D34: валюты в прогнозе — конвертация по курсам и валюта вывода

- расчёт ведётся в базовой валюте модели: баланс счёта переводится из
  валюты счёта, операция — из своей валюты (пусто = валюта счёта),
  актив и обязательство — из своей (пусто = базовая);
- нет курса — не падение, а предупреждение: сумма не попадает в прогноз,
  но пользователь видит, чего не хватает (нет курса USD → RUB);
- FinancialModel.display_currency — валюта вывода по умолчанию;
  новая команда cf config display-currency; cf forecast/scenario/compare
  печатают предупреждения расчёта; cf info показывает обе валюты и
  суммы в валюте их владельца;
- рост активов при нулевых балансах теперь делится поровну — раньше он
  делился по доле от единицы и просто исчезал.

Тесты: 296 → 302 (класс TestForecastCurrency: конвертация баланса,
операции, актива, регулярного платежа, предупреждение об отсутствии
курса).
This commit is contained in:
oqyude committed 2026-11-15 05:59:59 +03:00
1 parent 289f039ed8
commit 885a91f15f
14 files changed
+300 -45

No files matched your search

+109 -29
View File
@@ -2,7 +2,8 @@ from copy import deepcopy
from datetime import date, timedelta
from decimal import ROUND_HALF_UP, Decimal
from domain import Account, FinancialModel, Transaction
from domain import Account, FinancialModel, RecurringCashflow
from domain.currency import CurrencyConverter, CurrencyError
from domain.recurrence import parse_date
@@ -67,36 +68,77 @@ class ForecastService:
Транзакции раскладываются по датам (D33): операция из прошлого уже учтена
в балансе счёта и в прогноз не попадает, операция будущего попадает в
месяц своей даты. Регулярные платежи считаются по календарю (D32).
Валюты (D34): расчёт ведётся в базовой валюте модели. Баланс счёта —
в валюте счёта, операция — в своей валюте (пусто = валюта счёта или
базовая). Нет курса — не ошибка, а предупреждение: сумма не попадает
в прогноз, но пользователь видит, чего не хватает.
"""
def __init__(self, model: FinancialModel, start_month: str | date | None = None):
def __init__(
self,
model: FinancialModel,
start_month: str | date | None = None,
converter: CurrencyConverter | None = None,
):
self.model = deepcopy(model)
self.start_month = _first_of_month(start_month)
# Предупреждения расчёта (D33): операция без счёта, счёт не найден.
self._converter = converter or CurrencyConverter(self.model.exchange_rates)
# Предупреждения расчёта: счёт не найден, нет курса валюты.
self.warnings: list[str] = []
@property
def converter(self) -> CurrencyConverter:
return self._converter
def forecast_cashflow(self, months: int = 12) -> list[dict]:
if months < 1:
raise ForecastError("Число месяцев должно быть не меньше 1")
self.warnings = []
base = self.model.base_currency
# Локальное состояние расчёта — вместо мутации модели (D14).
# `liability_balances` — текущий остаток по каждому обязательству,
# `asset_values` — текущая стоимость каждого актива.
liability_balances = [li.balance for li in self.model.liabilities]
asset_values = [a.value for a in self.model.assets]
# Локальное состояние расчёта — вместо мутации модели (D14). Все
# суммы переводятся в базовую валюту: `liability_balances` — текущий
# остаток по каждому обязательству, `asset_values` — текущая стоимость
# каждого актива.
liability_balances = [
self._to_base(li.balance, li.currency or base, f"обязательство «{li.name}»") or _ZERO
for li in self.model.liabilities
]
asset_values = [
self._to_base(a.value, a.currency or base, f"актив «{a.name}»") or _ZERO
for a in self.model.assets
]
account_balances = [
self._to_base(account.balance, account.currency or base, f"счёт «{account.name}»") or _ZERO
for account in self.model.accounts
]
# Транзакции, разложенные по счетам и месяцам сетки (D33).
transactions_by_account = self._group_transactions(months)
transactions_by_account = self._group_transactions(months, base)
# Регулярные платежи — сумма списания переводится в базовую валюту
# один раз, а не на каждый месяц (D34).
recurring_base: list[tuple[RecurringCashflow, Decimal]] = []
for r in self.model.recurring:
amount = self._to_base(
r.amount,
r.currency or base,
f"регулярный платёж «{r.category or r.id}»",
)
if amount is None:
continue
recurring_base.append((r, amount))
results = []
for index, account in enumerate(self.model.accounts):
monthly = self._project_account(
account,
account_balances[index],
months,
liability_balances,
transactions_by_account.get(index, []),
recurring_base,
)
for m in range(months):
results.append(
@@ -115,11 +157,18 @@ class ForecastService:
value * a.growth_rate / _HUNDRED / _TWELVE for value, a in zip(asset_values, self.model.assets)
)
month_rows = [r for r in results if r["month"] == m + 1]
total_bal = sum(r["balance"] for r in month_rows) or _ONE
for r in month_rows:
share = r["balance"] / total_bal
r["income"] = _q(r["income"] + total_growth * share)
r["balance"] = _q(r["balance"] + total_growth * share)
total_bal = sum(r["balance"] for r in month_rows)
if total_bal > 0:
shares = [r["balance"] / total_bal for r in month_rows]
elif month_rows:
# Балансов нет — рост активов делим поровну. Раньше делили по
# доле от единицы, и при нулевых балансах рост просто исчезал.
shares = [_ONE / len(month_rows)] * len(month_rows)
else:
shares = []
for row, share in zip(month_rows, shares):
row["income"] = _q(row["income"] + total_growth * share)
row["balance"] = _q(row["balance"] + total_growth * share)
# Compound asset values for next month (локально, модель не меняется)
asset_values = [
@@ -128,15 +177,38 @@ class ForecastService:
return results
# -- валюты -------------------------------------------------------------
def _to_base(self, amount: Decimal, currency: str, subject: str = "") -> Decimal | None:
"""Привести сумму к базовой валюте модели. ``None`` — курса нет.
Отсутствующий курс не роняет прогноз: сумма не попадает в расчёт,
но в `warnings` появляется понятное сообщение — что именно не учтено.
"""
base = self.model.base_currency
source = (currency or base).upper()
if source == base.upper():
return amount
try:
return self._converter.convert(amount, source, base)
except CurrencyError:
prefix = f"{subject}: " if subject else ""
self.warnings.append(
f"{prefix}нет курса {source} → {base}, сумма {amount} {source} не учтена в прогнозе"
)
return None
# -- транзакции ---------------------------------------------------------
def _group_transactions(self, months: int) -> dict[int, list[tuple[int, Transaction]]]:
def _group_transactions(
self, months: int, base: str
) -> dict[int, list[tuple[int, Decimal]]]:
"""Разложить транзакции по счетам и месяцам сетки прогноза (D33).
Возвращает словарь «индекс счёта → список (месяц сетки, транзакция)».
Возвращает словарь «индекс счёта → список (месяц сетки, сумма)».
Транзакции из прошлого отбрасываются: они уже учтены в балансе счёта.
"""
grouped: dict[int, list[tuple[int, Transaction]]] = {}
grouped: dict[int, list[tuple[int, Decimal]]] = {}
for t in self.model.transactions:
account_index = self._account_index(t.account)
if account_index is None:
@@ -154,7 +226,13 @@ class ForecastService:
# За пределами горизонта прогноза.
continue
grouped.setdefault(account_index, []).append((month_index, t))
account = self.model.accounts[account_index]
currency = t.currency or account.currency or base
amount = self._to_base(t.amount, currency, f"транзакция «{t.description or t.category or t.id}»")
if amount is None:
continue
grouped.setdefault(account_index, []).append((month_index, amount))
return grouped
def _transaction_month(self, value: str) -> int | None:
@@ -184,12 +262,13 @@ class ForecastService:
def _project_account(
self,
account: Account,
start_balance: Decimal,
months: int,
liability_balances: list[Decimal],
transactions: list[tuple[int, Transaction]],
transactions: list[tuple[int, Decimal]],
recurring_base: list[tuple[RecurringCashflow, Decimal]],
) -> list[dict]:
balance = account.balance
balance = start_balance
monthly = []
for m in range(months):
income = _ZERO
@@ -203,26 +282,27 @@ class ForecastService:
# D33: транзакция попадает в месяц СВОЕЙ даты, а не в каждый
# месяц подряд. Транзакции из прошлого уже учтены в балансе
# счёта — в прогноз они не попадают.
for month_index, t in transactions:
for month_index, amount in transactions:
if month_index != m:
continue
if t.amount > 0:
income += t.amount
if amount > 0:
income += amount
else:
expenses += abs(t.amount)
expenses += abs(amount)
for r in self.model.recurring:
for r, unit_amount in recurring_base:
# D32: платёж раскладывается по календарю — сколько и каких
# списаний выпадает в этот месяц, решает сам календарь
# (daily/weekly/monthly/yearly), а не делитель периода.
share = r.amount_in_month(
count = r.occurrences_in_month(
month_start.isoformat(),
month_end.isoformat(),
default_start=self.start_month.isoformat(),
)
if share == 0:
if count == 0:
continue
share = unit_amount * count
# D16a: классификация только по знаку; `category` — подпись,
# а не правило (то же правило в ScenarioService.apply/what_if).
if share > 0:
+11 -2
View File
@@ -4,6 +4,7 @@ from decimal import Decimal
from application.forecast import ForecastService
from domain import FinancialModel, ForecastScenario
from domain.currency import CurrencyConverter
DEFAULT_SCENARIOS = {
"baseline": ForecastScenario(
@@ -31,10 +32,17 @@ DEFAULT_SCENARIOS = {
class ScenarioService:
def __init__(self, model: FinancialModel, start_month: str | date | None = None):
def __init__(
self,
model: FinancialModel,
start_month: str | date | None = None,
converter: CurrencyConverter | None = None,
):
self.model = deepcopy(model)
# Месяц старта сетки прогноза (D16b) — тот же для всех сценариев.
self.start_month = start_month
# Курсы для перевода сумм в базовую валюту (D34).
self._converter = converter
def apply(self, scenario: ForecastScenario, months: int = 12) -> dict:
model = deepcopy(self.model)
@@ -56,10 +64,11 @@ class ScenarioService:
for a in model.assets:
a.growth_rate = a.growth_rate * scenario.growth_multiplier
service = ForecastService(model, start_month=self.start_month)
service = ForecastService(model, start_month=self.start_month, converter=self._converter)
result = service.summary(months)
result["scenario"] = scenario.name
result["scenario_description"] = scenario.description
result["warnings"] = list(service.warnings)
return result
def compare(self, months: int = 12) -> dict: