Add a seeded Monte Carlo run to the retirement planner

JA
7d ago
+786-1

Base: up/retirement-plan-projection (stacked) | Head: up/retirement-plan-monte-carlo | Draft

Part of #5567

Fork pre-flight: jaysbeekay/sure#369 (same commits, head 7506b94f7)

Stacked on #5610

Third of four. Model only: no route, controller, view or job.

Problem

The year-by-year plan says whether the money lasts at the expected return. It cannot say how likely that is when returns vary, or how badly a run of poor years early in retirement hurts.

Resulting behaviour

A Monte Carlo run over 5,000 paths reports:

  • the success rate;
  • percentile paths in today's money;
  • a worst-sequence stress rate;
  • the first year that meets the plan's success target;
  • a 5 x 5 grid over return (-2 to +2 points) and savings rate (-10 to +10 points).

The design choice to know about: the run is deterministic. Its draws come from a seed fixed by the plan's id, so the same inputs always give the same answer, and every question asked of one run shares the same draws.

  • Migration: return_volatility (default 12%) and success_target (default 90%) on retirement_plans, with check constraints.
  • RetirementPlan::MonteCarlo (pure). Each year's return is log-normal around the expected return: 1 + r_t = (1 + r) * exp(sigma * z_t). So the median path is the expected-returns path, and with sigma = 0 every path equals RetirementPlan::Simulation to the cent. Normals come from Box-Muller over Random.new(seed). The yearly contributions and withdrawals come from the simulation (#yearly_flows), so the two engines cannot disagree on them; only the growth varies. Percentiles use nearest rank. The stress run reorders each path's retirement-year returns worst first, or every modelled year when retirement is already past. The growth factor is floored at 0, so a grid step past -100% empties the portfolio rather than flipping its sign. A path's withdrawal fails only when it exceeds the value by more than half a cent, because the run replays the flows in Float.
  • RetirementPlan::Simulation gains the readers the run uses: #yearly_flows, #inflation_rate, #current_assets and #return_rate. Its existing behaviour is unchanged.
  • RetirementPlan#monte_carlo_seed is the CRC32 of the id. #monte_carlo(as_of:) retires on the plan's date, or in FIRE mode in the solved year. It returns nil, before computing anything, for an unsaved plan or one with nothing to simulate. #monte_carlo_result(as_of:) returns the answers as plain values. The confident-year search, which is a full run per candidate year, runs only in FIRE mode.

Not in this PR: a background job and a result cache. A full result runs thousands of paths, and the confident-year search repeats that per candidate year, so the page that shows it should run it off the request. That job belongs with the page.

Size: 270 non-test lines (269 added, 1 removed), not counting db/schema.rb (4 lines).

Validation

  • Full suite bin/rails test, run at the top of the stack (a commit whose tree differs from the last PR's head only in a code comment): 18300 runs, 0 failures. The 8 errors are ReleaseNotesWorkflowTest, which needs node, missing from the test image. The Monte Carlo tests use fixed seeds and pass on every run.
  • CI at this head: lint (bin/rubocop), Brakeman, and the unit and system test jobs pass.
  • The engine is run on two different days under travel_to, inside assert_queries_count(0) and with Current expected never. Both runs must give the same rates, percentiles, confident year and grid.
  • Mutations, each caught by a failing assertion:
MutationCaught by
mean-based log-normal (- sigma^2 / 2)the median path is the expected-returns path
seed ignored (Random.new)the same seed gives the same result, and a different seed a different one
plan seed not fixed by its id, or plan volatility not passed throughthe run uses the plan's own volatility, a seed fixed by the plan...
FIRE mode not solved for its yearin FIRE mode the run retires in the expected-returns year
confident year searched outside FIRE modeoutside FIRE mode the result has no confident year and the search never runs
confident year needs to beat the targeta year whose success rate equals the target exactly is confident
stress run not reorderedthe worst-first ordering of the same returns never succeeds more often
percentile off by onea percentile is the smallest value with at least that share at or below it
percentiles not deflated, or withdrawal taken after growthwith no volatility every path is the deterministic projection, to the cent
grid ignores the savings stepthe heatmap never lowers success for a higher return or savings rate
Box-Muller cosine used twicethe median path is the expected-returns path
volatility upper bound removedvolatility outside 0 to 100% and a target of 0 or above 100% are refused
FIRE end-age fallback droppedin FIRE mode a plan that never lasts is run retiring in its end-age year
no half-cent tolerancewith no volatility a plan funded to the cent lasts, as the simulation says; a plan a cent short runs out on every path

Blast radius

Simulation's new readers are read only by MonteCarlo. #yearly_flows calls the same private flows_for the rows use. Simulation.new is called by RetirementPlan#simulation, Solver and MonteCarlo, all with the same simulation_inputs hash, so the three cannot drift on inputs. Nothing outside RetirementPlan changes.

Migration notes

20261008150300_add_monte_carlo_to_retirement_plans (AddMonteCarloToRetirementPlans) adds two non-null columns with defaults to retirement_plans, and existing rows take the defaults. There is nothing to run after deploy.

Screenshots

None: this PR has no UI.


Summary by cubic

Adds a seeded Monte Carlo run to the retirement planner, so a plan can estimate how likely its savings last when returns vary instead of only at the expected return. With zero volatility every path equals the deterministic projection, to the cent.

  • Draws come from a seed fixed by the plan id, so the same inputs always give the same answer and every question shares the same draws.
  • Reports the success rate, percentile paths in today's money, a worst-first stress rate, the first year that meets the plan's success target, and a 5 x 5 grid over return and savings rate.
  • The first year's return covers only the part of the year left from the reference date, and the stress reorder starts at the first whole year when the first year is partial.
  • A stress path counts only if it also lasts in its own order; worst-first is not always worst when income tops spending in a retired year.
  • The run replays the simulation's yearly flows, so the two engines cannot disagree on contributions or withdrawals, and reads no clock, database, or request.
  • Returns nil on the same terms as the simulation: unsaved plan, no years to plan, or retirement after the end age. In FIRE mode a plan that never lasts is run retiring in its end-age year.
  • Model only: no route, controller, view, job, or result cache yet. The confident-year search is a full run per candidate year and should run off the request, on a lazy frame with the page that shows it.

Migration

  • Adds return_volatility (default 12%) and success_target (default 90%) to retirement_plans with check constraints; existing rows take the defaults, nothing to run after deploy.

Summary by CodeRabbit

  • New Features
    • Added Monte Carlo retirement projections with success rates, projected portfolio percentiles, stress-test results, and a heatmap across return and savings assumptions.
    • FIRE plans can show the first projected year that meets the selected success target.
  • Improvements
    • Set return volatility and success targets as percentages. New plans default to 12% volatility and a 90% success target.