fix(currency): кросс-курс через промежуточную валюту (Н3)
CurrencyConverter знал только прямые пары и обратные к ним. ЦБ РФ публикует курсы к рублю, поэтому при базовой валюте, отличной от RUB, перевод EUR → USD не находился: счёт молча выпадал из прогноза с предупреждением «нет курса», а модель обнулялась. get_rate теперь ищет кратчайший путь по графу известных курсов (BFS): прямая пара → обратная → кросс через любую валюту, для которой есть обе пары. Прямая пара по-прежнему имеет приоритет. Пример: USD→RUB = 80, EUR→RUB = 90, базовая валюта USD, счёт 100 EUR. Было: баланс 0.00, предупреждение «нет курса EUR → USD». Стало: баланс 112.50 USD, предупреждений нет. Refs: review/2026-11-29-review.md §2 Н3, §6 R3.
This commit is contained in:
1 parent
bdc90e15f5
commit
c887a1e3ff
3 files changed
+81
-3
No files matched your search
+37
-3
@@ -99,12 +99,46 @@ class CurrencyConverter:
|
|||||||
self._rates[(to_currency, from_currency)] = Decimal("1") / d
|
self._rates[(to_currency, from_currency)] = Decimal("1") / d
|
||||||
|
|
||||||
def get_rate(self, from_currency: str, to_currency: str) -> Decimal:
|
def get_rate(self, from_currency: str, to_currency: str) -> Decimal:
|
||||||
|
"""Курс пары: прямой, обратный или кросс-курс через промежуточную валюту.
|
||||||
|
|
||||||
|
ЦБ РФ публикует курсы всех валют к рублю, поэтому прямых пар между
|
||||||
|
не-рублёвыми валютами обычно нет. Без триангуляции модель с базовой
|
||||||
|
валютой, отличной от рубля, молча обнулялась (Н3): EUR → USD не
|
||||||
|
находился, хотя EUR → RUB и USD → RUB известны.
|
||||||
|
"""
|
||||||
if from_currency == to_currency:
|
if from_currency == to_currency:
|
||||||
return Decimal("1")
|
return Decimal("1")
|
||||||
try:
|
direct = self._rates.get((from_currency, to_currency))
|
||||||
return self._rates[(from_currency, to_currency)]
|
if direct is not None:
|
||||||
except KeyError:
|
return direct
|
||||||
|
path = self._shortest_path(from_currency, to_currency)
|
||||||
|
if path is None:
|
||||||
raise CurrencyError(f"Нет курса: {from_currency} → {to_currency}")
|
raise CurrencyError(f"Нет курса: {from_currency} → {to_currency}")
|
||||||
|
rate = Decimal("1")
|
||||||
|
for source, target in zip(path, path[1:]):
|
||||||
|
rate *= self._rates[(source, target)]
|
||||||
|
return rate
|
||||||
|
|
||||||
|
def _shortest_path(self, from_currency: str, to_currency: str) -> list[str] | None:
|
||||||
|
"""Кратчайший путь по графу известных курсов (BFS)."""
|
||||||
|
adjacency: dict[str, list[str]] = {}
|
||||||
|
for source, target in self._rates:
|
||||||
|
adjacency.setdefault(source, []).append(target)
|
||||||
|
queue = [from_currency]
|
||||||
|
previous: dict[str, str | None] = {from_currency: None}
|
||||||
|
while queue:
|
||||||
|
node = queue.pop(0)
|
||||||
|
for neighbour in adjacency.get(node, []):
|
||||||
|
if neighbour in previous:
|
||||||
|
continue
|
||||||
|
previous[neighbour] = node
|
||||||
|
if neighbour == to_currency:
|
||||||
|
path = [neighbour]
|
||||||
|
while previous[path[-1]] is not None:
|
||||||
|
path.append(previous[path[-1]])
|
||||||
|
return list(reversed(path))
|
||||||
|
queue.append(neighbour)
|
||||||
|
return None
|
||||||
|
|
||||||
def convert(
|
def convert(
|
||||||
self,
|
self,
|
||||||
|
|||||||
@@ -61,6 +61,33 @@ class TestCurrencyConverter:
|
|||||||
# На отображении округление по знакам валюты даёт те же 10.00.
|
# На отображении округление по знакам валюты даёт те же 10.00.
|
||||||
assert converter.format_money(result, "EUR") == "€10.00"
|
assert converter.format_money(result, "EUR") == "€10.00"
|
||||||
|
|
||||||
|
def test_cross_rate_through_rub(self):
|
||||||
|
# Н3: прямых пар между не-рублёвыми валютами нет, но обе известны к RUB.
|
||||||
|
converter = CurrencyConverter(
|
||||||
|
[
|
||||||
|
ExchangeRate(from_currency="USD", to_currency="RUB", rate=80),
|
||||||
|
ExchangeRate(from_currency="EUR", to_currency="RUB", rate=90),
|
||||||
|
]
|
||||||
|
)
|
||||||
|
assert converter.convert(100, "EUR", "USD") == Decimal("112.5")
|
||||||
|
# Обратный кросс-курс — бесконечная дробь; сравниваем после округления.
|
||||||
|
assert converter.convert(112.5, "USD", "EUR").quantize(Decimal("0.01")) == Decimal("100.00")
|
||||||
|
|
||||||
|
def test_direct_rate_wins_over_cross_rate(self):
|
||||||
|
converter = CurrencyConverter(
|
||||||
|
[
|
||||||
|
ExchangeRate(from_currency="USD", to_currency="RUB", rate=80),
|
||||||
|
ExchangeRate(from_currency="EUR", to_currency="RUB", rate=90),
|
||||||
|
ExchangeRate(from_currency="EUR", to_currency="USD", rate=Decimal("1.2")),
|
||||||
|
]
|
||||||
|
)
|
||||||
|
assert converter.get_rate("EUR", "USD") == Decimal("1.2")
|
||||||
|
|
||||||
|
def test_no_path_raises(self):
|
||||||
|
converter = CurrencyConverter([ExchangeRate(from_currency="USD", to_currency="RUB", rate=80)])
|
||||||
|
with pytest.raises(CurrencyError):
|
||||||
|
converter.convert(100, "EUR", "GBP")
|
||||||
|
|
||||||
def test_get_symbol(self, sample_converter):
|
def test_get_symbol(self, sample_converter):
|
||||||
assert sample_converter.get_symbol("USD") == "$"
|
assert sample_converter.get_symbol("USD") == "$"
|
||||||
assert sample_converter.get_symbol("RUB") == "₽"
|
assert sample_converter.get_symbol("RUB") == "₽"
|
||||||
|
|||||||
@@ -402,6 +402,23 @@ class TestForecastCurrency:
|
|||||||
assert service.warnings
|
assert service.warnings
|
||||||
assert "нет курса USD → EUR" in service.warnings[0]
|
assert "нет курса USD → EUR" in service.warnings[0]
|
||||||
|
|
||||||
|
def test_account_in_third_currency_is_converted_through_rub(self):
|
||||||
|
# Н3: базовая валюта USD, счёт в EUR; прямого курса EUR → USD нет,
|
||||||
|
# но обе валюты известны к рублю.
|
||||||
|
model = self._model(
|
||||||
|
base_currency="USD",
|
||||||
|
accounts=[Account(name="Евро", currency="EUR", balance=Decimal("100"))],
|
||||||
|
exchange_rates=[
|
||||||
|
ExchangeRate(from_currency="USD", to_currency="RUB", rate=Decimal("80")),
|
||||||
|
ExchangeRate(from_currency="EUR", to_currency="RUB", rate=Decimal("90")),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
service = ForecastService(model, start_month=self._GRID)
|
||||||
|
rows = service.forecast_cashflow(1)
|
||||||
|
# 100 EUR = 9000 RUB = 112.50 USD.
|
||||||
|
assert rows[0]["balance"] == Decimal("112.50")
|
||||||
|
assert service.warnings == []
|
||||||
|
|
||||||
def test_liability_payment_is_converted_to_base_currency(self):
|
def test_liability_payment_is_converted_to_base_currency(self):
|
||||||
# Н2: платёж в валюте обязательства переводится в базовую валюту так
|
# Н2: платёж в валюте обязательства переводится в базовую валюту так
|
||||||
# же, как остаток долга. Иначе 100 USD вычитались бы из 80 000 ₽.
|
# же, как остаток долга. Иначе 100 USD вычитались бы из 80 000 ₽.
|
||||||
|
|||||||
Reference in new issue
Block a user