Topic

Uncertain inputs and repeated runs

A projection with fixed rates answers "what happens if things go as planned". Markets and prices do not, so a scenario can take its rates from a random process instead, and be run many times from one seed. Each run is still exact bookkeeping; what is uncertain is only the path, and every summary says how many runs it rests on and how far it could be off.

import { simulate, processes } from "@ratmath/finance";
import { normal } from "@ratmath/stats";

const retirement = {
  periods: 360,                              // 30 years, monthly
  accounts: [{ name: "pot", balance: 600000 }],
  flows: [{ name: "spending", amount: 2500, from: "pot" }],
};
const s = simulate(retirement, {
  returns: { pot: processes.gbm({ drift: "5%", volatility: "15%" }) },
  inflation: processes.independent(normal("2.5/100", "1/100")),
  indexed: ["spending"],                     // spending keeps up with prices
  events: [{ name: "roof", probability: "4%", amount: 15000, from: "pot" }],
  runs: 1000, seed: 1,
});
s.ruin;              // how often the pot ran out, with an exact 95% interval
s.percentiles["5"];  // the final balance in a bad case
s.bands;             // percentiles at every month, for a fan chart
s.real.median;       // the median outcome in today's money

Processes

A process turns a seeded random stream into a path: one growth factor per period, 1 plus that period's return or interest. Written into an account (through returns), the path replaces the account's fixed rate.

processeach year or period
processes.fixed(rate)the same annual return every year: a baseline with no uncertainty
processes.independent(dist)an annual return drawn afresh from a distribution, such as normal("7/100", "15/100") from @ratmath/stats
processes.choice(values, weights)an annual return from a short list with exact weights
processes.sequence(returns)the returns given, in order
processes.resample(history, { block })years drawn from history you supply, in blocks of consecutive years so that runs of good or bad years survive
processes.gbm({ drift, volatility })geometric Brownian motion: each period multiplies by exp⁡((μ−σ22)Δt+σΔt Z)\exp\big((\mu - \tfrac{\sigma^2}{2})\Delta t + \sigma\sqrt{\Delta t}\,Z\big), so a year grows by eμe^{\mu} on average
processes.walk({ start, step, min, max })an interest rate that moves by a random step once a year
processes.meanReverting({ start, mean, speed, volatility, floor })a Vasicek rate, r←r+a(θ−r)Δt+σΔt Zr \leftarrow r + a(\theta - r)\Delta t + \sigma\sqrt{\Delta t}\,Z: pulled back towards its mean

An annual return R spread over m periods becomes the factor (1+R)1/m(1+R)^{1/m} each period. With yearly periods that is R itself, exactly. Otherwise, and for every draw from a continuous distribution, the factor is a floating-point number that is rounded to 8 decimal places of the per-period rate. From that point on everything is exact, so two runs from the same seed agree to the cent on any machine.

Inflation and events

inflation is a process for the price level. Flows named in indexed are multiplied by the price level at the start of their period, and real divides each outcome by the final price level, giving it in today's money. A fixed inflation rate reproduces a flow with the same growth exactly; the tests check that.

An event is a one-off flow that happens with a stated probability each year (or each period with per: "period"), at a random point in that year. It can be limited to the first time with once, and its amount can be fixed or drawn from a distribution. A burst pipe, a gap in income, or an inheritance are events.

Many runs

Run i uses the stream rng(seed).fork("run i"), and each input within it has its own fork. So run 7 is the same whether you ask for 10 runs or 10,000, and adding an event does not change the returns. The summaries are simulated answers and say so:

  • mean is the exact average of the outcomes, and standardError is s/ns/\sqrt{n}, enclosed.
  • ruin is the fraction of runs in which an account that started at or above zero went below it. It is reported with an exact (Clopper–Pearson) interval for the true probability, so 37 of 1000 runs reads as "between 2.6% and 5.1%", not as 3.7%.
  • percentiles, quantile(p) and bands use the nearest-rank rule, so each value is one of the outcomes that actually occurred.

Balances are rounded to the cent each period during a simulation, as a bank would round them, unless the scenario names another rule or you pass rounding: false. Without rounding, a balance after hundreds of random months is a fraction with thousands of digits.

Checking the machinery against exact answers

When each year's return is one of two values, three years have eight equally likely paths, and the probability of running out can be found exactly by projecting all eight. A simulation with processes.choice must then report an interval that contains that fraction. Its mean must be within a few standard errors of the exact mean of the eight outcomes, and every outcome must be one of the eight. The tests check these, and they also check that geometric Brownian motion's mean growth is eμTe^{\mu T} within the sampling error.

The order of good and bad years

With no money going in or out, the order of returns cannot matter, because (1+r1)(1+r2)(1+r3)(1+r_1)(1+r_2)(1+r_3) is the same product in any order. sequenceRisk confirms this exactly (orderMatters: false). Add withdrawals and the order matters a great deal. A bad year early, while the pot is large, takes more money out than the same bad year late. sequenceRisk(spec, { account, returns }) applies the same returns in the given order, reversed, best first, worst first and in shuffled orders, and reports the spread.

callreturns
simulate(spec, { returns, inflation, indexed, events, runs, seed, rounding, measure, ruin, level, percentiles, track })Simulation: outcomes, sorted, mean, standardError, percentiles, quantile(p), ruin, ruinTimes, bands, real
sequenceRisk(spec, { account, returns, shuffles, seed, measure }){ rows: [{ order, returns, outcome, firstNegative }], best, worst, spread, orderMatters }
process.path(seed, periods, periodsPerYear)the growth factors of one path
Try itEdit the code and run it with @ratmath/finance and Core's Rational in scope. The last line's value is shown; PRINT(…) adds lines, TEX(…) typesets math.
Ctrl/⌘ + Enter runs