diff --git a/application/forecast.py b/application/forecast.py index 05183d9..2115da4 100644 --- a/application/forecast.py +++ b/application/forecast.py @@ -26,20 +26,19 @@ class ForecastService: for account in self.model.accounts: monthly = self._project_account(account, months) for m in range(months): - results.append({ - "account": account.name, - "month": m + 1, - "balance": monthly[m]["balance"], - "income": monthly[m]["income"], - "expenses": monthly[m]["expenses"], - }) + results.append( + { + "account": account.name, + "month": m + 1, + "balance": monthly[m]["balance"], + "income": monthly[m]["income"], + "expenses": monthly[m]["expenses"], + } + ) # Asset growth — once per month, distributed across accounts proportionally for m in range(months): - total_growth = sum( - a.value * a.growth_rate / _HUNDRED / _TWELVE - for a in self.model.assets - ) + total_growth = sum(a.value * a.growth_rate / _HUNDRED / _TWELVE for a in 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: @@ -77,11 +76,13 @@ class ForecastService: balance = balance + income - expenses - monthly.append({ - "balance": _q(balance), - "income": _q(income), - "expenses": _q(expenses), - }) + monthly.append( + { + "balance": _q(balance), + "income": _q(income), + "expenses": _q(expenses), + } + ) return monthly def _liability_cost(self, account: Account) -> Decimal: diff --git a/application/repositories/model_repository.py b/application/repositories/model_repository.py index af3d448..9cb1a0d 100644 --- a/application/repositories/model_repository.py +++ b/application/repositories/model_repository.py @@ -3,6 +3,7 @@ Определяет контракт: load(path) -> FinancialModel, save(model, path) -> None. Реализации: JsonFileRepository, ExcelRepository. """ + from __future__ import annotations from pathlib import Path diff --git a/application/scenarios.py b/application/scenarios.py index 3c6e2eb..2bdd2a0 100644 --- a/application/scenarios.py +++ b/application/scenarios.py @@ -83,9 +83,6 @@ class ScenarioService: income_multiplier=to_d(income_mult), expense_multiplier=to_d(expense_mult), growth_multiplier=to_d(growth_mult), - description=( - f"What-if: income x{income_mult}, " - f"expense x{expense_mult}, growth x{growth_mult}" - ), + description=(f"What-if: income x{income_mult}, expense x{expense_mult}, growth x{growth_mult}"), ) return self.apply(scenario, months) diff --git a/domain/model.py b/domain/model.py index e242215..29aa755 100644 --- a/domain/model.py +++ b/domain/model.py @@ -25,9 +25,7 @@ class FinancialModel(BaseModel): assets: list[Asset] = Field(default_factory=list) liabilities: list[Liability] = Field(default_factory=list) scenarios: list[ForecastScenario] = Field(default_factory=list) - exchange_rates: list[ExchangeRate] = Field( - default_factory=lambda: [r.model_copy() for r in DEFAULT_RATES] - ) + exchange_rates: list[ExchangeRate] = Field(default_factory=lambda: [r.model_copy() for r in DEFAULT_RATES]) def to_dict(self) -> dict: """Сериализация в dict с version и UUID-as-str (для JSON).""" diff --git a/infrastructure/cli/app.py b/infrastructure/cli/app.py index 7194263..e510b8a 100644 --- a/infrastructure/cli/app.py +++ b/infrastructure/cli/app.py @@ -1,4 +1,5 @@ """Entry point приложения cf. Регистрирует все команды.""" + import sys import typer diff --git a/infrastructure/cli/commands/analyze.py b/infrastructure/cli/commands/analyze.py index f4f6966..23f6acd 100644 --- a/infrastructure/cli/commands/analyze.py +++ b/infrastructure/cli/commands/analyze.py @@ -1,4 +1,5 @@ """cf analyze — AI-анализ финансовой модели (заглушка).""" + import typer from infrastructure.cli.i18n import t diff --git a/infrastructure/cli/commands/compare.py b/infrastructure/cli/commands/compare.py index 70edf45..7195ba3 100644 --- a/infrastructure/cli/commands/compare.py +++ b/infrastructure/cli/commands/compare.py @@ -1,4 +1,5 @@ """cf compare — сравнить все сценарии.""" + import typer from rich.table import Table diff --git a/infrastructure/cli/commands/config_cmd.py b/infrastructure/cli/commands/config_cmd.py index 7b7297b..7942a4a 100644 --- a/infrastructure/cli/commands/config_cmd.py +++ b/infrastructure/cli/commands/config_cmd.py @@ -1,4 +1,5 @@ """cf config — подкоманды для редактирования модели (базовая валюта, счета, транзакции, ...).""" + import typer from rich.table import Table @@ -52,11 +53,13 @@ def rate_set( if existing: existing[0].rate = rate else: - model.exchange_rates.append(ExchangeRate( - from_currency=fc, - to_currency=tc, - rate=rate, - )) + model.exchange_rates.append( + ExchangeRate( + from_currency=fc, + to_currency=tc, + rate=rate, + ) + ) save_model(model) console.print(f"[green]{t('global.ok')}[/green] {t('cmd.config.rate_set.ok', fc=fc, tc=tc, rate=rate)}") @@ -86,10 +89,7 @@ def rate_remove( model = load_model() fc, tc = from_currency.upper(), to_currency.upper() initial = len(model.exchange_rates) - model.exchange_rates = [ - r for r in model.exchange_rates - if not (r.from_currency == fc and r.to_currency == tc) - ] + model.exchange_rates = [r for r in model.exchange_rates if not (r.from_currency == fc and r.to_currency == tc)] if len(model.exchange_rates) < initial: save_model(model) console.print(f"[green]{t('global.ok')}[/green] {t('cmd.config.rate_remove.ok', fc=fc, tc=tc)}") @@ -143,10 +143,7 @@ def account_remove( """Удалить счёт по ID или названию""" model = load_model() initial = len(model.accounts) - model.accounts = [ - a for a in model.accounts - if str(a.id) != identifier and a.name != identifier - ] + model.accounts = [a for a in model.accounts if str(a.id) != identifier and a.name != identifier] if len(model.accounts) < initial: save_model(model) console.print(f"[green]{t('global.ok')}[/green] {t('cmd.config.account_remove.ok', id=identifier)}") @@ -204,12 +201,14 @@ def transaction_list() -> None: table.add_column(t("table.transactions.col.description")) for tx in model.transactions: account_name = _account_name(model, tx.account) - amount_str = CurrencyConverter.format_money( - tx.amount, _account_currency(model, tx.account) - ) + amount_str = CurrencyConverter.format_money(tx.amount, _account_currency(model, tx.account)) table.add_row( - str(tx.id)[:8], tx.date, account_name, tx.category, - amount_str, tx.description, + str(tx.id)[:8], + tx.date, + account_name, + tx.category, + amount_str, + tx.description, ) console.print(table) @@ -244,8 +243,11 @@ def recurring_add( """Добавить регулярный платёж""" model = load_model() rc = RecurringCashflow( - start_date=start_date or "", end_date=end_date or "", - frequency=frequency, amount=amount, category=category, + start_date=start_date or "", + end_date=end_date or "", + frequency=frequency, + amount=amount, + category=category, ) model.recurring.append(rc) save_model(model) @@ -334,10 +336,7 @@ def asset_remove( """Удалить актив по ID или названию""" model = load_model() initial = len(model.assets) - model.assets = [ - a for a in model.assets - if str(a.id) != identifier and a.name != identifier - ] + model.assets = [a for a in model.assets if str(a.id) != identifier and a.name != identifier] if len(model.assets) < initial: save_model(model) console.print(f"[green]{t('global.ok')}[/green] {t('cmd.config.asset_remove.ok', id=identifier)}") @@ -392,10 +391,7 @@ def liability_remove( """Удалить обязательство по ID или названию""" model = load_model() initial = len(model.liabilities) - model.liabilities = [ - li for li in model.liabilities - if str(li.id) != identifier and li.name != identifier - ] + model.liabilities = [li for li in model.liabilities if str(li.id) != identifier and li.name != identifier] if len(model.liabilities) < initial: save_model(model) console.print(f"[green]{t('global.ok')}[/green] {t('cmd.config.liability_remove.ok', id=identifier)}") diff --git a/infrastructure/cli/commands/export_xlsx.py b/infrastructure/cli/commands/export_xlsx.py index b2ff792..2d30c93 100644 --- a/infrastructure/cli/commands/export_xlsx.py +++ b/infrastructure/cli/commands/export_xlsx.py @@ -1,4 +1,5 @@ """cf export-xlsx — экспорт модели в Excel.""" + import typer from infrastructure.cli.i18n import t diff --git a/infrastructure/cli/commands/forecast.py b/infrastructure/cli/commands/forecast.py index 84bfeae..00e82f5 100644 --- a/infrastructure/cli/commands/forecast.py +++ b/infrastructure/cli/commands/forecast.py @@ -1,4 +1,5 @@ """cf forecast — прогноз денежных потоков.""" + import typer from rich.table import Table @@ -37,7 +38,8 @@ def forecast( for r in results: table.add_row( - r["account"], str(r["month"]), + r["account"], + str(r["month"]), fmt_amount(convert_value(converter, r["balance"], base_curr, target_curr), target_curr, symbol), fmt_amount(convert_value(converter, r["income"], base_curr, target_curr), target_curr, symbol), fmt_amount(convert_value(converter, r["expenses"], base_curr, target_curr), target_curr, symbol), @@ -47,7 +49,11 @@ def forecast( cb = convert_value(converter, summary["total_balance"], base_curr, target_curr) ci = convert_value(converter, summary["total_income"], base_curr, target_curr) ce = convert_value(converter, summary["total_expenses"], base_curr, target_curr) - console.print(t("cmd.forecast.total", - balance=fmt_amount(cb, target_curr, symbol), - income=fmt_amount(ci, target_curr, symbol), - expenses=fmt_amount(ce, target_curr, symbol))) + console.print( + t( + "cmd.forecast.total", + balance=fmt_amount(cb, target_curr, symbol), + income=fmt_amount(ci, target_curr, symbol), + expenses=fmt_amount(ce, target_curr, symbol), + ) + ) diff --git a/infrastructure/cli/commands/import_xlsx.py b/infrastructure/cli/commands/import_xlsx.py index 707eab8..05cc3f5 100644 --- a/infrastructure/cli/commands/import_xlsx.py +++ b/infrastructure/cli/commands/import_xlsx.py @@ -1,4 +1,5 @@ """cf import-xlsx — импорт данных из Excel.""" + import typer from infrastructure.cli.i18n import t @@ -15,12 +16,16 @@ def import_xlsx( try: model = _repo.load(path) save_model(model) - console.print(t("cmd.import.ok", - accounts=len(model.accounts), - transactions=len(model.transactions), - recurring=len(model.recurring), - assets=len(model.assets), - liabilities=len(model.liabilities))) + console.print( + t( + "cmd.import.ok", + accounts=len(model.accounts), + transactions=len(model.transactions), + recurring=len(model.recurring), + assets=len(model.assets), + liabilities=len(model.liabilities), + ) + ) console.print(t("cmd.import.base_currency", currency=model.base_currency)) except ExcelRepositoryError as e: console.print(f"[red]{t('cmd.import.err', error=str(e))}[/red]") diff --git a/infrastructure/cli/commands/info.py b/infrastructure/cli/commands/info.py index 8c77730..3e8dd79 100644 --- a/infrastructure/cli/commands/info.py +++ b/infrastructure/cli/commands/info.py @@ -1,4 +1,5 @@ """cf info — сводка всей финансовой модели.""" + from rich.table import Table from domain import CurrencyConverter diff --git a/infrastructure/cli/commands/scenario.py b/infrastructure/cli/commands/scenario.py index de9dc6d..96b53d1 100644 --- a/infrastructure/cli/commands/scenario.py +++ b/infrastructure/cli/commands/scenario.py @@ -1,4 +1,5 @@ """cf scenario — применить именованный сценарий (baseline/optimistic/pessimistic).""" + import typer from application.scenarios import DEFAULT_SCENARIOS diff --git a/infrastructure/cli/commands/whatif.py b/infrastructure/cli/commands/whatif.py index 5ee9f6d..93642b6 100644 --- a/infrastructure/cli/commands/whatif.py +++ b/infrastructure/cli/commands/whatif.py @@ -1,4 +1,5 @@ """cf whatif — what-if анализ с произвольными множителями.""" + import typer from infrastructure.cli.i18n import t diff --git a/infrastructure/cli/i18n.py b/infrastructure/cli/i18n.py index 9f46d4f..32dc710 100644 --- a/infrastructure/cli/i18n.py +++ b/infrastructure/cli/i18n.py @@ -68,9 +68,11 @@ _r("cmd.compare.col.scenario", "Сценарий") _r("cmd.import.help", "Импорт данных из Excel") _r("cmd.import.arg.path", "Путь к .xlsx файлу") -_r("cmd.import.ok", - "Импортировано: {accounts} счетов, {transactions} транзакций, " - "{recurring} регулярных платежей, {assets} активов, {liabilities} обязательств") +_r( + "cmd.import.ok", + "Импортировано: {accounts} счетов, {transactions} транзакций, " + "{recurring} регулярных платежей, {assets} активов, {liabilities} обязательств", +) _r("cmd.import.base_currency", "Базовая валюта: {currency}") _r("cmd.import.err", "Ошибка импорта: {error}") @@ -254,56 +256,65 @@ _r("global.ok", "OK") # ── prompts ─────────────────────────────────────────────────── -_r("prompt.analyze", ( - "Ты — финансовый AI-ассистент. Проанализируй финансовую модель пользователя.\n" - "\n" - "### Модель (JSON):\n" - "{model_json}\n" - "\n" - "### Прогноз на {months} месяцев:\n" - "{forecast_json}\n" - "\n" - "### Валюта:\n" - "Базовая валюта модели: {base_currency}\n" - "Отображаемая валюта: {display_currency}\n" - "\n" - "Дай анализ по пунктам:\n" - "1. Общее финансовое состояние\n" - "2. Тренд денежного потока (рост/падение)\n" - "3. Достаточность ликвидности\n" - "4. Рекомендации по улучшению" -)) +_r( + "prompt.analyze", + ( + "Ты — финансовый AI-ассистент. Проанализируй финансовую модель пользователя.\n" + "\n" + "### Модель (JSON):\n" + "{model_json}\n" + "\n" + "### Прогноз на {months} месяцев:\n" + "{forecast_json}\n" + "\n" + "### Валюта:\n" + "Базовая валюта модели: {base_currency}\n" + "Отображаемая валюта: {display_currency}\n" + "\n" + "Дай анализ по пунктам:\n" + "1. Общее финансовое состояние\n" + "2. Тренд денежного потока (рост/падение)\n" + "3. Достаточность ликвидности\n" + "4. Рекомендации по улучшению" + ), +) -_r("prompt.advice", ( - "Ты — финансовый AI-ассистент. Дай персональные рекомендации.\n" - "\n" - "### Модель:\n" - "{model_json}\n" - "\n" - "### Прогноз:\n" - "{forecast_json}\n" - "\n" - "### Валюта:\n" - "Базовая валюта модели: {base_currency}\n" - "Отображаемая валюта: {display_currency}\n" - "\n" - "Вопрос пользователя: {question}\n" - "\n" - "Ответь как опытный финансовый консультант." -)) +_r( + "prompt.advice", + ( + "Ты — финансовый AI-ассистент. Дай персональные рекомендации.\n" + "\n" + "### Модель:\n" + "{model_json}\n" + "\n" + "### Прогноз:\n" + "{forecast_json}\n" + "\n" + "### Валюта:\n" + "Базовая валюта модели: {base_currency}\n" + "Отображаемая валюта: {display_currency}\n" + "\n" + "Вопрос пользователя: {question}\n" + "\n" + "Ответь как опытный финансовый консультант." + ), +) -_r("prompt.scenario_comparison", ( - "Ты — финансовый AI-ассистент. Сравни сценарии прогноза.\n" - "\n" - "### Результаты сценариев:\n" - "{scenarios_json}\n" - "\n" - "### Валюта:\n" - "Базовая валюта модели: {base_currency}\n" - "Отображаемая валюта: {display_currency}\n" - "\n" - "Дай рекомендацию: какой сценарий наиболее вероятен и почему." -)) +_r( + "prompt.scenario_comparison", + ( + "Ты — финансовый AI-ассистент. Сравни сценарии прогноза.\n" + "\n" + "### Результаты сценариев:\n" + "{scenarios_json}\n" + "\n" + "### Валюта:\n" + "Базовая валюта модели: {base_currency}\n" + "Отображаемая валюта: {display_currency}\n" + "\n" + "Дай рекомендацию: какой сценарий наиболее вероятен и почему." + ), +) _current_lang = "ru" diff --git a/infrastructure/cli/paths.py b/infrastructure/cli/paths.py index d172ee9..28a67ef 100644 --- a/infrastructure/cli/paths.py +++ b/infrastructure/cli/paths.py @@ -1,4 +1,5 @@ """Пути к данным и экспортам.""" + from pathlib import Path DATA_DIR: Path = Path("data") diff --git a/infrastructure/cli/services.py b/infrastructure/cli/services.py index 0a2f61e..2dbbf9f 100644 --- a/infrastructure/cli/services.py +++ b/infrastructure/cli/services.py @@ -1,4 +1,5 @@ """Composition root + общие хелперы для CLI-команд.""" + from __future__ import annotations from decimal import Decimal @@ -34,9 +35,7 @@ def build_services( converter = CurrencyConverter(model.exchange_rates) forecast_service = ForecastService(model) scenario_service = ScenarioService(model) - assistant_service = AssistantService( - model, forecast_service=forecast_service, converter=converter - ) + assistant_service = AssistantService(model, forecast_service=forecast_service, converter=converter) return forecast_service, scenario_service, assistant_service, converter @@ -47,9 +46,7 @@ def resolve_currency(model: FinancialModel, currency: str | None) -> tuple[str, return target, symbol -def convert_value( - converter: CurrencyConverter, amount: Decimal, from_curr: str, to_curr: str -) -> Decimal: +def convert_value(converter: CurrencyConverter, amount: Decimal, from_curr: str, to_curr: str) -> Decimal: if to_curr == from_curr: return amount return converter.convert(amount, from_curr, to_curr) diff --git a/infrastructure/repositories/excel_repository.py b/infrastructure/repositories/excel_repository.py index 065c27e..757be43 100644 --- a/infrastructure/repositories/excel_repository.py +++ b/infrastructure/repositories/excel_repository.py @@ -1,4 +1,5 @@ """ExcelRepository — хранит FinancialModel в .xlsx (5 листов + ModelInfo).""" + from pathlib import Path from uuid import UUID @@ -107,8 +108,7 @@ class ExcelRepository(ModelRepository): ws.append(config["fields"]) for item in items: row = [ - str(getattr(item, f)) if isinstance(getattr(item, f), UUID) - else getattr(item, f) + str(getattr(item, f)) if isinstance(getattr(item, f), UUID) else getattr(item, f) for f in config["fields"] ] ws.append(row) diff --git a/infrastructure/repositories/json_file_repository.py b/infrastructure/repositories/json_file_repository.py index 34479ae..79d5593 100644 --- a/infrastructure/repositories/json_file_repository.py +++ b/infrastructure/repositories/json_file_repository.py @@ -1,4 +1,5 @@ """JsonFileRepository — хранит FinancialModel в .json (включая version).""" + import json from pathlib import Path diff --git a/tests/conftest.py b/tests/conftest.py index 4226bbb..eb43acd 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -25,24 +25,32 @@ def sample_model() -> FinancialModel: ], transactions=[ Transaction( - date="2026-01-01", account=str(acc_id), - category="income", amount=3000.0, + date="2026-01-01", + account=str(acc_id), + category="income", + amount=3000.0, description="Зарплата", ), Transaction( - date="2026-01-05", account=str(acc_id), - category="rent", amount=-1200.0, + date="2026-01-05", + account=str(acc_id), + category="rent", + amount=-1200.0, description="Аренда", ), ], recurring=[ RecurringCashflow( - start_date="2026-01-01", frequency="monthly", - amount=500.0, category="income", + start_date="2026-01-01", + frequency="monthly", + amount=500.0, + category="income", ), RecurringCashflow( - start_date="2026-01-01", frequency="monthly", - amount=-200.0, category="subscription", + start_date="2026-01-01", + frequency="monthly", + amount=-200.0, + category="subscription", ), ], assets=[ diff --git a/tests/test_cli.py b/tests/test_cli.py index beec93a..1728b7e 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -86,13 +86,21 @@ class TestCli: runner.invoke(app, ["init"]) runner.invoke(app, ["config", "account-add", "--name", "Счёт", "--balance", "0"]) - add = runner.invoke(app, [ - "config", "transaction-add", - "--account", "Счёт", - "--amount", "5000", - "--category", "income", - "--description", "Зарплата", - ]) + add = runner.invoke( + app, + [ + "config", + "transaction-add", + "--account", + "Счёт", + "--amount", + "5000", + "--category", + "income", + "--description", + "Зарплата", + ], + ) assert add.exit_code == 0 assert "доход" in add.stdout @@ -103,12 +111,19 @@ class TestCli: _cleanup() runner.invoke(app, ["init"]) - add = runner.invoke(app, [ - "config", "asset-add", - "--name", "Квартира", - "--value", "5000000", - "--growth", "5", - ]) + add = runner.invoke( + app, + [ + "config", + "asset-add", + "--name", + "Квартира", + "--value", + "5000000", + "--growth", + "5", + ], + ) assert add.exit_code == 0 assert "Квартира" in add.stdout @@ -119,13 +134,21 @@ class TestCli: _cleanup() runner.invoke(app, ["init"]) - add = runner.invoke(app, [ - "config", "liability-add", - "--name", "Кредит", - "--balance", "100000", - "--interest", "10", - "--payment", "5000", - ]) + add = runner.invoke( + app, + [ + "config", + "liability-add", + "--name", + "Кредит", + "--balance", + "100000", + "--interest", + "10", + "--payment", + "5000", + ], + ) assert add.exit_code == 0 assert "Кредит" in add.stdout @@ -133,12 +156,19 @@ class TestCli: _cleanup() runner.invoke(app, ["init"]) - add = runner.invoke(app, [ - "config", "recurring-add", - "--amount", "-500", - "--category", "аренда", - "--frequency", "monthly", - ]) + add = runner.invoke( + app, + [ + "config", + "recurring-add", + "--amount", + "-500", + "--category", + "аренда", + "--frequency", + "monthly", + ], + ) assert add.exit_code == 0 lst = runner.invoke(app, ["config", "recurring-list"]) @@ -160,8 +190,7 @@ class TestCli: runner.invoke(app, ["init"]) acc_args = ["config", "account-add", "--name", "Основной", "--balance", "50000"] runner.invoke(app, acc_args) - asset_args = ["config", "asset-add", "--name", "Акции", - "--value", "100000", "--growth", "8.0"] + asset_args = ["config", "asset-add", "--name", "Акции", "--value", "100000", "--growth", "8.0"] runner.invoke(app, asset_args) result = runner.invoke(app, ["info"]) diff --git a/tests/test_cli_contract.py b/tests/test_cli_contract.py index 899b862..299f119 100644 --- a/tests/test_cli_contract.py +++ b/tests/test_cli_contract.py @@ -6,6 +6,7 @@ CLI (D3 — удаление мёртвых typer.Typer(), D25 — разбие на пакет): если набор изменился, поведение CLI изменилось без согласования — тест обязан упасть. """ + import typer from typer.main import get_command diff --git a/tests/test_model.py b/tests/test_model.py index 587d41b..39800c2 100644 --- a/tests/test_model.py +++ b/tests/test_model.py @@ -60,6 +60,7 @@ class TestFinancialModel: def test_base_currency_backward_compat(self, tmp_path: Path): import json + p = tmp_path / "legacy.json" with open(p, "w") as f: json.dump({"accounts": []}, f) diff --git a/tests/test_repositories.py b/tests/test_repositories.py index a554158..ec1de3b 100644 --- a/tests/test_repositories.py +++ b/tests/test_repositories.py @@ -29,6 +29,7 @@ class TestJsonFileRepository: p = tmp_path / "v.json" repo.save(model, p) import json + with open(p) as f: data = json.load(f) assert data["version"] == 1 @@ -46,9 +47,7 @@ class TestJsonFileRepository: def test_decimal_preserved(self, tmp_path: Path): repo = JsonFileRepository() - model = FinancialModel( - assets=[Asset(name="Stocks", value=Decimal("12345.67"), growth_rate=Decimal("8.5"))] - ) + model = FinancialModel(assets=[Asset(name="Stocks", value=Decimal("12345.67"), growth_rate=Decimal("8.5"))]) p = tmp_path / "decimal.json" repo.save(model, p) loaded = repo.load(p)