spawn_stochastic/
feller.rs

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