"""Converts rates from the CZK quotes published by the sources to another base currency.""" from app.models import Rate CZK = "CZK" # Prices of weak currencies in a strong base can be tiny, for example IDR in EUR is # around 0.00005, so this keeps more decimals than the CZK quotes need. CONVERTED_RATE_DECIMALS = 10 class BaseCurrencyNotAvailable(ValueError): """The source does not publish the requested base currency.""" def rebase_rates(rates: list[Rate], base: str) -> list[Rate]: """Goes through CZK, so the spread of both currencies is applied. The bank buying X in base B means: the client sells X for CZK at X.buy and then pays CZK for B at B.sell. Selling X in base B is the opposite direction. """ if base == CZK: return rates base_rate = next((rate for rate in rates if rate.currency == base), None) if base_rate is None: raise BaseCurrencyNotAvailable(base) czk_rate = Rate( currency=CZK, buy=1, sell=1, middle=1, buy_sell_origin="computed", middle_origin="computed", ) converted = [ Rate( currency=rate.currency, buy=round(rate.buy / base_rate.sell, CONVERTED_RATE_DECIMALS), sell=round(rate.sell / base_rate.buy, CONVERTED_RATE_DECIMALS), middle=round(rate.middle / base_rate.middle, CONVERTED_RATE_DECIMALS), buy_sell_origin="computed", middle_origin="computed", ) for rate in [*rates, czk_rate] if rate.currency != base ] return sorted(converted, key=lambda rate: rate.currency)