Repository Public
1import type { Locale } from "@/schema";2import { createRng, mean as avg } from "../core";3import { numberOption, option, optionError, param, type ParamDef, type SimConfig, type SimDef } from "../types";4import { fmt, fmtInt } from "../ui/format";5import { Plot, type PlotLayer } from "../ui/Plot";6import { Readouts } from "../ui/Readouts";78export const PROCESSES = ["brownian", "gbm", "ou"] as const;9export type Process = (typeof PROCESSES)[number];10export const WALK_STEPS = 100;11const X0: Record<Process, number> = { brownian: 0, gbm: 100, ou: 2 };1213const common = [param("paths", "Trajectoires", "Paths", 1, 20, 1, 8), param("horizon", "Horizon T", "Horizon T", 1, 20, 1, 5)];14const PARAMS: Record<Process, ParamDef[]> = {15 brownian: [param("drift", "Dérive μ", "Drift μ", -2, 2, 0.1, 0.5), param("volatility", "Volatilité σ", "Volatility σ", 0.1, 3, 0.1, 1), ...common],16 gbm: [param("drift", "Dérive μ", "Drift μ", -0.3, 0.5, 0.01, 0.08), param("volatility", "Volatilité σ", "Volatility σ", 0.05, 0.8, 0.01, 0.2), ...common],17 ou: [param("drift", "Niveau de long terme μ", "Long-run level μ", -2, 2, 0.1, 0), param("volatility", "Volatilité σ", "Volatility σ", 0.1, 2, 0.1, 0.5), param("reversion", "Force de rappel θ", "Mean reversion θ", 0.1, 5, 0.1, 1), ...common],18};1920export interface WalkModel {21 process: Process; x0: number; horizon: number;22 times: number[];23 paths: number[][];24 /** Theoretical mean and standard deviation of X_t given X_0. */25 mean: number[]; sd: number[];26 /** Average of the simulated terminal values. */27 terminalSampleMean: number;28}2930/** Closed-form moments of X_t given X_0 = x0. */31export function walkMoments(process: Process, x0: number, mu: number, sigma: number, theta: number, t: number): { mean: number; sd: number } {32 if (process === "brownian") return { mean: x0 + mu * t, sd: sigma * Math.sqrt(t) };33 if (process === "gbm") { const m = x0 * Math.exp(mu * t); return { mean: m, sd: m * Math.sqrt(Math.expm1(sigma * sigma * t)) }; }34 return { mean: mu + (x0 - mu) * Math.exp(-theta * t), sd: sigma * Math.sqrt(-Math.expm1(-2 * theta * t) / (2 * theta)) };35}3637/** All three processes are simulated with their exact transition law, so there is no discretisation error at the grid points. */38export function computeWalk(p: Readonly<Record<string, number>>, seed: number, config: SimConfig): WalkModel {39 const process = option(config, "process", PROCESSES);40 const x0 = process === "gbm" ? numberOption(config, "x0", X0.gbm, 0.01, 1e6) : numberOption(config, "x0", X0[process], -1e6, 1e6);41 const mu = p.drift, sigma = p.volatility, theta = p.reversion ?? 1, T = p.horizon, nPaths = Math.round(p.paths);42 const dt = T / WALK_STEPS;43 const times = Array.from({ length: WALK_STEPS + 1 }, (_, i) => i * dt);44 const rng = createRng(seed, "walk");45 const decay = Math.exp(-theta * dt), ouSd = sigma * Math.sqrt(-Math.expm1(-2 * theta * dt) / (2 * theta));46 const paths: number[][] = [];47 for (let k = 0; k < nPaths; k++) {48 const path = [x0];49 let x = x0;50 for (let i = 0; i < WALK_STEPS; i++) {51 const z = rng.normal();52 if (process === "brownian") x += mu * dt + sigma * Math.sqrt(dt) * z;53 else if (process === "gbm") x *= Math.exp((mu - 0.5 * sigma * sigma) * dt + sigma * Math.sqrt(dt) * z);54 else x = mu + (x - mu) * decay + ouSd * z;55 path.push(x);56 }57 paths.push(path);58 }59 const moments = times.map((t) => walkMoments(process, x0, mu, sigma, theta, t));60 return { process, x0, horizon: T, times, paths, mean: moments.map((m) => m.mean), sd: moments.map((m) => m.sd), terminalSampleMean: avg(paths.map((q) => q[WALK_STEPS])) };61}6263const NAMES: Record<Process, { fr: string; en: string }> = {64 brownian: { fr: "Mouvement brownien avec dérive", en: "Brownian motion with drift" },65 gbm: { fr: "Mouvement brownien géométrique", en: "Geometric Brownian motion" },66 ou: { fr: "Processus d'Ornstein–Uhlenbeck", en: "Ornstein–Uhlenbeck process" },67};68const TXT = {69 fr: { t: "Temps t", x: "X_t", paths: "trajectoires simulées", mean: "espérance théorique", band: "espérance ± 2 écarts-types", proc: "Processus", tm: "Espérance théorique en T", tsd: "Écart-type théorique en T", sm: "Moyenne simulée en T", n: "Trajectoires" },70 en: { t: "Time t", x: "X_t", paths: "simulated paths", mean: "theoretical mean", band: "mean ± 2 standard deviations", proc: "Process", tm: "Theoretical mean at T", tsd: "Theoretical standard deviation at T", sm: "Simulated mean at T", n: "Paths" },71} as const;7273function WalkView({ model: m, locale, idPrefix }: { model: WalkModel; locale: Locale; idPrefix: string }) {74 const L = TXT[locale];75 const last = m.times.length - 1;76 const layers: PlotLayer[] = [77 { type: "band", points: m.times.map((t, i) => ({ x: t, lo: m.mean[i] - 2 * m.sd[i], hi: m.mean[i] + 2 * m.sd[i] })), tone: "amber", name: L.band, opacity: 0.14 },78 ...m.paths.map((path, k): PlotLayer => ({ type: "line", points: path.map((y, i) => ({ x: m.times[i], y })), tone: "blue", width: 1.2, opacity: 0.6, ...(k === 0 ? { name: L.paths } : {}) })),79 { type: "line", points: m.times.map((t, i) => ({ x: t, y: m.mean[i] })), tone: "amber", name: L.mean, dashed: true },80 ];81 return (82 <>83 <Plot locale={locale} idPrefix={idPrefix} spec={{ title: NAMES[m.process][locale], xLabel: L.t, yLabel: L.x, xDomain: [0, m.horizon], layers }} />84 <Readouts items={[85 { label: L.proc, value: NAMES[m.process][locale] },86 { label: L.tm, value: fmt(locale, m.mean[last], 3), tone: "amber" },87 { label: L.tsd, value: fmt(locale, m.sd[last], 3) },88 { label: L.sm, value: fmt(locale, m.terminalSampleMean, 3), tone: "blue" },89 { label: L.n, value: fmtInt(locale, m.paths.length) },90 ]} />91 </>92 );93}9495export const randomWalk: SimDef<WalkModel> = {96 kind: "random-walk",97 title: { fr: "Trajectoires d'un processus stochastique", en: "Paths of a stochastic process" },98 description: {99 fr: "Brownien : $dX = \\mu\\,dt + \\sigma\\,dW$. Géométrique : $dS = \\mu S\\,dt + \\sigma S\\,dW$ ($S$ reste positif). Ornstein–Uhlenbeck : $dX = \\theta(\\mu - X)\\,dt + \\sigma\\,dW$ (retour vers $\\mu$). Chaque trajectoire est simulée avec la loi de transition exacte ; la bande est l'espérance théorique ± 2 écarts-types. Pour le brownien géométrique, la loi est log-normale : cette bande symétrique n'est qu'un repère, pas un intervalle à 95 %.",100 en: "Brownian: $dX = \\mu\\,dt + \\sigma\\,dW$. Geometric: $dS = \\mu S\\,dt + \\sigma S\\,dW$ ($S$ stays positive). Ornstein–Uhlenbeck: $dX = \\theta(\\mu - X)\\,dt + \\sigma\\,dW$ (pull towards $\\mu$). Each path uses the exact transition law; the band is the theoretical mean ± 2 standard deviations. For geometric Brownian motion the law is log-normal: that symmetric band is a guide, not a 95% interval.",101 },102 params: PARAMS.brownian,103 stochastic: true,104 configKeys: ["process", "x0"],105 paramsFor: (c) => PARAMS[option(c, "process", PROCESSES)],106 validateConfig: (c) => {107 const out = optionError(c, "process", PROCESSES);108 if (c.x0 !== undefined && typeof c.x0 !== "number") out.push("config.x0: expected a number");109 if (typeof c.x0 === "number" && c.process === "gbm" && c.x0 <= 0) out.push("config.x0: must be positive for a geometric Brownian motion");110 return out;111 },112 compute: computeWalk,113 View: WalkView,114};115