fire-planner: Wave 2 chart-first — flex spending, categorised life
Some checks failed
ci/woodpecker/push/woodpecker Pipeline failed
Some checks failed
ci/woodpecker/push/woodpecker Pipeline failed
events, interactive Visx Gantt + spending-profile chart
Charts are now the primary editor for life events. The Plan-tab body
re-orders to make charts ~80% of viewport real-estate; legacy form
sections are collapsed into a drawer.
Backend:
- alembic 0004: life_event.category enum (essential / discretionary /
not_spending). Defaults to essential so existing rows keep their
full spending impact.
- Simulator gains discretionary_outflows + flex_rules params. Tracks
per-path running ATH, applies the deepest applicable cut to
discretionary outflows when portfolio drops vs ATH (PLab-style flex
spending). Cut amount stays in the portfolio (refund pattern).
- New flex_spending module with FlexRule + applicable_cut +
cuts_per_year (vectorised). Sortable rules; "deepest cut wins" so
users specify cumulative cuts at each tier.
- New /scenarios/{id}/spending-profile endpoint returning per-year
base / essential / discretionary / flex_cut / total breakdown.
- SimulateRequest gains flex_rules + life_event.category roundtrip.
- 8 new tests; 246 total pytest pass; mypy + ruff clean.
Frontend (Visx + ECharts):
- Installed @visx/{scale,shape,group,axis,event,responsive,tooltip}
for native SVG drag interactions.
- New <SpendingProfileChart> — Visx stacked-area of base/essential/
discretionary with red flex-cut overlay, hover tooltip, click-to-
scrub-year.
- New <EventGantt> — interactive Visx Gantt:
* Click empty space → popover create at that year (default
essential spending event)
* Click a bar → inline edit popover (name, kind, range, £/y,
category) with delete button
* Drag bar middle → moves the whole event (year-resolution snap)
* Drag bar edges → resizes year_start / year_end
* All gestures persist via PATCH /life-events/{id}
- New <FlexRulesEditor> — list of {from_ath_pct, cut} tiers, save-on-
change to scenario.config_json.flex_rules.
- Plan-tab redesign: NW fan dominant top with floating stat badges
(Year/Age/NW/Δ NW/Spending/Eff. tax) over the chart; spending-
profile chart middle; Gantt bottom; flex-rules editor; legacy form
sections in a collapsed <details> drawer.
- Frontend typecheck + 7 vitest tests + production build all clean.
This commit is contained in:
parent
9cc781a8d6
commit
64eb90c3dc
19 changed files with 2581 additions and 88 deletions
|
|
@ -185,6 +185,9 @@ class AnnualSpending(BaseModel):
|
|||
# ── life events ──────────────────────────────────────────────────────
|
||||
|
||||
|
||||
_CATEGORY_PATTERN = "^(essential|discretionary|not_spending)$"
|
||||
|
||||
|
||||
class LifeEventOut(_Base):
|
||||
id: int
|
||||
scenario_id: int
|
||||
|
|
@ -194,6 +197,7 @@ class LifeEventOut(_Base):
|
|||
year_end: int | None
|
||||
delta_gbp_per_year: Decimal
|
||||
one_time_amount_gbp: Decimal | None
|
||||
category: str = "essential"
|
||||
enabled: bool
|
||||
payload: dict[str, Any] | None
|
||||
created_at: datetime
|
||||
|
|
@ -206,6 +210,7 @@ class LifeEventCreate(BaseModel):
|
|||
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
|
||||
category: str = Field(default="essential", pattern=_CATEGORY_PATTERN)
|
||||
enabled: bool = True
|
||||
payload: dict[str, Any] | None = None
|
||||
|
||||
|
|
@ -217,6 +222,7 @@ class LifeEventPatch(BaseModel):
|
|||
year_end: int | None = None
|
||||
delta_gbp_per_year: Decimal | None = None
|
||||
one_time_amount_gbp: Decimal | None = None
|
||||
category: str | None = Field(default=None, pattern=_CATEGORY_PATTERN)
|
||||
enabled: bool | None = None
|
||||
payload: dict[str, Any] | None = None
|
||||
|
||||
|
|
@ -386,9 +392,46 @@ class LifeEventInput(BaseModel):
|
|||
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
|
||||
category: str = Field(default="essential", pattern=_CATEGORY_PATTERN)
|
||||
enabled: bool = True
|
||||
|
||||
|
||||
class FlexRule(BaseModel):
|
||||
"""ProjectionLab-style flex-spending rule.
|
||||
|
||||
When the portfolio falls ``from_ath_pct`` below its running all-time-high,
|
||||
cut discretionary spending by ``cut_discretionary_pct``. Multiple rules
|
||||
stack via "worst applicable threshold wins" — at -30% from ATH a rule
|
||||
keyed at -10% AND a rule keyed at -25% both apply, but only the deeper
|
||||
cut takes effect (so users specify *cumulative* cuts, not per-tier).
|
||||
|
||||
`from_ath_pct` is the absolute drop magnitude as a positive fraction:
|
||||
0.30 means "the portfolio is 30% below its ATH". This matches the way
|
||||
PLab labels its sliders ("if down 30%, cut 60%").
|
||||
"""
|
||||
from_ath_pct: Decimal = Field(ge=0, le=1)
|
||||
cut_discretionary_pct: Decimal = Field(ge=0, le=1)
|
||||
|
||||
|
||||
# ── spending profile ────────────────────────────────────────────────
|
||||
|
||||
|
||||
class SpendingProfilePoint(BaseModel):
|
||||
year_idx: int
|
||||
base_gbp: Decimal
|
||||
essential_gbp: Decimal
|
||||
discretionary_gbp: Decimal
|
||||
not_spending_gbp: Decimal
|
||||
flex_cut_gbp: Decimal
|
||||
total_gbp: Decimal
|
||||
|
||||
|
||||
class SpendingProfileResponse(BaseModel):
|
||||
scenario_id: int
|
||||
horizon_years: int
|
||||
points: list[SpendingProfilePoint]
|
||||
|
||||
|
||||
class SimulateRequest(BaseModel):
|
||||
"""Sync, non-persisted simulate. Used by the React UI for what-if.
|
||||
|
||||
|
|
@ -422,6 +465,7 @@ class SimulateRequest(BaseModel):
|
|||
manual_real_return_pct: Decimal | None = None
|
||||
income_streams: list[IncomeStreamInput] = Field(default_factory=list)
|
||||
goals: list[GoalCreate] = Field(default_factory=list)
|
||||
flex_rules: list[FlexRule] = Field(default_factory=list)
|
||||
# Rates settings (Wave 1.D.3). When `rates_mode='fixed'`, the engine
|
||||
# synthesises a deterministic real-return path from the per-asset
|
||||
# growth + dividend + inflation rates below, weighted by the static
|
||||
|
|
|
|||
|
|
@ -26,11 +26,16 @@ from fire_planner.api.schemas import (
|
|||
SimulateRequest,
|
||||
SimulateResult,
|
||||
)
|
||||
from fire_planner.flex_spending import FlexRule as EngineFlexRule
|
||||
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.life_events import (
|
||||
EventInput,
|
||||
events_to_cashflow_array,
|
||||
events_to_category_outflows,
|
||||
)
|
||||
from fire_planner.returns.bootstrap import block_bootstrap
|
||||
from fire_planner.returns.shiller import load_from_csv, synthetic_returns
|
||||
from fire_planner.returns.wealthfolio_returns import (
|
||||
|
|
@ -105,6 +110,7 @@ def _project(req: SimulateRequest, paths: np.ndarray) -> tuple[SimulationResult,
|
|||
floor = float(req.floor_gbp) if req.floor_gbp is not None else None
|
||||
|
||||
cashflow_adjustments = None
|
||||
discretionary_outflows = None
|
||||
if req.life_events:
|
||||
engine_events = [
|
||||
EventInput(
|
||||
|
|
@ -113,10 +119,20 @@ def _project(req: SimulateRequest, paths: np.ndarray) -> tuple[SimulationResult,
|
|||
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),
|
||||
category=ev.category,
|
||||
enabled=ev.enabled,
|
||||
) for ev in req.life_events
|
||||
]
|
||||
cashflow_adjustments = events_to_cashflow_array(engine_events, req.horizon_years)
|
||||
category_outflows = events_to_category_outflows(engine_events, req.horizon_years)
|
||||
discretionary_outflows = category_outflows.get("discretionary")
|
||||
|
||||
engine_flex = [
|
||||
EngineFlexRule(
|
||||
from_ath_pct=float(r.from_ath_pct),
|
||||
cut_discretionary_pct=float(r.cut_discretionary_pct),
|
||||
) for r in req.flex_rules
|
||||
] if req.flex_rules else None
|
||||
|
||||
income_inflows = None
|
||||
income_taxable = None
|
||||
|
|
@ -158,6 +174,8 @@ def _project(req: SimulateRequest, paths: np.ndarray) -> tuple[SimulationResult,
|
|||
cashflow_adjustments=cashflow_adjustments,
|
||||
income_inflows=income_inflows,
|
||||
income_taxable=income_taxable,
|
||||
discretionary_outflows=discretionary_outflows,
|
||||
flex_rules=engine_flex,
|
||||
)
|
||||
elapsed = time.perf_counter() - started
|
||||
return result, elapsed
|
||||
|
|
|
|||
185
fire_planner/api/spending_profile.py
Normal file
185
fire_planner/api/spending_profile.py
Normal file
|
|
@ -0,0 +1,185 @@
|
|||
"""Per-year spending breakdown — drives the Visx stacked-area chart on
|
||||
the Plan tab.
|
||||
|
||||
Returns one ``SpendingProfilePoint`` per year of the scenario horizon:
|
||||
|
||||
base_gbp — scenario-level baseline spending (real GBP)
|
||||
essential_gbp — sum of |delta| from active essential life events
|
||||
discretionary_gbp — sum of |delta| from active discretionary events
|
||||
not_spending_gbp — informational events that have a delta_gbp_per_year
|
||||
but are tagged ``not_spending`` (rare, but possible)
|
||||
flex_cut_gbp — discretionary £ trimmed by flex rules at p50 portfolio
|
||||
drawdown vs running ATH (0 when no rules / no
|
||||
drawdown).
|
||||
total_gbp — base + essential + discretionary − flex_cut
|
||||
|
||||
The flex-cut estimate uses the persisted p50 portfolio path (from
|
||||
``projection_yearly``) because the user's scenario.config_json may carry
|
||||
``flex_rules`` they've configured but not yet re-run a recompute against.
|
||||
This gives an honest preview of how the rules would shape spending; the
|
||||
exact per-path cut shows up in the next live ``POST /simulate``.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Sequence
|
||||
from decimal import Decimal
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from fire_planner.api.dependencies import get_session
|
||||
from fire_planner.api.schemas import (
|
||||
SpendingProfilePoint,
|
||||
SpendingProfileResponse,
|
||||
)
|
||||
from fire_planner.db import LifeEvent, McRun, ProjectionYearly, Scenario
|
||||
|
||||
router = APIRouter(prefix="/scenarios", tags=["spending-profile"])
|
||||
|
||||
|
||||
def _category_outflow_at(events: Sequence[LifeEvent], year_idx: int,
|
||||
category: str) -> Decimal:
|
||||
total = Decimal("0")
|
||||
for ev in events:
|
||||
if not ev.enabled or ev.category != category:
|
||||
continue
|
||||
if year_idx < ev.year_start:
|
||||
continue
|
||||
end = ev.year_end if ev.year_end is not None else ev.year_start
|
||||
if year_idx > end:
|
||||
continue
|
||||
delta = Decimal(str(ev.delta_gbp_per_year or 0))
|
||||
if delta < 0:
|
||||
total += -delta
|
||||
if year_idx == ev.year_start and ev.one_time_amount_gbp is not None:
|
||||
ot = Decimal(str(ev.one_time_amount_gbp))
|
||||
if ot < 0:
|
||||
total += -ot
|
||||
return total
|
||||
|
||||
|
||||
def _category_inflow_at(events: Sequence[LifeEvent], year_idx: int,
|
||||
category: str) -> Decimal:
|
||||
"""Positive deltas are inflows — surface them as a negative spending
|
||||
contribution so the stacked area sums correctly."""
|
||||
total = Decimal("0")
|
||||
for ev in events:
|
||||
if not ev.enabled or ev.category != category:
|
||||
continue
|
||||
if year_idx < ev.year_start:
|
||||
continue
|
||||
end = ev.year_end if ev.year_end is not None else ev.year_start
|
||||
if year_idx > end:
|
||||
continue
|
||||
delta = Decimal(str(ev.delta_gbp_per_year or 0))
|
||||
if delta > 0:
|
||||
total += delta
|
||||
return total
|
||||
|
||||
|
||||
def _flex_rules_for(scenario: Scenario) -> list[dict[str, float]]:
|
||||
blob = scenario.config_json or {}
|
||||
rules = blob.get("flex_rules") if isinstance(blob, dict) else None
|
||||
if not isinstance(rules, list):
|
||||
return []
|
||||
out: list[dict[str, float]] = []
|
||||
for r in rules:
|
||||
if not isinstance(r, dict):
|
||||
continue
|
||||
try:
|
||||
out.append({
|
||||
"from_ath_pct": float(r.get("from_ath_pct", 0)),
|
||||
"cut_discretionary_pct": float(r.get("cut_discretionary_pct", 0)),
|
||||
})
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
return out
|
||||
|
||||
|
||||
def _flex_cut_at_year(year: ProjectionYearly, ath_so_far_gbp: Decimal,
|
||||
rules: list[dict[str, float]],
|
||||
discretionary_gbp: Decimal) -> Decimal:
|
||||
if not rules or discretionary_gbp <= 0 or ath_so_far_gbp <= 0:
|
||||
return Decimal("0")
|
||||
p50 = Decimal(str(year.p50_portfolio_gbp))
|
||||
drawdown = max(Decimal("0"), Decimal("1") - p50 / ath_so_far_gbp)
|
||||
best = Decimal("0")
|
||||
for rule in rules:
|
||||
thr = Decimal(str(rule["from_ath_pct"]))
|
||||
cut = Decimal(str(rule["cut_discretionary_pct"]))
|
||||
if drawdown >= thr and cut > best:
|
||||
best = cut
|
||||
return (discretionary_gbp * best).quantize(Decimal("0.01"))
|
||||
|
||||
|
||||
@router.get("/{scenario_id}/spending-profile",
|
||||
response_model=SpendingProfileResponse)
|
||||
async def get_spending_profile(
|
||||
scenario_id: int,
|
||||
session: AsyncSession = Depends(get_session),
|
||||
) -> SpendingProfileResponse:
|
||||
scen = await session.get(Scenario, scenario_id)
|
||||
if scen is None:
|
||||
raise HTTPException(status_code=404, detail="Scenario not found")
|
||||
|
||||
events = list((await session.execute(
|
||||
select(LifeEvent).where(LifeEvent.scenario_id == scenario_id))).scalars().all())
|
||||
|
||||
yearly_rows: list[ProjectionYearly] = []
|
||||
run = (await session.execute(
|
||||
select(McRun).where(McRun.scenario_id == scenario_id).order_by(
|
||||
McRun.run_at.desc()).limit(1))).scalar_one_or_none()
|
||||
if run is not None:
|
||||
rows = (await session.execute(
|
||||
select(ProjectionYearly).where(ProjectionYearly.mc_run_id == run.id).order_by(
|
||||
ProjectionYearly.year_idx))).scalars().all()
|
||||
yearly_rows = list(rows)
|
||||
|
||||
rules = _flex_rules_for(scen)
|
||||
base = Decimal(str(scen.spending_gbp))
|
||||
horizon = scen.horizon_years
|
||||
by_year = {row.year_idx: row for row in yearly_rows}
|
||||
|
||||
points: list[SpendingProfilePoint] = []
|
||||
ath = Decimal(str(scen.nw_seed_gbp))
|
||||
for year_idx in range(horizon):
|
||||
essential = _category_outflow_at(events, year_idx, "essential")
|
||||
discretionary = _category_outflow_at(events, year_idx, "discretionary")
|
||||
not_spending = _category_outflow_at(events, year_idx, "not_spending")
|
||||
|
||||
# Income-shaped life events (positive delta) reduce the net spend
|
||||
# the user must sustain. We don't subtract them from any single
|
||||
# bucket — they net against `base` for the chart's footprint.
|
||||
ess_inflow = _category_inflow_at(events, year_idx, "essential")
|
||||
disc_inflow = _category_inflow_at(events, year_idx, "discretionary")
|
||||
net_base = base - ess_inflow - disc_inflow
|
||||
if net_base < 0:
|
||||
net_base = Decimal("0")
|
||||
|
||||
flex_cut = Decimal("0")
|
||||
row = by_year.get(year_idx)
|
||||
if row is not None:
|
||||
ath = max(ath, Decimal(str(row.p50_portfolio_gbp)))
|
||||
flex_cut = _flex_cut_at_year(row, ath, rules, discretionary)
|
||||
|
||||
total = net_base + essential + discretionary - flex_cut
|
||||
if total < 0:
|
||||
total = Decimal("0")
|
||||
|
||||
points.append(
|
||||
SpendingProfilePoint(
|
||||
year_idx=year_idx,
|
||||
base_gbp=net_base,
|
||||
essential_gbp=essential,
|
||||
discretionary_gbp=discretionary,
|
||||
not_spending_gbp=not_spending,
|
||||
flex_cut_gbp=flex_cut,
|
||||
total_gbp=total,
|
||||
))
|
||||
|
||||
return SpendingProfileResponse(
|
||||
scenario_id=scenario_id,
|
||||
horizon_years=horizon,
|
||||
points=points,
|
||||
)
|
||||
|
|
@ -50,6 +50,7 @@ from fire_planner.api.progress import router as progress_router
|
|||
from fire_planner.api.scenarios import router as scenarios_router
|
||||
from fire_planner.api.simulate import router as simulate_router
|
||||
from fire_planner.api.spending import router as spending_router
|
||||
from fire_planner.api.spending_profile import router as spending_profile_router
|
||||
from fire_planner.api.year_stats import router as year_stats_router
|
||||
from fire_planner.db import create_engine_from_env, make_session_factory
|
||||
|
||||
|
|
@ -134,6 +135,7 @@ app.include_router(income_streams_router, prefix=_API_PREFIX)
|
|||
app.include_router(year_stats_router, prefix=_API_PREFIX)
|
||||
app.include_router(progress_router, prefix=_API_PREFIX)
|
||||
app.include_router(cashflow_router, prefix=_API_PREFIX)
|
||||
app.include_router(spending_profile_router, prefix=_API_PREFIX)
|
||||
app.include_router(simulate_router, prefix=_API_PREFIX)
|
||||
app.include_router(spending_router, prefix=_API_PREFIX)
|
||||
|
||||
|
|
|
|||
|
|
@ -192,6 +192,15 @@ class LifeEvent(Base):
|
|||
nullable=False,
|
||||
server_default=text("0"))
|
||||
one_time_amount_gbp: Mapped[Decimal | None] = mapped_column(Numeric(14, 2), nullable=True)
|
||||
# Spending category for flex-spending classification:
|
||||
# essential — never trimmed by flex rules (mortgage, food, kids)
|
||||
# discretionary — trimmed when portfolio drops vs ATH (travel, dining)
|
||||
# not_spending — informational only (a milestone marker that doesn't
|
||||
# change cashflow, e.g. a kid graduating)
|
||||
# Default is `essential` so existing rows keep their full spending impact.
|
||||
category: Mapped[str] = mapped_column(String(16),
|
||||
nullable=False,
|
||||
server_default=text("'essential'"))
|
||||
enabled: Mapped[bool] = mapped_column(Boolean, nullable=False, server_default=text("true"))
|
||||
payload: Mapped[dict[str, Any] | None] = mapped_column(JSON_TYPE, nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(TIMESTAMP(timezone=True),
|
||||
|
|
|
|||
89
fire_planner/flex_spending.py
Normal file
89
fire_planner/flex_spending.py
Normal file
|
|
@ -0,0 +1,89 @@
|
|||
"""ProjectionLab-style flex-spending rules.
|
||||
|
||||
A `FlexRule` says "if the portfolio is at least ``from_ath_pct`` below its
|
||||
running all-time-high, trim discretionary spending by ``cut_discretionary_pct``".
|
||||
Multiple rules stack via "deepest applicable cut wins" — users specify
|
||||
*cumulative* cuts at each tier, so a [-0.10 → 20%, -0.30 → 60%] config
|
||||
trims by 60% (not 80%) at -30%.
|
||||
|
||||
The engine path:
|
||||
|
||||
per year y, per path p:
|
||||
drawdown[p,y] = 1 - portfolio[p,y] / ath[p,y]
|
||||
cut_pct[p,y] = max(rule.cut for rule in flex_rules if drawdown[p,y] >= rule.from_ath_pct)
|
||||
discretionary_after_flex[p,y] = discretionary_baseline[y] * (1 - cut_pct[p,y])
|
||||
|
||||
The cuts are applied to the *baseline* discretionary spend each year (so a
|
||||
£10k/y travel budget cut by 60% becomes £4k that year), and the saved
|
||||
amount is *not* drawn from the portfolio. The simulator subtracts the
|
||||
saved amount from the cashflow drawdown before calling the strategy.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
import numpy as np
|
||||
import numpy.typing as npt
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class FlexRule:
|
||||
"""Engine-level flex rule. ``from_ath_pct`` is the absolute drop
|
||||
magnitude (positive fraction); ``cut_discretionary_pct`` is the
|
||||
fraction to remove from discretionary spending at that depth."""
|
||||
from_ath_pct: float
|
||||
cut_discretionary_pct: float
|
||||
|
||||
|
||||
def applicable_cut(drawdown: float, rules: list[FlexRule]) -> float:
|
||||
"""Return the cut fraction for a single (path, year) pair.
|
||||
|
||||
``drawdown`` is 1 − portfolio/ath (in the [0, 1] range — clamp inside
|
||||
the simulator before calling). The deepest rule whose threshold is
|
||||
satisfied wins.
|
||||
"""
|
||||
if not rules:
|
||||
return 0.0
|
||||
best = 0.0
|
||||
for rule in rules:
|
||||
if drawdown >= rule.from_ath_pct and rule.cut_discretionary_pct > best:
|
||||
best = rule.cut_discretionary_pct
|
||||
return best
|
||||
|
||||
|
||||
def cuts_per_year(
|
||||
portfolio_real: npt.NDArray[np.float64],
|
||||
rules: list[FlexRule],
|
||||
) -> npt.NDArray[np.float64]:
|
||||
"""Vectorised version of ``applicable_cut`` across every (path, year).
|
||||
|
||||
``portfolio_real`` shape: ``(n_paths, n_years + 1)`` — index 0 is the
|
||||
seed, last column is the horizon. Returns ``(n_paths, n_years)``: the
|
||||
cut applied at the start of year ``y`` is decided by the portfolio
|
||||
*after year y-1's close* (i.e. column ``y`` in the input).
|
||||
"""
|
||||
if not rules or portfolio_real.size == 0:
|
||||
return np.zeros((portfolio_real.shape[0], portfolio_real.shape[1] - 1),
|
||||
dtype=np.float64)
|
||||
n_paths, ncols = portfolio_real.shape
|
||||
n_years = ncols - 1
|
||||
# Running ATH per path. np.maximum.accumulate over axis=1 gives us
|
||||
# the running max — exactly what we want.
|
||||
ath = np.maximum.accumulate(portfolio_real, axis=1)
|
||||
# Avoid divide-by-zero. If ATH is 0 (only happens if seed is 0 and the
|
||||
# portfolio never grew), drawdown is treated as 0.
|
||||
safe_ath = np.where(ath > 0, ath, 1.0)
|
||||
drawdown = np.clip(1.0 - portfolio_real / safe_ath, 0.0, 1.0)
|
||||
cuts = np.zeros((n_paths, n_years), dtype=np.float64)
|
||||
sorted_rules = sorted(rules,
|
||||
key=lambda r: r.cut_discretionary_pct,
|
||||
reverse=True)
|
||||
for rule in sorted_rules:
|
||||
# Each rule's cut applies wherever drawdown >= threshold AND a
|
||||
# higher cut hasn't already been recorded (because we iterate
|
||||
# rules from largest cut down).
|
||||
# Drawdown at year y end-of-year-(y-1) — column y of drawdown.
|
||||
mask = (drawdown[:, :n_years] >= rule.from_ath_pct) & (
|
||||
cuts < rule.cut_discretionary_pct)
|
||||
cuts[mask] = rule.cut_discretionary_pct
|
||||
return cuts
|
||||
|
|
@ -26,11 +26,19 @@ 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."""
|
||||
the API Pydantic schema so callers can construct them however.
|
||||
|
||||
`category` classifies the event for the flex-spending engine:
|
||||
- "essential" — never trimmed
|
||||
- "discretionary" — trimmed when the portfolio drops vs ATH
|
||||
- "not_spending" — informational (no cashflow impact); still rendered
|
||||
on the milestone timeline
|
||||
"""
|
||||
year_start: int
|
||||
year_end: int | None = None
|
||||
delta_gbp_per_year: float = 0.0
|
||||
one_time_amount_gbp: float | None = None
|
||||
category: str = "essential"
|
||||
enabled: bool = True
|
||||
|
||||
|
||||
|
|
@ -38,7 +46,14 @@ 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."""
|
||||
"""Sum a list of events into a single `(horizon_years,)` real-GBP array.
|
||||
|
||||
Sign convention: ``delta_gbp_per_year > 0`` is an **inflow** (income or
|
||||
delayed-pension start), ``< 0`` is an **outflow** (extra expense).
|
||||
Categories are NOT consulted here — every event contributes to the
|
||||
headline cashflow array. Flex spending (which trims discretionary
|
||||
outflows) is layered on top via ``events_to_category_outflows``.
|
||||
"""
|
||||
out = np.zeros(horizon_years, dtype=np.float64)
|
||||
for ev in events:
|
||||
if not ev.enabled:
|
||||
|
|
@ -56,3 +71,38 @@ def events_to_cashflow_array(
|
|||
if ev.one_time_amount_gbp:
|
||||
out[start] += float(ev.one_time_amount_gbp)
|
||||
return out
|
||||
|
||||
|
||||
def events_to_category_outflows(
|
||||
events: Iterable[EventInput],
|
||||
horizon_years: int,
|
||||
) -> dict[str, npt.NDArray[np.float64]]:
|
||||
"""Per-category per-year **outflow magnitudes** (always >= 0).
|
||||
|
||||
Used by flex-spending: each year's discretionary outflow is the
|
||||
candidate the rules can trim. Inflow events (positive delta) and
|
||||
``not_spending`` events are excluded — flex rules only trim spending.
|
||||
"""
|
||||
out: dict[str, npt.NDArray[np.float64]] = {
|
||||
"essential": np.zeros(horizon_years, dtype=np.float64),
|
||||
"discretionary": np.zeros(horizon_years, dtype=np.float64),
|
||||
}
|
||||
for ev in events:
|
||||
if not ev.enabled:
|
||||
continue
|
||||
if ev.category not in ("essential", "discretionary"):
|
||||
continue
|
||||
start = max(0, int(ev.year_start))
|
||||
if start >= horizon_years:
|
||||
continue
|
||||
|
||||
if ev.delta_gbp_per_year and ev.delta_gbp_per_year < 0:
|
||||
outflow = -float(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[ev.category][start:end + 1] += outflow
|
||||
|
||||
if ev.one_time_amount_gbp and ev.one_time_amount_gbp < 0:
|
||||
out[ev.category][start] += -float(ev.one_time_amount_gbp)
|
||||
return out
|
||||
|
|
|
|||
|
|
@ -33,6 +33,7 @@ from decimal import Decimal
|
|||
import numpy as np
|
||||
import numpy.typing as npt
|
||||
|
||||
from fire_planner.flex_spending import FlexRule, applicable_cut
|
||||
from fire_planner.glide_path import GlideFn
|
||||
from fire_planner.strategies.base import StrategyState, WithdrawalStrategy
|
||||
from fire_planner.tax.base import TaxInputs, TaxRegime
|
||||
|
|
@ -186,6 +187,8 @@ def simulate(
|
|||
bucket_split: _BucketSplit = default_bucket_split,
|
||||
income_inflows: npt.NDArray[np.float64] | None = None,
|
||||
income_taxable: npt.NDArray[np.float64] | None = None,
|
||||
discretionary_outflows: npt.NDArray[np.float64] | None = None,
|
||||
flex_rules: list[FlexRule] | None = None,
|
||||
) -> SimulationResult:
|
||||
"""Run the MC simulation. `paths` shape: (n_paths, n_years, 3).
|
||||
|
||||
|
|
@ -223,6 +226,11 @@ def simulate(
|
|||
income_inflows = np.zeros(n_years, dtype=np.float64)
|
||||
if income_taxable is None:
|
||||
income_taxable = np.zeros(n_years, dtype=np.float64)
|
||||
if discretionary_outflows is None:
|
||||
discretionary_outflows = np.zeros(n_years, dtype=np.float64)
|
||||
rules = list(flex_rules) if flex_rules else []
|
||||
# Track running ATH per path so we can decide flex cuts each year.
|
||||
ath = np.full(n_paths, float(initial_portfolio), dtype=np.float64)
|
||||
|
||||
for y in range(n_years):
|
||||
alloc = glide(y)
|
||||
|
|
@ -246,6 +254,19 @@ def simulate(
|
|||
income_tax_breakdown = regime_at(y).compute_tax(
|
||||
TaxInputs(earned_income=Decimal(str(round(float(income_taxable[y]), 2)))))
|
||||
portfolio = portfolio - float(income_tax_breakdown.total)
|
||||
# Flex spending: per-path, decide the cut from this year's
|
||||
# drawdown-from-ATH and refund the trimmed discretionary
|
||||
# back to the portfolio. The cashflow_adjustments array already
|
||||
# subtracted the *baseline* discretionary, so we add back
|
||||
# `cut_pct * baseline` to leave only the post-cut amount drawn.
|
||||
if rules and discretionary_outflows[y] > 0.0:
|
||||
for p in range(n_paths):
|
||||
if ath[p] <= 0:
|
||||
continue
|
||||
drawdown = max(0.0, 1.0 - portfolio[p] / ath[p])
|
||||
cut = applicable_cut(drawdown, rules)
|
||||
if cut > 0:
|
||||
portfolio[p] += cut * float(discretionary_outflows[y])
|
||||
|
||||
# Strategy is per-path Python — 600k iterations at 60y × 10k paths.
|
||||
# Profiled: ~3 seconds for the full Trinity / GK / VPW set.
|
||||
|
|
@ -280,6 +301,9 @@ def simulate(
|
|||
|
||||
portfolio_history[:, y + 1] = np.clip(portfolio, a_min=0.0, a_max=None)
|
||||
portfolio = portfolio_history[:, y + 1]
|
||||
# Update running ATH per path so next year's flex decision uses
|
||||
# the post-close peak.
|
||||
np.maximum(ath, portfolio, out=ath)
|
||||
|
||||
# Success = portfolio stayed positive through every interim year.
|
||||
# Excludes the very last year-end because VPW deliberately drains
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue