// SPDX-License-Identifier: GPL-3.0-or-later // Ported from dfagnan/RBOMatlab (Fagnan et al.), GPL-3.0-or-later. Copyright of the original: David Fagnan, Austin // Gromatzky, Jose-Maria Fernandez, Roger M. Stein, Andrew W. Lo. This port: Udgam Labs, 2026. // // Megafund simulator, browser port. // // A line-by-line TypeScript port of the lab's Python simulator (private, not published), which is // itself a port of RBOMatlab's `simulate_CFs_fn` (Fagnan, Gromatzky, Fernandez, Stein, Lo; Markov mode, one compound // type, no guarantee). The Python simulator was the reference; this file follows its order of random draws exactly, so // that both give the same result on the same random stream (scripts/megafund/gate.ts checks this). // Licence: GPL-3.0-or-later (founder, 22 Nov 2026). The source is offered at udgamlabs.com/tools/megafund#source (the files sit under /tools/megafund/source/). export type FundParams = { rho: number pricing: number[][] sell_in_phase: string sale_time: number[] ratio_unchanged: number equity_stake: number capital_structure: number[] ic_pers: number interest_coverage: number[] amort_timing: number[][] coupon: number[] servicing_rate: number svc_accrual: number cash_accrual: number initial_cash: number initial_compounds: number[] } export interface Rng { normal(): number random(): number } const SLD = 0, DSC = 1, PRE = 2, P3 = 5, NDA = 6, APP = 7 const NAMES: Record = { DSC: 1, PRE: 2, P1: 3, P2: 4, P3: 5, NDA: 6, APP: 7 } const VMU = 0, VSIG = 1, VMX = 2, UPF = 3, MIL = 4, CMU = 5, CSIG = 6, CMX = 7, FCE = 8 // --- numerics that must match Python/numpy --------------------------------------------------------------------------- /** numpy's pairwise summation (np.sum on a contiguous 1-D float64 array). */ function npSum(a: ArrayLike, start = 0, n = a.length - start): number { if (n < 8) { let res = 0 for (let i = 0; i < n; i++) res += a[start + i] return res } if (n <= 128) { const r = [a[start], a[start + 1], a[start + 2], a[start + 3], a[start + 4], a[start + 5], a[start + 6], a[start + 7]] let i = 8 for (; i < n - (n % 8); i += 8) for (let j = 0; j < 8; j++) r[j] += a[start + i + j] let res = ((r[0] + r[1]) + (r[2] + r[3])) + ((r[4] + r[5]) + (r[6] + r[7])) for (; i < n; i++) res += a[start + i] return res } let n2 = Math.floor(n / 2) n2 -= n2 % 8 return npSum(a, start, n2) + npSum(a, start + n2, n - n2) } /** Python's round() on a float: ties to even. */ function pyRound(x: number): number { const f = Math.floor(x) const d = x - f if (d > 0.5) return f + 1 if (d < 0.5) return f return f % 2 === 0 ? f : f + 1 } /** erf by its all-positive series, accurate to about 1e-16 (no cancellation); |x| >= 6 gives ±1. */ function erf(x: number): number { const ax = Math.abs(x) if (ax >= 6) return x > 0 ? 1 : -1 const x2 = ax * ax let term = ax let sum = ax for (let n = 0; n < 400; n++) { term *= (2 * x2) / (2 * n + 3) sum += term if (term < sum * 1e-17) break } const v = (2 / Math.sqrt(Math.PI)) * Math.exp(-x2) * sum return x < 0 ? -v : v } const ndtr = (x: number) => 0.5 * (1 + erf(x / Math.SQRT2)) // --- random numbers -------------------------------------------------------------------------------------------------- /** xoshiro128** seeded through splitmix32; 53-bit uniforms; Marsaglia polar normals. Fixed seed -> fixed numbers. */ class Xoshiro implements Rng { private a: number private b: number private c: number private d: number private spare = 0 private hasSpare = false constructor(seed: number) { let s = seed | 0 const sm = () => { s = (s + 0x9e3779b9) | 0 let z = s z = Math.imul(z ^ (z >>> 16), 0x85ebca6b) z = Math.imul(z ^ (z >>> 13), 0xc2b2ae35) return z ^ (z >>> 16) } this.a = sm() this.b = sm() this.c = sm() this.d = sm() } private next(): number { const b = this.b const x = Math.imul(b, 5) const r = Math.imul((x << 7) | (x >>> 25), 9) const t = b << 9 this.c ^= this.a this.d ^= b this.b ^= this.c this.a ^= this.d this.c ^= t this.d = (this.d << 11) | (this.d >>> 21) return r } random(): number { return ((this.next() >>> 5) * 67108864 + (this.next() >>> 6)) / 9007199254740992 } normal(): number { if (this.hasSpare) { this.hasSpare = false return this.spare } let u = 0, v = 0, q = 0 do { u = 2 * this.random() - 1 v = 2 * this.random() - 1 q = u * u + v * v } while (q >= 1 || q === 0) const m = Math.sqrt((-2 * Math.log(q)) / q) this.spare = v * m this.hasSpare = true return u * m } } export function makeRng(seed: number): Rng { return new Xoshiro(seed) } // --- the fund -------------------------------------------------------------------------------------------------------- export type RunResult = { roe: number; A1: boolean; A2: boolean; svc: boolean } export class Fund { p: FundParams T: number[][] cd: Float64Array[] // cumulative rows of T, last entry forced to 1 (as sim.py's step_phase) pp: number[][] rho: number transRho: number sell: number npers: number saleLag: number horizon: number nominal: number[] coupon: number[] nb: number amort: number[][] start: Int32Array svc: number eq: number constructor(p: FundParams, transProb: number[][], transRho = 0, valueRho?: number) { this.p = p this.T = transProb this.cd = transProb.map((row) => { const c = new Float64Array(row.length) let s = 0 for (let j = 0; j < row.length; j++) c[j] = s += row[j] c[row.length - 1] = 1 return c }) this.pp = p.pricing this.rho = valueRho === undefined ? p.rho : valueRho this.transRho = transRho this.sell = NAMES[p.sell_in_phase] const amort = p.amort_timing.map((r) => r.map((x) => Math.trunc(x))) this.npers = Math.max(...amort.flat()) + 1 this.saleLag = Math.ceil(Math.max(...p.sale_time)) this.horizon = this.npers + this.saleLag this.nominal = p.capital_structure.map((x) => p.initial_cash * x) this.coupon = p.coupon this.nb = this.nominal.length - 1 this.amort = Array.from({ length: this.nb }, () => new Array(this.npers + 1).fill(0)) const left = this.nominal.slice(0, this.nb) for (let t = 1; t <= this.npers; t++) { for (let b = 0; b < this.nb; b++) { const [a0, a1] = amort[b] if (a0 <= t && t <= a1) { const due = this.nominal[b] / (a1 - a0 + 1) this.amort[b][t] = due < left[b] ? due : left[b] } left[b] -= this.amort[b][t] } } const st: number[] = [] p.initial_compounds.forEach((cnt, i) => { for (let k = 0; k < cnt; k++) st.push(i + 1) }) this.start = Int32Array.from(st) this.svc = p.servicing_rate this.eq = p.equity_stake } /** sim.py trial_cost: one normal per compound in PRE..P3, in index order; others cost 0. */ private trialCost(phase: Int32Array, rng: Rng, out: Float64Array) { for (let k = 0; k < phase.length; k++) { const ph = phase[k] if (ph >= PRE && ph <= P3) { const r = this.pp[ph - 1] out[k] = Math.min(Math.exp(rng.normal() * r[CSIG] + r[CMU]), r[CMX]) } else out[k] = 0 } } private price(ph: number, z: number, rng: Rng) { const r = this.pp[ph - 1] const e = rng.normal() const x = this.rho === 0 ? e : Math.sqrt(this.rho) * z + Math.sqrt(1 - this.rho) * e return Math.min(Math.exp(x * r[VSIG] + r[VMU]), r[VMX]) * this.eq } runOne(rng: Rng): RunResult { const p = this.p const H = this.horizon, NP = this.npers, icPers = p.ic_pers, nb = this.nb const n = this.start.length const phase = Int32Array.from(this.start) const invested = new Uint8Array(n) const acquired = new Uint8Array(n) const tip = new Int32Array(n) const cash = new Float64Array(H + 2) cash[1] = p.initial_cash const bv = this.nominal.slice() let unpaid = 0 let inDefault = false const dflt = { svc: false, A1: false, A2: false } const cost = new Float64Array(n) this.trialCost(phase, rng, cost) const ps = this.sell - 1 let couponDue = 0 { const tmp = new Float64Array(nb) for (let b = 0; b < nb; b++) tmp[b] = this.nominal[b] * this.coupon[b] couponDue = npSum(tmp) } let left = cash[1] - icPers * couponDue for (let k = 0; k < n; k++) { const priceTmp = cost[k] + this.pp[phase[k] - 1][UPF] const fce = (ps >= 1 ? 1 : 0) * (this.pp[phase[k] - 1][FCE] - this.pp[ps - 1][FCE]) if (left >= priceTmp + fce) { left -= priceTmp + fce cash[1] -= priceTmp invested[k] = acquired[k] = 1 } else phase[k] = DSC } cash[2] = cash[1] const z = rng.normal() const prBuf = new Float64Array(n) const idxBuf = new Int32Array(n) const tc = new Float64Array(n) const old = new Int32Array(n) const elig = new Uint8Array(n) const sellM = new Uint8Array(n) const transM = new Uint8Array(n) // sale(idx): price draws in idx order; uninvested compounds give back their unpaid trial cost const sale = (m: number) => { for (let j = 0; j < m; j++) { const k = idxBuf[j] let pr = this.price(phase[k], z, rng) if (!invested[k]) pr = Math.max(pr - cost[k], 0) prBuf[j] = pr } } const book = (ids: ArrayLike, prs: ArrayLike, m: number, t: number) => { cash[Math.min(t + this.saleLag, H)] += npSum(prs, 0, m) for (let j = 0; j < m; j++) { phase[ids[j]] = SLD tip[ids[j]] = 0 } } const collectLive = () => { let m = 0 for (let k = 0; k < n; k++) if (phase[k] !== DSC && phase[k] !== SLD) idxBuf[m++] = k return m } const liquidate = (t: number) => { const m = collectLive() if (m) { sale(m) for (let j = 0; j < m; j++) if (tip[idxBuf[j]] === t - 1) prBuf[j] *= p.ratio_unchanged book(idxBuf.slice(0, m), prBuf.slice(0, m), m, t) } } const bvSum = () => npSum(bv) const svcDue = () => this.svc * bvSum() + unpaid * (1 + p.svc_accrual) for (let t = 2; t <= NP; t++) { let cur = cash[t] old.set(phase) // step_phase on eligible compounds, in index order let ne = 0 for (let k = 0; k < n; k++) { const e = invested[k] && phase[k] !== DSC && phase[k] !== SLD && phase[k] !== APP ? 1 : 0 elig[k] = e ne += e } if (ne) { if (this.transRho === 0) { for (let k = 0; k < n; k++) if (elig[k]) phase[k] = this.stepOne(phase[k], rng.random()) } else { const zt = rng.normal() const a = Math.sqrt(this.transRho), b = Math.sqrt(1 - this.transRho) for (let k = 0; k < n; k++) if (elig[k]) phase[k] = this.stepOne(phase[k], ndtr(a * zt + b * rng.normal())) } } let ns = 0 for (let k = 0; k < n; k++) { sellM[k] = elig[k] && (phase[k] === this.sell || phase[k] === APP) ? 1 : 0 if (sellM[k]) idxBuf[ns++] = k } if (ns) { sale(ns) book(idxBuf.slice(0, ns), prBuf.slice(0, ns), ns, t) } let anyTrans = false for (let k = 0; k < n; k++) { const dsc = elig[k] && phase[k] === DSC if (dsc) tip[k] = 0 transM[k] = elig[k] && !sellM[k] && !dsc && phase[k] !== old[k] ? 1 : 0 if (transM[k]) anyTrans = true } if (anyTrans) { const nda = new Uint8Array(n) for (let k = 0; k < n; k++) nda[k] = phase[k] === NDA ? 1 : 0 for (let k = 0; k < n; k++) if (nda[k] && transM[k]) invested[k] = 1 for (let k = 0; k < n; k++) if (!nda[k] && transM[k]) invested[k] = 0 this.trialCost(phase, rng, tc) for (let k = 0; k < n; k++) if (!nda[k] && transM[k]) cost[k] = tc[k] + this.pp[phase[k] - 1][MIL] for (let k = 0; k < n; k++) if (transM[k]) tip[k] = 0 } for (let k = 0; k < n; k++) { // stat = elig & ~sell & ~dsc & ~trans (dsc judged on the phase after the step) if (elig[k] && !sellM[k] && !(phase[k] === DSC) && !transM[k]) tip[k] += 1 } if (!inDefault) { const due = svcDue() const a1 = this.amort[0][t] + bv[0] * this.coupon[0] const a2 = this.amort[1][t] + bv[1] * this.coupon[1] if (cur < due) { dflt.svc = true dflt.A1 = dflt.A1 || bv[0] > 0 dflt.A2 = dflt.A2 || bv[1] > 0 } else if (cur < due + a1) { dflt.A1 = true dflt.A2 = dflt.A2 || bv[1] > 0 } else if (cur < due + a1 + a2 && bv[1] > 0) { dflt.A2 = true } inDefault = dflt.svc || dflt.A1 || dflt.A2 } if (!inDefault) { const due = svcDue() const paid = Math.min(due, cur) unpaid = pyRound((due - paid) * 1e5) / 1e5 cur -= paid for (let b = 0; b < nb; b++) cur -= Math.min(this.coupon[b] * bv[b], cur) for (let b = 0; b < nb; b++) { const prPaid = Math.min(this.amort[b][t], cur) cur -= prPaid bv[b] -= prPaid if (bv[b] < 1e-4) bv[b] = 0 } const icShort = new Float64Array(nb) for (let b = 0; b < nb; b++) { if (bv[b] > 0) { const kCash = cur + npSum(cash, t + 1, Math.min(icPers, cash.length - t - 1)) const [dueB, kLeft] = this.ic(b, t, kCash, bv, unpaid) icShort[b] = p.interest_coverage[b] * dueB - kLeft } } const eqDue = unpaid + this.saleLag * bv[bv.length - 1] * this.svc let icMax = icShort[0] for (let b = 1; b < nb; b++) if (icShort[b] > icMax) icMax = icShort[b] const short = Math.max(icMax, eqDue - cur) if (short > 0) { const m = collectLive() if (m) { sale(m) const order = Array.from({ length: m }, (_, j) => j).sort((x, y) => -prBuf[x] - -prBuf[y]) let cum = 0 let nsold = m for (let j = 0; j < m; j++) { cum += prBuf[order[j]] if (cum >= short) { nsold = j + 1 break } } const ids = new Int32Array(nsold) const prs = new Float64Array(nsold) for (let j = 0; j < nsold; j++) { ids[j] = idxBuf[order[j]] prs[j] = prBuf[order[j]] } book(ids, prs, nsold, t) } } else if (t < NP) { const nxt: number[] = [] if (t < NP - icPers) for (let q = t + 1; q <= t + icPers; q++) nxt.push(q) else nxt.push(t + 1) const am = new Float64Array(nb * nxt.length) let q = 0 for (let b = 0; b < nb; b++) for (const c of nxt) am[q++] = this.amort[b][c] const cb = new Float64Array(nb) for (let b = 0; b < nb; b++) cb[b] = this.coupon[b] * bv[b] const need = npSum(am) + nxt.length * (npSum(cb) + this.svc * bvSum()) let avail = Math.max(cur - need, 0) if (avail > 0) { let spent = 0 const cand: number[] = [] for (let k = 0; k < n; k++) if (phase[k] !== DSC && phase[k] !== APP && phase[k] !== SLD && acquired[k] && !invested[k]) cand.push(k) for (const k of cand) { if (cost[k] <= avail) { invested[k] = 1 avail -= cost[k] spent += cost[k] } } cur -= spent } } } else { liquidate(t) for (let b = 0; b < nb; b++) { if (cur > 0) { const iPaid = Math.min(cur, this.coupon[b] * bv[b]) cur -= iPaid const prPaid = Math.min(cur, bv[b]) bv[b] -= prPaid if (bv[b] < 1e-4) bv[b] = 0 cur -= prPaid } } if (!dflt.A1 && dflt.A2 && bv[0] > 0) dflt.A1 = true } cash[t] = cur if (t !== NP) cash[t + 1] += cur * (1 + p.cash_accrual) } liquidate(NP) for (let t = NP; t < H; t++) { let cur = cash[t] if (!inDefault) { const due = svcDue() const paid = Math.min(due, cur) unpaid = pyRound((due - paid) * 1e5) / 1e5 cur -= paid } cash[t] = cur cash[t + 1] = cash[t] + cash[t + 1] } const eqNom = this.nominal[this.nominal.length - 1] const roe = Math.max((cash[H] - eqNom) / eqNom, -1) return { roe, A1: dflt.A1, A2: dflt.A2, svc: dflt.svc } } private stepOne(ph: number, u: number) { const cd = this.cd[ph - 1] let c = 0 for (let j = 0; j < cd.length; j++) if (u >= cd[j]) c++ return c + 1 } private ic(b: number, t: number, kCash: number, bv: number[], unpaid: number): [number, number] { const NP = this.npers, icPers = this.p.ic_pers if (t === NP) return [0, kCash] const nAhead = Math.min(icPers, NP - t) let k = kCash for (let bb = 0; bb < b; bb++) { let btemp = bv[bb] for (let m = 1; m <= nAhead; m++) { k -= this.amort[bb][t + m] + this.coupon[bb] * btemp + this.svc * btemp btemp -= this.amort[bb][t + m] } } let sp = 0, si = 0 let ss = unpaid let bvb = bv[b] for (let m = 1; m <= nAhead; m++) { sp += this.amort[b][t + m] si += this.coupon[b] * bvb ss += this.svc * bvb bvb -= this.amort[b][t + m] } return [sp + si + ss, k] } } // --- summary --------------------------------------------------------------------------------------------------------- export type Summary = { nsims: number years: number roe_ann_mean: number roe_ann_se: number roe_ann_sd: number p_equity_loss: number p_default_A1: number p_default_A2: number } /** The same statistics as sim.py Fund.run, from a list of runs. */ export function summarise(runs: RunResult[], horizon: number): Summary { const nsims = runs.length const years = horizon / 2 const ann = Float64Array.from(runs, (r) => Math.pow(1 + r.roe, 1 / years) - 1) const mean = npSum(ann) / nsims let ss = 0 for (let i = 0; i < nsims; i++) ss += (ann[i] - mean) * (ann[i] - mean) const sd = Math.sqrt(ss / (nsims - 1)) return { nsims, years, roe_ann_mean: mean, roe_ann_se: sd / Math.sqrt(nsims), roe_ann_sd: sd, p_equity_loss: runs.filter((r) => r.roe < 0).length / nsims, p_default_A1: runs.filter((r) => r.A1).length / nsims, p_default_A2: runs.filter((r) => r.A2).length / nsims, } } export const annualise = (roe: number, horizon: number) => Math.pow(1 + roe, 2 / horizon) - 1