@ratmath/finance 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,390 @@
1
+ // Uncertain inputs and repeated runs. A *process* turns a seeded random
2
+ // stream into a path: one growth factor per period (1 + the return or the
3
+ // interest for that period). `simulate` draws a path for each uncertain
4
+ // input, projects the scenario exactly along those paths, and does that many
5
+ // times from one seed. Everything it reports is a simulated answer: it
6
+ // carries its seed and the size of its own sampling error.
7
+ //
8
+ // Draws from continuous distributions are floating-point numbers; they are
9
+ // rounded to a stated grid (8 decimal places of the per-period rate by
10
+ // default) and from then on all arithmetic is exact, so two runs from the
11
+ // same seed agree to the cent on every machine.
12
+ import { Rational } from "@ratmath/core";
13
+ import { rng as makeRng } from "@ratmath/discrete";
14
+ import { SimulatedRate, proportionInterval, variance, sqrt, normal } from "@ratmath/stats";
15
+ import { refuse, amount, ZERO, ONE, Q, round, show } from "./money.js";
16
+ import { Scenario } from "./scenario.js";
17
+
18
+ const GRID = 8;
19
+ const fromFloat = (x, places = GRID) => {
20
+ if (!Number.isFinite(x)) refuse("bad-draw", `a draw came out as ${x}`);
21
+ const scale = 10 ** places;
22
+ return new Rational(BigInt(Math.round(x * scale)), 10n ** BigInt(places));
23
+ };
24
+ /** a draw from anything with sample(rng): a stats distribution, or your own */
25
+ const drawOf = (dist, rng, what) => {
26
+ if (!dist || typeof dist.sample !== "function") refuse("bad-process", `${what} needs a distribution with sample(rng), such as normal("7%", "15%") from @ratmath/stats`);
27
+ const x = dist.sample(rng);
28
+ if (x instanceof Rational) return x;
29
+ if (typeof x === "bigint") return new Rational(x);
30
+ return fromFloat(Number(x));
31
+ };
32
+ const whole = (n, what, min = 0) => (Number.isInteger(n) && n >= min ? n : refuse("bad-argument", `${what} is a whole number${min ? ` from ${min}` : ""}`));
33
+
34
+ /**
35
+ * The per-period growth factor that compounds to 1 + R over a year of m
36
+ * periods: exact when the root is rational (always when m = 1), otherwise
37
+ * rounded to the grid.
38
+ */
39
+ function perPeriod(R, m) {
40
+ const g = ONE.add(R);
41
+ if (g.numerator <= 0n) refuse("bad-draw", `a return of ${show(R, 4)} would leave less than nothing`);
42
+ if (m === 1) return g;
43
+ return ONE.add(fromFloat(g.toNumber() ** (1 / m) - 1));
44
+ }
45
+
46
+ export class Process {
47
+ /** `make(rng, periods, m)` returns an array of `periods` growth factors (Rationals). */
48
+ constructor(name, make, info = {}) {
49
+ this.name = name;
50
+ this.make = make;
51
+ Object.assign(this, info);
52
+ }
53
+ /** One path: growth factors for each period, from a generator or a seed. */
54
+ path(rng, periods, periodsPerYear = 12) {
55
+ const r = typeof rng === "object" && rng ? rng : makeRng(rng ?? 1);
56
+ const out = this.make(r, whole(periods, "periods", 1), whole(periodsPerYear, "periodsPerYear", 1));
57
+ if (out.length !== periods) throw new Error(`process ${this.name} gave ${out.length} factors for ${periods} periods`);
58
+ return out;
59
+ }
60
+ /** The same path as annual nominal rates per period, which is what a scenario account takes. */
61
+ rates(rng, periods, periodsPerYear = 12) {
62
+ const m = Q(periodsPerYear);
63
+ return this.path(rng, periods, periodsPerYear).map((g) => g.subtract(ONE).multiply(m));
64
+ }
65
+ toString() {
66
+ return this.name;
67
+ }
68
+ }
69
+
70
+ /** annual return R for each year, spread evenly over its periods */
71
+ const yearly = (name, drawYear, info) =>
72
+ new Process(name, (rng, periods, m) => {
73
+ const out = [];
74
+ for (let year = 0; out.length < periods; year++) {
75
+ const f = perPeriod(drawYear(rng, year), m);
76
+ for (let j = 0; j < m && out.length < periods; j++) out.push(f);
77
+ }
78
+ return out;
79
+ }, info);
80
+
81
+ export const processes = Object.freeze({
82
+ /** the same annual rate every year: no uncertainty, useful as a baseline */
83
+ fixed(rate) {
84
+ const R = amount(rate);
85
+ return yearly(`fixed(${R})`, () => R, { kind: "fixed", rate: R });
86
+ },
87
+ /** independent annual returns drawn from a distribution */
88
+ independent(dist) {
89
+ return yearly(`independent(${dist})`, (rng) => drawOf(dist, rng, "independent"), { kind: "independent", dist });
90
+ },
91
+ /** annual returns from a finite list with exact weights (default equal): small cases can be enumerated exactly */
92
+ choice(values, weights) {
93
+ const v = values.map(amount);
94
+ const w = (weights ?? v.map(() => 1)).map(amount);
95
+ if (w.length !== v.length || !v.length) refuse("bad-process", "choice needs as many weights as values");
96
+ const total = w.reduce((a, b) => a.add(b), ZERO);
97
+ // exact weighted draw: a uniform integer below the common denominator
98
+ const den = w.reduce((d, x) => lcm(d, x.denominator), total.denominator);
99
+ const ticks = w.map((x) => x.multiply(new Rational(den)).numerator);
100
+ const all = total.multiply(new Rational(den)).numerator;
101
+ return yearly(`choice(${v.join(", ")})`, (rng) => {
102
+ let u = rng.int(all);
103
+ for (let i = 0; i < v.length; i++) {
104
+ if (u < ticks[i]) return v[i];
105
+ u -= ticks[i];
106
+ }
107
+ return v[v.length - 1];
108
+ }, { kind: "choice", values: v, weights: w });
109
+ },
110
+ /** the annual returns given, in order (the last one repeats if the run is longer) */
111
+ sequence(returns) {
112
+ const r = returns.map(amount);
113
+ if (!r.length) refuse("bad-process", "sequence needs at least one return");
114
+ return yearly(`sequence(${r.length} years)`, (rng, year) => r[Math.min(year, r.length - 1)], { kind: "sequence", returns: r });
115
+ },
116
+ /** annual returns resampled from history the caller supplies, in blocks of `block` consecutive years */
117
+ resample(history, { block = 1 } = {}) {
118
+ const h = history.map(amount);
119
+ whole(block, "block", 1);
120
+ if (h.length < block) refuse("bad-process", "the history is shorter than one block");
121
+ return new Process(`resample(${h.length} years, block ${block})`, (rng, periods, m) => {
122
+ const years = [];
123
+ while (years.length * m < periods) {
124
+ const s = rng.int(h.length - block + 1);
125
+ for (let j = 0; j < block; j++) years.push(h[s + j]);
126
+ }
127
+ const out = [];
128
+ for (const R of years) {
129
+ const f = perPeriod(R, m);
130
+ for (let j = 0; j < m && out.length < periods; j++) out.push(f);
131
+ }
132
+ return out;
133
+ }, { kind: "resample", history: h, block });
134
+ },
135
+ /**
136
+ * Geometric Brownian motion with annual drift μ and volatility σ: each
137
+ * period's factor is exp((μ − σ²/2)Δt + σ√Δt·Z), Δt = 1/periodsPerYear,
138
+ * so E[factor over a year] = e^μ.
139
+ */
140
+ gbm({ drift, volatility }) {
141
+ const mu = amount(drift).toNumber();
142
+ const sigma = amount(volatility).toNumber();
143
+ if (sigma < 0) refuse("bad-process", "volatility is not negative");
144
+ const Z = normal(0, 1);
145
+ return new Process(`gbm(${drift}, ${volatility})`, (rng, periods, m) => {
146
+ const dt = 1 / m;
147
+ const out = [];
148
+ for (let k = 0; k < periods; k++) out.push(ONE.add(fromFloat(Math.expm1((mu - sigma * sigma / 2) * dt + sigma * Math.sqrt(dt) * Z.sample(rng)))));
149
+ return out;
150
+ }, { kind: "gbm", drift: amount(drift), volatility: amount(volatility) });
151
+ },
152
+ /**
153
+ * An interest rate that wanders: each year it moves by a draw from `step`,
154
+ * kept between `min` and `max`. The path is the rate credited (as rate/m
155
+ * each period), not a return.
156
+ */
157
+ walk({ start, step, min = "-1", max = "1" }) {
158
+ const [r0, lo, hi] = [amount(start), amount(min), amount(max)];
159
+ return new Process(`walk(${r0})`, (rng, periods, m) => {
160
+ const out = [];
161
+ let r = r0;
162
+ for (let k = 0; k < periods; k++) {
163
+ if (k > 0 && k % m === 0) {
164
+ r = r.add(drawOf(step, rng, "walk"));
165
+ if (r.compareTo(lo) < 0) r = lo;
166
+ if (r.compareTo(hi) > 0) r = hi;
167
+ }
168
+ out.push(ONE.add(r.divide(Q(m))));
169
+ }
170
+ return out;
171
+ }, { kind: "walk", start: r0, step, min: lo, max: hi });
172
+ },
173
+ /**
174
+ * A mean-reverting (Vasicek) rate: each period
175
+ * r ← r + speed·(mean − r)·Δt + volatility·√Δt·Z, kept at or above `floor`.
176
+ */
177
+ meanReverting({ start, mean, speed, volatility, floor = null }) {
178
+ const [r0, th, a, s] = [start, mean, speed, volatility].map((x) => amount(x).toNumber());
179
+ const fl = floor === null ? -Infinity : amount(floor).toNumber();
180
+ const Z = normal(0, 1);
181
+ return new Process(`meanReverting(${start} → ${mean})`, (rng, periods, m) => {
182
+ const dt = 1 / m;
183
+ const out = [];
184
+ let r = r0;
185
+ for (let k = 0; k < periods; k++) {
186
+ out.push(ONE.add(fromFloat(r * dt)));
187
+ r = Math.max(fl, r + a * (th - r) * dt + s * Math.sqrt(dt) * Z.sample(rng));
188
+ }
189
+ return out;
190
+ }, { kind: "meanReverting", start: amount(start), mean: amount(mean), speed: amount(speed), volatility: amount(volatility) });
191
+ },
192
+ });
193
+ function lcm(a, b) {
194
+ const g = (x, y) => (y === 0n ? x : g(y, x % y));
195
+ return (a / g(a, b)) * b;
196
+ }
197
+
198
+ /** occurrence multipliers for a one-off event: 0 most periods, the amount factor when it happens */
199
+ function eventIndex(e, rng, periods, m) {
200
+ const p = amount(e.probability);
201
+ if (p.numerator < 0n || p.compareTo(ONE) > 0) refuse("bad-event", `event "${e.name}": a probability is between 0 and 1`);
202
+ const per = e.per ?? "year";
203
+ if (per !== "year" && per !== "period") refuse("bad-event", 'per is "year" or "period"');
204
+ const hit = () => rng.bool(p);
205
+ const size = () => (e.amount !== undefined && typeof e.amount?.sample === "function" ? round(drawOf(e.amount, rng, "an event amount"), { places: 2 }) : ONE);
206
+ const out = new Array(periods).fill(ZERO);
207
+ const start = (e.start ?? 1) - 1;
208
+ const end = Math.min(periods, e.end ?? periods);
209
+ let happened = false;
210
+ if (per === "period") {
211
+ for (let k = start; k < end && !(e.once && happened); k++) if (hit()) (out[k] = size(), (happened = true));
212
+ } else {
213
+ for (let y = Math.floor(start / m); y * m < end && !(e.once && happened); y++) {
214
+ if (!hit()) continue;
215
+ const k = Math.max(start, y * m) + rng.int(Math.min(m, end - Math.max(start, y * m)));
216
+ out[k] = size();
217
+ happened = true;
218
+ }
219
+ }
220
+ return out;
221
+ }
222
+
223
+ /** The input to Scenario with this run's paths written in. */
224
+ function concrete(spec, paths, inflationIndex, indexed, events, rng, rounding) {
225
+ const m = spec.periodsPerYear ?? 12;
226
+ const periods = spec.periods;
227
+ const accounts = (spec.accounts ?? []).map((a) => (paths[a.name] ? { ...a, rates: paths[a.name] } : a));
228
+ const flows = (spec.flows ?? []).map((f) => (inflationIndex && indexed.has(f.name ?? "") ? { ...f, index: inflationIndex } : f));
229
+ for (const e of events) {
230
+ const idx = eventIndex(e, rng.fork(`event ${e.name}`), periods, m);
231
+ const amt = e.amount !== undefined && typeof e.amount?.sample === "function" ? ONE : amount(e.amount);
232
+ flows.push({ name: e.name, amount: amt, from: e.from, to: e.to, index: inflationIndex && e.indexed ? idx.map((x, k) => x.multiply(inflationIndex[k])) : idx });
233
+ }
234
+ return new Scenario({ ...spec, accounts, flows, rounding });
235
+ }
236
+
237
+ const KEEP = (p) => p.netWorth;
238
+
239
+ export class Simulation {
240
+ constructor(fields) {
241
+ Object.assign(this, fields);
242
+ this.kind = "simulated";
243
+ Object.freeze(this);
244
+ }
245
+ /** The p-quantile of the outcomes (0 ≤ p ≤ 1), by the nearest-rank rule: always one of the outcomes. */
246
+ quantile(p) {
247
+ return nearestRank(this.sorted, amount(p));
248
+ }
249
+ toString() {
250
+ const pct = this.percentiles;
251
+ return `${this.name ?? "simulation"}: ${this.runs} runs, seed ${JSON.stringify(this.seed)}; median ${show(pct[50] ?? this.quantile("1/2"), 2)}, mean ${show(this.mean, 2)} ± ${show(this.standardError, 2)}; ruin ${show(this.ruin.rate, 4)} [${show(this.ruin.interval.low, 4)}, ${show(this.ruin.interval.high, 4)}]`;
252
+ }
253
+ [Symbol.for("nodejs.util.inspect.custom")]() {
254
+ return this.toString();
255
+ }
256
+ }
257
+ function nearestRank(sorted, p) {
258
+ const n = sorted.length;
259
+ if (p.numerator < 0n || p.compareTo(ONE) > 0) refuse("bad-argument", "a quantile is between 0 and 1");
260
+ const r = p.multiply(Q(n));
261
+ let k = Number(r.numerator / r.denominator) + (r.denominator === 1n ? 0 : 1);
262
+ return sorted[Math.min(n, Math.max(1, k)) - 1];
263
+ }
264
+ const cmpQ = (a, b) => a.compareTo(b);
265
+
266
+ /**
267
+ * Many runs of a scenario with uncertain inputs.
268
+ *
269
+ * simulate(spec, {
270
+ * returns: { stocks: processes.gbm({ drift: "6%", volatility: "18%" }) },
271
+ * inflation: processes.independent(normal("2.5%", "1%")),
272
+ * indexed: ["spending"], // flows that grow with inflation
273
+ * events: [{ name: "repair", probability: "10%", amount: 5000, from: "cash" }],
274
+ * runs: 1000, seed: 1 })
275
+ *
276
+ * `returns` maps account names to processes whose path replaces the
277
+ * account's rate. `events` are one-off random flows: `probability` per year
278
+ * (or per period with per: "period"), `once` to stop after the first, an
279
+ * `amount` that is fixed or a distribution. Run i uses the stream
280
+ * rng(seed).fork("run i"), so a run does not depend on how many there are.
281
+ *
282
+ * The result: `outcomes` (one per run, in run order), `mean` (exact),
283
+ * `standardError`, `percentiles` and `quantile(p)`, `ruin` (how often an
284
+ * account that started at or above zero went below it, as a SimulatedRate
285
+ * with an exact Clopper–Pearson interval), `ruinTimes`, `bands` (percentiles
286
+ * of the tracked quantity at each period), and `real` outcomes in today's
287
+ * money when there is inflation. Balances are rounded to the cent each
288
+ * period unless the scenario names another rule or `rounding: false`.
289
+ */
290
+ export function simulate(spec, { returns = {}, inflation = null, indexed = [], events = [], runs = 1000, seed = 1, rounding, measure = KEEP, ruin = null, level = "0.95", percentiles = [5, 25, 50, 75, 95], track = "netWorth", name } = {}) {
291
+ if (spec instanceof Scenario) refuse("bad-argument", "simulate takes the scenario's description (the object you would pass to scenario), so it can write the paths in");
292
+ const R = whole(runs, "runs", 1);
293
+ const m = spec.periodsPerYear ?? 12;
294
+ const periods = whole(spec.periods, "periods", 1);
295
+ for (const [acct, proc] of Object.entries(returns)) {
296
+ if (!(proc instanceof Process)) refuse("bad-process", `returns.${acct} is not a process (use processes.gbm, processes.independent, …)`);
297
+ if (!(spec.accounts ?? []).some((a) => a.name === acct)) refuse("bad-process", `returns names an account "${acct}" that the scenario does not have`);
298
+ }
299
+ if (inflation !== null && !(inflation instanceof Process)) refuse("bad-process", "inflation is a process");
300
+ const ix = new Set(indexed);
301
+ for (const f of ix) if (!(spec.flows ?? []).some((g) => g.name === f)) refuse("bad-process", `indexed names a flow "${f}" that the scenario does not have`);
302
+ const rule = rounding !== undefined ? rounding : spec.rounding !== undefined && spec.rounding !== false ? spec.rounding : 2;
303
+ const base = makeRng(seed);
304
+ const outcomes = [];
305
+ const real = [];
306
+ const series = Array.from({ length: periods + 1 }, () => []);
307
+ let ruined = 0;
308
+ const ruinTimes = [];
309
+ for (let i = 0; i < R; i++) {
310
+ const rng = base.fork(`run ${i}`);
311
+ const paths = {};
312
+ for (const [acct, proc] of Object.entries(returns)) paths[acct] = proc.rates(rng.fork(`returns ${acct}`), periods, m);
313
+ let index = null;
314
+ if (inflation) {
315
+ const g = inflation.path(rng.fork("inflation"), periods, m);
316
+ index = [];
317
+ let acc = ONE;
318
+ for (const f of g) index.push((acc = rule === false ? acc.multiply(f) : round(acc.multiply(f), { places: GRID })));
319
+ }
320
+ // the price level is kept to the grid (exact when rounding is off); a flow is indexed by the level at the start of its period
321
+ const flowIndex = index ? [ONE, ...index.slice(0, -1)] : null;
322
+ const proj = concrete(spec, paths, flowIndex, ix, events, rng, rule).project();
323
+ const out = measure(proj);
324
+ outcomes.push(out);
325
+ if (index) real.push(out.divide(index[index.length - 1]));
326
+ const bad = ruin ? ruin(proj) : proj.firstNegative !== null;
327
+ if (bad) {
328
+ ruined++;
329
+ if (proj.firstNegative) ruinTimes.push(proj.firstNegative.period);
330
+ }
331
+ const pick = (row) => (track === "netWorth" ? row.netWorth : row.balances[track]);
332
+ series[0].push(pick(proj.opening));
333
+ proj.rows.forEach((row, k) => series[k + 1].push(pick(row)));
334
+ }
335
+ const sorted = [...outcomes].sort(cmpQ);
336
+ const mean = outcomes.reduce((a, b) => a.add(b), ZERO).divide(Q(R));
337
+ const se = R > 1 ? sqrt(variance(outcomes).divide(Q(R)), 40) : null;
338
+ const ps = percentiles.map((p) => amount(p));
339
+ const pctOf = (xs) => Object.fromEntries(ps.map((p) => [p.toString(), nearestRank(xs, p.divide(Q(100)))]));
340
+ const bands = series.map((xs, k) => ({ period: k, ...pctOf([...xs].sort(cmpQ)) }));
341
+ const ci = proportionInterval(ruined, R, { level });
342
+ return new Simulation({
343
+ name,
344
+ seed,
345
+ runs: R,
346
+ rounding: rule,
347
+ outcomes,
348
+ sorted,
349
+ mean,
350
+ standardError: se,
351
+ percentiles: pctOf(sorted),
352
+ ruin: new SimulatedRate({ rate: Q(ruined, R), hits: ruined, runs: R, seed, interval: { low: ci.low, high: ci.high, level: ci.level } }),
353
+ ruinTimes,
354
+ bands,
355
+ real: index_or_null(real, R),
356
+ });
357
+ }
358
+ const index_or_null = (real, R) => (real.length === R ? Object.freeze({ outcomes: real, mean: real.reduce((a, b) => a.add(b), ZERO).divide(Q(R)), median: nearestRank([...real].sort(cmpQ), Q(1, 2)) }) : null);
359
+
360
+ /**
361
+ * The order of good and bad years. The same annual returns are applied to
362
+ * an account in several orders (as given, reversed, best first, worst first,
363
+ * and `shuffles` random orders from `seed`) and each projection is exact.
364
+ * With no money going in or out the order cannot matter (multiplication
365
+ * commutes), and `orderMatters` is false; withdrawals or contributions make
366
+ * it matter, and `spread` says by how much.
367
+ */
368
+ export function sequenceRisk(spec, { account, returns, shuffles = 0, seed = 1, measure = KEEP } = {}) {
369
+ const r = returns.map(amount);
370
+ const m = spec.periodsPerYear ?? 12;
371
+ if (!(spec.accounts ?? []).some((a) => a.name === account)) refuse("bad-argument", `the scenario has no account "${account}"`);
372
+ if (spec.periods > r.length * m) refuse("bad-argument", `${r.length} annual returns cover ${r.length * m} periods; the scenario has ${spec.periods}`);
373
+ const orders = [
374
+ ["as given", r],
375
+ ["reversed", [...r].reverse()],
376
+ ["best first", [...r].sort((a, b) => b.compareTo(a))],
377
+ ["worst first", [...r].sort((a, b) => a.compareTo(b))],
378
+ ];
379
+ const g = makeRng(seed);
380
+ for (let i = 0; i < shuffles; i++) orders.push([`shuffle ${i + 1}`, g.fork(`shuffle ${i}`).shuffle(r)]);
381
+ const rows = orders.map(([label, seq]) => {
382
+ const rates = processes.sequence(seq).rates(null, spec.periods, m);
383
+ const proj = new Scenario({ ...spec, accounts: spec.accounts.map((a) => (a.name === account ? { ...a, rates } : a)) }).project();
384
+ return { order: label, returns: seq, outcome: measure(proj), firstNegative: proj.firstNegative };
385
+ });
386
+ const outs = rows.map((x) => x.outcome);
387
+ const hi = outs.reduce((a, b) => (b.compareTo(a) > 0 ? b : a));
388
+ const lo = outs.reduce((a, b) => (b.compareTo(a) < 0 ? b : a));
389
+ return { rows, best: rows.find((x) => x.outcome.equals(hi)).order, worst: rows.find((x) => x.outcome.equals(lo)).order, spread: hi.subtract(lo), orderMatters: !hi.equals(lo) };
390
+ }