fire-planner/fire_planner/income_streams.py
Viktor Barzin 9cc781a8d6
All checks were successful
ci/woodpecker/push/woodpecker Pipeline was successful
fire-planner: ProjectionLab parity Wave 1 — tabbed shell, year stats, goals,
income streams, Sankey cashflow, progress overlay, settings sub-pages

Wave 1 (9 features across 4 streams):

Stream A — dashboard skeleton
  1.A.1 ScenarioShell with top tabs (Plan/Cash Flow/Tax Analytics/Compare/
        Reports/Estate/Settings) + left Sidebar with Plans switcher.
  1.A.2 GET /scenarios/{id}/year-stats?year=N returning per-year metrics
        (NW, Δ NW, taxable income, taxes, eff. rate, spending, contribs,
        investment growth). YearScrubber + YearStatsPanel render the
        right-hand sidebar; URL ?year= preserves selection.
  1.A.3 FanChart gains optional `milestones` prop (lib/milestone.ts maps
        life_event.kind → emoji) + selectedYear marker line.

Stream B — goals + progress
  1.B.1 New goals_eval module: target_nw_by_year / never_run_out /
        target_real_income probability evaluation. Wired into POST
        /simulate (exact, per-path) and GET /scenarios/{id}/projection
        (approximated from persisted fan via percentile interpolation).
        GoalsSection renders pass/fail badges.
  1.B.2 GET /scenarios/{id}/progress overlays AccountSnapshot totals on
        the projection fan; ProgressPage shows variance side-panel.

Stream C — income + cashflow
  1.C.1 New IncomeStream model + alembic 0003 + CRUD endpoints. Engine
        aggregates streams into per-year inflows + taxable arrays;
        income tax routes through the jurisdiction tax engine.
        IncomeStreamsSection on Plan tab.
  1.C.2 GET /scenarios/{id}/cashflow?year=N returns sources/sinks for
        an ECharts Sankey (sums conserve). CashflowTab body.

Stream D — settings
  1.D.1 SettingsTab + sub-nav (Milestones/Rates/Dividends/Bonds/Tax/
        Metrics/Other/Notes); placeholder cards for unbuilt sub-pages.
  1.D.2 LifeEventsSection relocated to /scenarios/:id/settings.
  1.D.3 RatesSettings (Fixed/Historical/Advanced segmented + per-asset
        cards). SimulateRequest gains rates_mode, inflation_pct,
        stocks/bonds growth + dividend, stocks_allocation. New
        build_fixed_paths() in simulator. Real-return arithmetic
        verified against (1+g+d)/(1+i)−1 ≈ 5.4%.
  1.D.4 NotesSettings — markdown textarea, save-on-blur, stored in
        scenario.config_json.notes.

Backend: 238 pytest pass (+19 new), mypy + ruff clean.
Frontend: typecheck + 7 unit tests + production build clean.

Roadmap for Wave 2-N is documented in the implementation plan.
2026-05-10 12:49:44 +00:00

62 lines
2.3 KiB
Python

"""Aggregate income streams into per-year engine arrays.
Two outputs feed the simulator:
- ``inflows``: per-year real-GBP cash that lands in the portfolio at
start-of-year (compounds at the year's return). This includes every
enabled stream regardless of tax treatment.
- ``taxable``: per-year real-GBP that the jurisdiction tax engine should
charge income tax on (i.e. ``tax_treatment='income'``). Dividend / CGT
buckets are accounted for at withdrawal time, not income time;
``tax_free`` is excluded entirely.
``growth_pct`` is real (after inflation), applied geometrically each
year from ``start_year``. The simulator already runs in real-GBP, so we
do not double-deflate.
"""
from __future__ import annotations
from collections.abc import Iterable
from dataclasses import dataclass
import numpy as np
import numpy.typing as npt
@dataclass(frozen=True)
class IncomeStreamInput:
"""Engine-level income stream — decoupled from ORM and Pydantic so
callers can construct them however."""
kind: str = "salary"
start_year: int = 0
end_year: int | None = None
amount_gbp_per_year: float = 0.0
growth_pct: float = 0.0
tax_treatment: str = "income"
enabled: bool = True
def streams_to_arrays(
streams: Iterable[IncomeStreamInput],
horizon_years: int,
) -> tuple[npt.NDArray[np.float64], npt.NDArray[np.float64]]:
"""Returns ``(inflows, taxable)`` — both ``(horizon_years,)``."""
inflows = np.zeros(horizon_years, dtype=np.float64)
taxable = np.zeros(horizon_years, dtype=np.float64)
for stream in streams:
if not stream.enabled or stream.amount_gbp_per_year <= 0:
continue
start = max(0, int(stream.start_year))
if start >= horizon_years:
continue
end_inclusive = (stream.end_year if stream.end_year is not None else horizon_years - 1)
end_inclusive = min(int(end_inclusive), horizon_years - 1)
if end_inclusive < start:
continue
for y in range(start, end_inclusive + 1):
growth_factor = (1.0 + stream.growth_pct)**(y - start)
value = stream.amount_gbp_per_year * growth_factor
inflows[y] += value
if stream.tax_treatment == "income":
taxable[y] += value
return inflows, taxable