engine+api: plumb life events into the simulator
Some checks failed
ci/woodpecker/push/woodpecker Pipeline was canceled
Some checks failed
ci/woodpecker/push/woodpecker Pipeline was canceled
Until now life events were stored but ignored by the engine — pure metadata. Now they actually move portfolios. Engine: - simulator.simulate() takes optional cashflow_adjustments: a (n_years,) real-GBP array applied each year *after* savings + return but *before* withdrawal. Positive = inflow, negative = outflow. - New fire_planner/life_events.py with EventInput dataclass + events_to_cashflow_array(events, horizon). Handles ranged deltas, one-time amounts, disabled events, year clipping past horizon, negative year_start (clipped to 0), and summing multiple events. API: - /simulate accepts optional life_events list. Server converts each to EventInput, builds cashflow_adjustments, passes to simulate(). - Frontend Run-now on scenario detail now fetches the scenario's life events and includes them in the request — projections finally reflect "retire at 50, kid born at y3, inheritance at y22". Tests: 11 events helper + 4 end-to-end engine + 1 API integration = 16 new tests. 188 total (was 172). mypy strict + ruff clean. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
parent
b82770b5c4
commit
2fc92c12f5
9 changed files with 335 additions and 4 deletions
|
|
@ -203,6 +203,15 @@ class GoalCreate(BaseModel):
|
|||
# ── simulate / compare ───────────────────────────────────────────────
|
||||
|
||||
|
||||
class LifeEventInput(BaseModel):
|
||||
"""Engine-level event shape — same as the DB row's relevant fields."""
|
||||
year_start: int = Field(ge=0, le=100)
|
||||
year_end: int | None = Field(default=None, ge=0, le=100)
|
||||
delta_gbp_per_year: Decimal = Decimal("0")
|
||||
one_time_amount_gbp: Decimal | None = None
|
||||
enabled: bool = True
|
||||
|
||||
|
||||
class SimulateRequest(BaseModel):
|
||||
"""Sync, non-persisted simulate. Used by the React UI for what-if."""
|
||||
jurisdiction: str
|
||||
|
|
@ -216,6 +225,7 @@ class SimulateRequest(BaseModel):
|
|||
floor_gbp: Decimal | None = None
|
||||
n_paths: int = Field(ge=100, le=50_000, default=5_000)
|
||||
seed: int = 42
|
||||
life_events: list[LifeEventInput] = Field(default_factory=list)
|
||||
|
||||
|
||||
class SimulateResult(BaseModel):
|
||||
|
|
|
|||
|
|
@ -26,6 +26,7 @@ from fire_planner.api.schemas import (
|
|||
SimulateResult,
|
||||
)
|
||||
from fire_planner.glide_path import get as get_glide
|
||||
from fire_planner.life_events import EventInput, events_to_cashflow_array
|
||||
from fire_planner.returns.bootstrap import block_bootstrap
|
||||
from fire_planner.returns.shiller import load_from_csv, synthetic_returns
|
||||
from fire_planner.scenarios import build_regime_schedule, build_strategy
|
||||
|
|
@ -47,6 +48,21 @@ def _project(req: SimulateRequest) -> tuple[SimulationResult, float]:
|
|||
annual_savings = (np.full(req.horizon_years, float(req.savings_per_year_gbp), dtype=np.float64)
|
||||
if req.savings_per_year_gbp > 0 else None)
|
||||
floor = float(req.floor_gbp) if req.floor_gbp is not None else None
|
||||
|
||||
cashflow_adjustments = None
|
||||
if req.life_events:
|
||||
engine_events = [
|
||||
EventInput(
|
||||
year_start=ev.year_start,
|
||||
year_end=ev.year_end,
|
||||
delta_gbp_per_year=float(ev.delta_gbp_per_year),
|
||||
one_time_amount_gbp=(float(ev.one_time_amount_gbp)
|
||||
if ev.one_time_amount_gbp is not None else None),
|
||||
enabled=ev.enabled,
|
||||
) for ev in req.life_events
|
||||
]
|
||||
cashflow_adjustments = events_to_cashflow_array(engine_events, req.horizon_years)
|
||||
|
||||
started = time.perf_counter()
|
||||
result = simulate(
|
||||
paths=paths,
|
||||
|
|
@ -57,6 +73,7 @@ def _project(req: SimulateRequest) -> tuple[SimulationResult, float]:
|
|||
regime=build_regime_schedule(req.jurisdiction, req.leave_uk_year),
|
||||
horizon_years=req.horizon_years,
|
||||
annual_savings=annual_savings,
|
||||
cashflow_adjustments=cashflow_adjustments,
|
||||
)
|
||||
elapsed = time.perf_counter() - started
|
||||
return result, elapsed
|
||||
|
|
|
|||
58
fire_planner/life_events.py
Normal file
58
fire_planner/life_events.py
Normal file
|
|
@ -0,0 +1,58 @@
|
|||
"""Convert life-event records into per-year cashflow adjustments.
|
||||
|
||||
Two event shapes the engine understands:
|
||||
|
||||
- **Ranged delta**: `delta_gbp_per_year != 0` applied each year in
|
||||
`[year_start, year_end]` (inclusive). Use a negative delta for
|
||||
expenses (childcare, sabbatical), positive for income (rental,
|
||||
pension that hasn't started yet).
|
||||
|
||||
- **One-time amount**: `one_time_amount_gbp` applied once at
|
||||
`year_start`. Inheritance, house sale proceeds, lump-sum gift.
|
||||
|
||||
Disabled events (`enabled=False`) are skipped. Year ranges that
|
||||
extend past the simulation horizon are clipped — events beyond year
|
||||
H simply don't happen in this run.
|
||||
"""
|
||||
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 EventInput:
|
||||
"""Engine-level event shape — decoupled from the SQLAlchemy ORM and
|
||||
the API Pydantic schema so callers can construct them however."""
|
||||
year_start: int
|
||||
year_end: int | None = None
|
||||
delta_gbp_per_year: float = 0.0
|
||||
one_time_amount_gbp: float | None = None
|
||||
enabled: bool = True
|
||||
|
||||
|
||||
def events_to_cashflow_array(
|
||||
events: Iterable[EventInput],
|
||||
horizon_years: int,
|
||||
) -> npt.NDArray[np.float64]:
|
||||
"""Sum a list of events into a `(horizon_years,)` real-GBP array."""
|
||||
out = np.zeros(horizon_years, dtype=np.float64)
|
||||
for ev in events:
|
||||
if not ev.enabled:
|
||||
continue
|
||||
start = max(0, int(ev.year_start))
|
||||
if start >= horizon_years:
|
||||
continue
|
||||
|
||||
if ev.delta_gbp_per_year:
|
||||
end = ev.year_end if ev.year_end is not None else ev.year_start
|
||||
end = min(int(end), horizon_years - 1)
|
||||
if end >= start:
|
||||
out[start:end + 1] += float(ev.delta_gbp_per_year)
|
||||
|
||||
if ev.one_time_amount_gbp:
|
||||
out[start] += float(ev.one_time_amount_gbp)
|
||||
return out
|
||||
|
|
@ -155,6 +155,7 @@ def simulate(
|
|||
regime: TaxRegime | RegimeFn,
|
||||
horizon_years: int | None = None,
|
||||
annual_savings: npt.NDArray[np.float64] | None = None,
|
||||
cashflow_adjustments: npt.NDArray[np.float64] | None = None,
|
||||
bucket_split: _BucketSplit = default_bucket_split,
|
||||
) -> SimulationResult:
|
||||
"""Run the MC simulation. `paths` shape: (n_paths, n_years, 3).
|
||||
|
|
@ -163,6 +164,12 @@ def simulate(
|
|||
decided by the strategy. `annual_savings`, if given, is a (n_years,)
|
||||
real-GBP array — added at the start of each year while accumulating.
|
||||
|
||||
`cashflow_adjustments`, if given, is a (n_years,) real-GBP array of
|
||||
per-year deltas applied **after** savings + return but **before**
|
||||
withdrawal. Positive = inflow (e.g. inheritance, rental income),
|
||||
negative = extra outflow (e.g. childcare, sabbatical). Used to plumb
|
||||
`life_event` rows into the projection.
|
||||
|
||||
`regime` may be a single `TaxRegime` (constant for all years) or a
|
||||
callable `(year_idx) -> TaxRegime` to model jurisdiction switches —
|
||||
e.g. UK for years 0..N-1, then Cyprus from year N onward.
|
||||
|
|
@ -181,6 +188,8 @@ def simulate(
|
|||
|
||||
if annual_savings is None:
|
||||
annual_savings = np.zeros(n_years, dtype=np.float64)
|
||||
if cashflow_adjustments is None:
|
||||
cashflow_adjustments = np.zeros(n_years, dtype=np.float64)
|
||||
|
||||
for y in range(n_years):
|
||||
alloc = glide(y)
|
||||
|
|
@ -192,8 +201,11 @@ def simulate(
|
|||
real_bond = (1 + nominal_bond) / (1 + cpi) - 1
|
||||
port_return = alloc * real_stock + (1 - alloc) * real_bond
|
||||
|
||||
# Add savings at year start, then apply year's return.
|
||||
# Add savings at year start, apply year's return, then apply
|
||||
# life-event cashflow adjustments. Adjustments don't compound
|
||||
# this year's returns (they're treated as end-of-year events).
|
||||
portfolio = (portfolio + annual_savings[y]) * (1 + port_return)
|
||||
portfolio = portfolio + cashflow_adjustments[y]
|
||||
|
||||
# Strategy is per-path Python — 600k iterations at 60y × 10k paths.
|
||||
# Profiled: ~3 seconds for the full Trinity / GK / VPW set.
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue