"""Exchange rates and currency conversion.""" from __future__ import annotations import datetime as dt from bisect import bisect_right from decimal import Decimal from typing import Dict, List, Tuple, Union from .money import Money, minor_units from .rounding import round_decimal class MissingRate(LookupError): """Raised when no rate is known for a currency on a date.""" class RateTable: """Rates quoted against a base currency: units of currency per one unit of base.""" def __init__(self, base: str = "EUR") -> None: self.base = base.upper() self._rates: Dict[str, List[Tuple[dt.date, Decimal]]] = {} def set_rate(self, currency: str, rate: Union[str, int, Decimal], on: dt.date) -> None: currency = currency.upper() if currency == self.base: raise ValueError("the base currency always has rate 1") value = Decimal(rate) if value <= 0: raise ValueError("rate must be positive") series = [entry for entry in self._rates.get(currency, []) if entry[0] != on] series.append((on, value)) series.sort() self._rates[currency] = series def rate(self, currency: str, on: dt.date) -> Decimal: """The most recent rate on or before ``on``.""" currency = currency.upper() if currency == self.base: return Decimal(1) series = self._rates.get(currency) if not series: raise MissingRate("no rate for %s" % currency) index = bisect_right([entry[0] for entry in series], on) if index == 0: raise MissingRate("no %s rate on or before %s" % (currency, on.isoformat())) return series[index - 1][1] def cross_rate(self, source: str, target: str, on: dt.date) -> Decimal: return self.rate(target, on) / self.rate(source, on) def convert(self, money: Money, target: str, on: dt.date) -> Money: """Convert via the base currency, rounding half-even to the target's minor unit.""" target = target.upper() if money.currency == target: return money in_base = money.amount / self.rate(money.currency, on) converted = in_base * self.rate(target, on) return Money(round_decimal(converted, minor_units(target)), target)