spawn_stochastic/
abm.rs

1use rand::rngs::OsRng;
2use rand::Rng;
3
4/// Arithmetic Brownian Motion (ABM) simulates the asset price over time using the formula:
5/// dS = μ * dt + σ * dW
6pub struct ArithmeticBrownianMotion {
7    pub mu: f64,
8    pub sigma: f64,
9    pub n_paths: usize,
10    pub n_steps: usize,
11    pub t_end: f64,
12    pub s_0: f64,
13}
14
15impl ArithmeticBrownianMotion {
16    /// Creates a new ABM instance.
17    pub fn new(mu: f64, sigma: f64, n_paths: usize, n_steps: usize, t_end: f64, s_0: f64) -> Self {
18        Self { mu, sigma, n_paths, n_steps, t_end, s_0 }
19    }
20
21    /// Simulates the ABM paths using the Euler-Maruyama method with secure random number generation.
22    pub fn simulate(&self) -> Vec<Vec<f64>> {
23        let dt = self.t_end / self.n_steps as f64;
24        let mut rng = OsRng; // Güvenli rastgele sayı üretici
25        let mut paths = vec![vec![self.s_0; self.n_steps + 1]; self.n_paths];
26
27        for i in 0..self.n_paths {
28            for j in 1..=self.n_steps {
29                let d_w = rng.gen::<f64>() * dt.sqrt();
30                if let Some(prev) = paths[i].get(j - 1) {
31                    paths[i][j] = prev + self.mu * dt + self.sigma * d_w;
32                }
33            }
34        }
35
36        paths
37    }
38}