Traits and generics
Running project · riskforgeProject: diffusion models
So far riskforge valued the portfolio for a single spot price. The heart of a risk engine is to simulate thousands of future paths of that price, then measure exposure on each one. The way the price evolves is called a diffusion model, and there are many of them: a textbook case for a trait.
Two models to start with. Geometric Brownian motion (GBM), the classic for equities: the price moves by relative changes, with a trend (drift) and a volatility. The Ornstein-Uhlenbeck process, which reverts toward a mean level, suited to commodities and close to the Hull-White model used for rates.
pub trait DiffusionModel { /// Valeur après un pas de temps dt (en années), à partir d'un tirage normal z. fn step(&self, current: f64, dt: f64, z: f64) -> f64; fn name(&self) -> String { String::from("model") }} pub struct Gbm { pub drift: f64, pub volatility: f64,} impl DiffusionModel for Gbm { fn step(&self, current: f64, dt: f64, z: f64) -> f64 { let sigma = self.volatility; current * ((self.drift - 0.5 * sigma * sigma) * dt + sigma * dt.sqrt() * z).exp() } fn name(&self) -> String { format!("GBM(mu={}, sigma={})", self.drift, self.volatility) }} /// Générateur minimal pour l'exemple (riskforge fournit le sien dans src/rng.rs).struct Lcg(u64); impl Lcg { fn uniform(&mut self) -> f64 { self.0 = self.0.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); ((self.0 >> 11) as f64 + 0.5) / (1u64 << 53) as f64 } fn normal(&mut self) -> f64 { let (u1, u2) = (self.uniform(), self.uniform()); (-2.0 * u1.ln()).sqrt() * (2.0 * std::f64::consts::PI * u2).cos() }} /// Générique : une version spécialisée est compilée pour chaque modèle.fn simulate_terminal<M: DiffusionModel>(model: &M, spot: f64, years: f64, steps: usize, paths: usize) -> Vec<f64> { let dt = years / steps as f64; let mut rng = Lcg(42); let mut terminal = Vec::with_capacity(paths); for _ in 0..paths { let mut value = spot; for _ in 0..steps { value = model.step(value, dt, rng.normal()); } terminal.push(value); } terminal} fn main() { let model = Gbm { drift: 0.05, volatility: 0.2 }; let terminal = simulate_terminal(&model, 100.0, 1.0, 12, 20_000); let mean = terminal.iter().sum::<f64>() / terminal.len() as f64; println!("{} : moyenne à 1 an = {mean:.2} (théorie : {:.2})", model.name(), 100.0 * 0.05_f64.exp());}Thanks to the trait, adding a model touches neither the simulation nor the exposure computation. In the riskforge repository, the simulation returns the whole grid (a list of scenarios per date), which we plug into the exposure_profile written in step 3: at last we get a simulated expected exposure profile.
Your turn
Add a MeanReverting { speed, mean, volatility } model (Ornstein-Uhlenbeck) implementing DiffusionModel with the simple discretization: x + speed x (mean - x) x dt + volatility x sqrt(dt) x z.
trait DiffusionModel { fn step(&self, current: f64, dt: f64, z: f64) -> f64;} // ajoute MeanReverting et son impl ici fn main() { let model = MeanReverting { speed: 2.0, mean: 100.0, volatility: 0.0 }; let mut x = 130.0; for _ in 0..12 { x = model.step(x, 1.0 / 12.0, 0.0); } println!("{x:.2}"); // se rapproche de 100 : environ 103.36}A struct with three f64 fields and an impl DiffusionModel for MeanReverting with the formula from the prompt.
trait DiffusionModel { fn step(&self, current: f64, dt: f64, z: f64) -> f64;} struct MeanReverting { speed: f64, mean: f64, volatility: f64,} impl DiffusionModel for MeanReverting { fn step(&self, current: f64, dt: f64, z: f64) -> f64 { current + self.speed * (self.mean - current) * dt + self.volatility * dt.sqrt() * z }} fn main() { let model = MeanReverting { speed: 2.0, mean: 100.0, volatility: 0.0 }; let mut x = 130.0; for _ in 0..12 { x = model.step(x, 1.0 / 12.0, 0.0); } println!("{x:.2}"); // se rapproche de 100 : environ 103.36}With zero volatility you see mean reversion in its pure form: the gap of 30 shrinks by about 1/6 each month. The riskforge repository uses the exact discretization, more accurate when the time step is large.