fire-planner: ProjectionLab parity Wave 1 — tabbed shell, year stats, goals,
All checks were successful
ci/woodpecker/push/woodpecker Pipeline was successful

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.
This commit is contained in:
Viktor Barzin 2026-05-10 12:49:44 +00:00
parent e12e8f9290
commit 9cc781a8d6
42 changed files with 3765 additions and 80 deletions

View file

@ -21,11 +21,14 @@ from sqlalchemy.ext.asyncio import async_sessionmaker
from fire_planner.api.schemas import (
CompareRequest,
CompareResult,
GoalProbability,
ProjectionPoint,
SimulateRequest,
SimulateResult,
)
from fire_planner.glide_path import static
from fire_planner.goals_eval import evaluate_goals
from fire_planner.income_streams import IncomeStreamInput, streams_to_arrays
from fire_planner.ingest.wealthfolio_pg import create_wf_sync_engine_from_env
from fire_planner.life_events import EventInput, events_to_cashflow_array
from fire_planner.returns.bootstrap import block_bootstrap
@ -35,7 +38,7 @@ from fire_planner.returns.wealthfolio_returns import (
constant_real_return_paths,
)
from fire_planner.scenarios import build_regime_schedule, build_strategy
from fire_planner.simulator import SimulationResult, simulate
from fire_planner.simulator import SimulationResult, build_fixed_paths, simulate
router = APIRouter(tags=["simulate"])
@ -64,6 +67,16 @@ async def _wealthfolio_paths(seed: int, n_paths: int, n_years: int) -> np.ndarra
async def _build_paths(req: SimulateRequest) -> np.ndarray:
if req.rates_mode == "fixed":
return build_fixed_paths(
n_paths=req.n_paths,
n_years=req.horizon_years,
inflation_pct=float(req.inflation_pct),
stocks_growth_pct=float(req.stocks_growth_pct),
stocks_dividend_pct=float(req.stocks_dividend_pct),
bonds_growth_pct=float(req.bonds_growth_pct),
bonds_dividend_pct=float(req.bonds_dividend_pct),
)
if req.returns_mode == "manual":
if req.manual_real_return_pct is None:
raise HTTPException(
@ -105,6 +118,22 @@ def _project(req: SimulateRequest, paths: np.ndarray) -> tuple[SimulationResult,
]
cashflow_adjustments = events_to_cashflow_array(engine_events, req.horizon_years)
income_inflows = None
income_taxable = None
if req.income_streams:
engine_streams = [
IncomeStreamInput(
kind=s.kind,
start_year=s.start_year,
end_year=s.end_year,
amount_gbp_per_year=float(s.amount_gbp_per_year),
growth_pct=float(s.growth_pct),
tax_treatment=s.tax_treatment,
enabled=s.enabled,
) for s in req.income_streams
]
income_inflows, income_taxable = streams_to_arrays(engine_streams, req.horizon_years)
strategy = build_strategy(
req.strategy,
floor=floor,
@ -114,23 +143,31 @@ def _project(req: SimulateRequest, paths: np.ndarray) -> tuple[SimulationResult,
guardrail_cut_pct=float(req.guardrail_cut_pct),
)
glide_alloc = float(req.stocks_allocation) if req.rates_mode == "fixed" else 1.0
started = time.perf_counter()
result = simulate(
paths=paths,
initial_portfolio=float(req.nw_seed_gbp),
spending_target=float(req.spending_gbp),
glide=static(1.0),
glide=static(glide_alloc),
strategy=strategy,
regime=build_regime_schedule(req.jurisdiction, req.leave_uk_year),
horizon_years=req.horizon_years,
annual_savings=annual_savings,
cashflow_adjustments=cashflow_adjustments,
income_inflows=income_inflows,
income_taxable=income_taxable,
)
elapsed = time.perf_counter() - started
return result, elapsed
def _to_response(result: SimulationResult, elapsed: float) -> SimulateResult:
def _to_response(
result: SimulationResult,
elapsed: float,
req: SimulateRequest | None = None,
) -> SimulateResult:
# portfolio_real has n_years+1 columns (year 0 = seed, year k = end-of-year k).
# withdrawal_real / tax_real have n_years columns (year k = withdrawn in year k+1).
# Yearly point k describes "end of year k+1": portfolio after withdrawal & growth.
@ -156,6 +193,19 @@ def _to_response(result: SimulationResult, elapsed: float) -> SimulateResult:
) for y in range(n_years)
]
median_ytr = result.median_years_to_ruin()
goals_probability: list[GoalProbability] = []
if req is not None and req.goals:
evaluations = evaluate_goals(result, req.goals, req.horizon_years)
goals_probability = [
GoalProbability(
goal_id=None,
name=ev.name,
kind=ev.kind,
probability=Decimal(str(round(ev.probability, 4))),
threshold=Decimal(str(round(ev.threshold, 4))),
passed=ev.passed,
) for ev in evaluations
]
return SimulateResult(
success_rate=Decimal(str(round(float(result.success_rate), 4))),
p10_ending_gbp=Decimal(str(round(float(result.ending_percentile(10)), 2))),
@ -166,6 +216,7 @@ def _to_response(result: SimulationResult, elapsed: float) -> SimulateResult:
if median_ytr is not None else None),
elapsed_seconds=Decimal(str(round(elapsed, 3))),
yearly=yearly,
goals_probability=goals_probability,
)
@ -177,7 +228,7 @@ async def simulate_one(req: SimulateRequest) -> SimulateResult:
result, elapsed = await asyncio.to_thread(_project, req, paths)
except KeyError as e:
raise HTTPException(status_code=400, detail=f"Unknown name: {e}") from None
return _to_response(result, elapsed)
return _to_response(result, elapsed, req)
@router.post("/compare", response_model=CompareResult)
@ -186,7 +237,7 @@ async def compare_scenarios(req: CompareRequest) -> CompareResult:
async def one(s: SimulateRequest) -> SimulateResult:
paths = await _build_paths(s)
result, elapsed = await asyncio.to_thread(_project, s, paths)
return _to_response(result, elapsed)
return _to_response(result, elapsed, s)
try:
results = await asyncio.gather(*(one(s) for s in req.scenarios))