- GET /{source_id} pro cnb, kb, csob, moneta, jt, mbank, ppf, trinity, fio, creditas
- jednotny tvar odpovedi s bezhotovostnimi kurzy za 1 jednotku meny
- parametr ?base pro ceny v jine mene nez CZK
- pole buy_sell_origin a middle_origin rikaji, co je stazene a co dopocitane
- pravidelne stahovani na pozadi, ukladani do JSON, priznak stale
- testy a dokumentace ve slozce documentation
49 lines
1.6 KiB
Python
49 lines
1.6 KiB
Python
"""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)
|