digifi 3.0.10

General purpose financial library and framework for financial modelling, portfolio optimisation, and asset pricing.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
use ndarray::Array1;
#[cfg(feature = "serde")]
use serde::{Serialize, Deserialize};
use crate::error::{DigiFiError, ErrorTitle};
use crate::random_generators::RandomGenerator;
use crate::stochastic_processes::StochasticProcess;
use crate::random_generators::{standard_normal_generators::StandardNormalBoxMuller, generator_algorithms::inverse_transform};
use crate::statistics::continuous_distributions::GammaDistribution;


#[derive(Debug)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
/// Model used to reproduce the volatility smile effect.
/// 
/// # LaTeX Formula
/// - dS_{t} = \\mu*S_{t}*dt + \\sigma*S^{beta+1}_{t}*dW_{t}
///
/// # Links
/// - Wikipedia: <https://en.wikipedia.org/wiki/Constant_elasticity_of_variance_model>
/// - Original Source: <https://doi.org/10.3905/jpm.1996.015>
///
/// # Example
///
/// ```rust
/// use ndarray::Array1;
/// use digifi::utilities::TEST_ACCURACY;
/// use digifi::stochastic_processes::{StochasticProcessResult, StochasticProcess, ConstantElasticityOfVariance};
///
/// let n_paths: usize = 1_000;
/// let n_steps: usize = 200;
///
/// let cev: ConstantElasticityOfVariance = ConstantElasticityOfVariance::build(1.0, 0.4, 0.5, n_paths, n_steps, 1.0, 100.0).unwrap();
/// let sp_result: StochasticProcessResult = cev.simulate().unwrap();
/// 
/// assert_eq!(sp_result.paths.len(), n_paths);
/// assert_eq!(sp_result.paths[0].len(), n_steps + 1);
/// assert_eq!(sp_result.expectations_path.clone().unwrap().len(), n_steps + 1);
/// assert!((sp_result.mean - sp_result.expectations_path.unwrap()[n_steps]).abs() < 200_000_000.0 * TEST_ACCURACY);
/// ```
pub struct ConstantElasticityOfVariance {
    /// Mean of the process
    mu: f64,
    /// Standard deviation of the process
    sigma: f64,
    /// Parameter controlling the relationship between volatility and price
    gamma: f64,
    /// Number of paths to generate
    n_paths: usize,
    /// Number of steps
    n_steps: usize,
    /// Final time step
    t_f: f64,
    /// Initial value of the stochastic process
    s_0: f64,
    /// Time difference between two consequtive time steps
    dt: f64,
    /// Array of time steps
    t: Array1<f64>,
}

impl ConstantElasticityOfVariance {
    /// Creates a new `ConstantElasticityOfVariance` instance.
    /// 
    /// # Input
    /// - `mu`: Mean of the process
    /// - `sigma`: Standard deviation of the process
    /// - `gamma`: Parameter controlling the relationship between volatility and price
    /// - `n_paths`: Number of paths to generate
    /// - `n_steps`: Number of steps
    /// - `t_f`: Final time step
    /// - `s_0`: Initial value of the stochastic process
    pub fn build(mu: f64, sigma: f64, gamma: f64, n_paths: usize, n_steps: usize, t_f: f64, s_0: f64) -> Result<Self, DigiFiError> {
        if gamma < 0.0 {
            return Err(DigiFiError::ParameterConstraint {
                title: Self::error_title(),
                constraint: "Tha value of argument `gamma` cannot be smaller than `0`.".to_owned(),
            });
        }
        let dt: f64 = t_f / (n_steps as f64);
        let t: Array1<f64> = Array1::range(0.0, t_f + dt, dt);
        Ok(Self { mu, sigma, gamma, n_paths, n_steps, t_f, s_0, dt, t })
    }
}

impl ErrorTitle for ConstantElasticityOfVariance {
    fn error_title() -> String {
        String::from("Constant Elasticity of Variance")
    }
}

impl StochasticProcess for ConstantElasticityOfVariance {
    fn update_n_paths(&mut self, n_paths: usize) -> () {
        self.n_paths = n_paths;
    }

    fn get_n_steps(&self) -> usize {
        self.n_steps
    }

    fn get_t_f(&self) -> f64 {
        self.t_f
    }

    /// Calculates the expected path of the CEV process.
    ///
    /// # Output
    /// - An array of expected values of the stock price at each time step
    ///
    /// # LaTeX Formula
    /// - E[S_{t}] = S_{0} e^{\\mu t}
    fn get_expectations(&self) -> Option<Array1<f64>> {
        Some(self.t.map(|t| { self.s_0 * (self.mu * t).exp() } ))
    }

    fn get_variances(&self) -> Option<Array1<f64>> {
        None
    }

    /// Generates simulation paths for the Constant Elasticity of Variance (CEV) process.
    ///
    /// # Output
    /// - An array of simulated paths following the CEV process
    ///
    /// # LaTeX Formula
    /// - dS_{t} = \\mu*S_{t}*dt + \\sigma*S^{beta+1}_{t}*dW_{t}
    fn get_paths(&self) -> Result<Vec<Array1<f64>>, DigiFiError> {
        let mut paths: Vec<Array1<f64>> = Vec::with_capacity(self.n_paths);
        let len: usize = self.t.len();
        let drift_coef: f64 = self.mu * self.dt;
        let diffusion_coef: f64 = self.sigma * self.dt.sqrt();
        for _ in 0..self.n_paths {
            let n: Array1<f64> = StandardNormalBoxMuller::new_shuffle(len)?.generate()?;
            let mut s: Array1<f64> = Array1::from_vec(vec![self.s_0; len]);
            for i in 1..len {
                s[i] = s[i-1] + drift_coef * s[i-1] + diffusion_coef * s[i-1].powf(self.gamma) * n[i];
            }
            paths.push(s);
        }
        Ok(paths)
    }
}


#[derive(Debug)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
/// Model describes the evolution of stock price and its volatility.
/// 
/// # LaTeX Formula
/// - dS_{t} = \\mu*S_{t}*dt + \\sqrt{v_{t}}*S_{t}*dW^{S}_{t}
/// - dv_{t} = k*(\\theta-v)*dt + \\epsilon*\\sqrt{v}dW^{v}_{t}
/// - Corr(W^{S}_{t}, W^{v}_{t}) = \\rho
///
/// # Links
/// - Wikipedia: <https://en.wikipedia.org/wiki/Heston_model>
/// - Original Source: <https://doi.org/10.1093%2Frfs%2F6.2.327>
///
/// # Example
///
/// ```rust
/// use ndarray::Array1;
/// use digifi::utilities::TEST_ACCURACY;
/// use digifi::stochastic_processes::{StochasticProcessResult, StochasticProcess, HestonStochasticVolatility};
///
/// let n_paths: usize = 1_000;
/// let n_steps: usize = 200;
///
/// let hsv: HestonStochasticVolatility = HestonStochasticVolatility::new(0.1, 5.0, 0.07, 0.2, 0.0, n_paths, n_steps, 1.0, 100.0, 0.03);
/// let sp_result: StochasticProcessResult = hsv.simulate().unwrap();
/// 
/// assert_eq!(sp_result.paths.len(), n_paths);
/// assert_eq!(sp_result.paths[0].len(), n_steps + 1);
/// assert_eq!(sp_result.expectations_path.clone().unwrap().len(), n_steps + 1);
/// assert!((sp_result.mean - sp_result.expectations_path.unwrap()[n_steps]).abs() < 1_000_000.0 * TEST_ACCURACY);
/// ```
pub struct HestonStochasticVolatility {
    /// Mean of the process
    mu: f64,
    /// Scaling of volatility drift
    k: f64,
    /// Volatility trend
    theta: f64,
    /// Standard deviation of volatility
    epsilon: f64,
    /// Correlation between stock price and volatility
    rho: f64,
    /// Number of paths to generate
    n_paths: usize,
    /// Number of steps
    n_steps: usize,
    /// Final time step
    t_f: f64,
    /// Initial value of the stochastic process
    s_0: f64,
    /// Initial value of the volatility process
    v_0: f64,
    /// Time difference between two consequtive time steps
    dt: f64,
    /// Array of time steps
    t: Array1<f64>,
}

impl HestonStochasticVolatility {
    /// Creates a new `HestonStochasticVolatility` instance.
    /// 
    /// # Input
    /// - `mu`: Mean of the process
    /// - `k`: Scaling of volatility drift
    /// - `theta`: Volatility trend
    /// - `epsilon`: Standard deviation of volatility
    /// - `rho`: Correlation between stock price and volatility
    /// - `n_paths`: Number of paths to generate
    /// - `n_steps`: Number of steps
    /// - `t_f`: Final time step
    /// - `s_0`: Initial value of the stochastic process
    /// - `v_0`: Initial value of the volatility process
    pub fn new(mu: f64, k: f64, theta: f64, epsilon: f64, rho: f64, n_paths: usize, n_steps: usize, t_f: f64, s_0: f64, v_0: f64) -> Self {
        let dt: f64 = t_f / (n_steps as f64);
        let t: Array1<f64> = Array1::range(0.0, t_f + dt, dt);
        Self { mu, k, theta, epsilon, rho, n_paths, n_steps, t_f, s_0, v_0, dt, t }
    }
}

impl StochasticProcess for HestonStochasticVolatility {
    fn update_n_paths(&mut self, n_paths: usize) -> () {
        self.n_paths = n_paths;
    }

    fn get_n_steps(&self) -> usize {
        self.n_steps
    }

    fn get_t_f(&self) -> f64 {
        self.t_f
    }

    /// Calculates the expected path of the Heston Stochastic Volatility process.
    ///
    /// # Output
    /// - An array of expected values of the stock price at each time step
    ///
    /// # LaTeX Formula
    /// - E[S_{t}] = S_{0} + (\\mu - \\frac{1}{2}\\theta) t + \\frac{\\theta - v_{0}}{2k} (1 - e^{-kt})
    fn get_expectations(&self) -> Option<Array1<f64>> {
        let drift_coef: f64 = self.mu - 0.5 * self.theta;
        let c: f64 = self.theta - self.v_0;
        let two_k: f64 = 2.0 * self.k;
        Some(self.t.map(|t| { self.s_0 + drift_coef * t + c * (1.0 - (-self.k * t).exp()) / two_k } ))
    }

    fn get_variances(&self) -> Option<Array1<f64>> {
        None
    }

    /// Generates simulation paths for the Heston Stochastic Volatility process.
    ///
    /// # Output
    /// - A tuple of arrays representing the simulated paths of stock prices and volatilities
    ///
    /// # LaTeX Formula
    /// - dS_{t} = \\mu*S_{t}*dt + \\sqrt{v_{t}}*S_{t}*dW^{S}_{t}
    /// - dv_{t} = k*(\\theta-v)*dt + \\epsilon*\\sqrt{v}dW^{v}_{t}
    /// - Corr(W^{S}_{t}, W^{v}_{t}) = \\rho
    fn get_paths(&self) -> Result<Vec<Array1<f64>>, DigiFiError> {
        let mut paths: Vec<Array1<f64>> = Vec::with_capacity(self.n_paths);
        let len: usize = self.t.len();
        let v_drift_coef: f64 = (-self.k * self.dt).exp();
        let a: f64 = self.epsilon.powi(2) / self.k * (v_drift_coef - (-2.0 * self.k * self.dt).exp());
        let b: f64 = self.theta * self.epsilon.powi(2) / (2.0 * self.k) * (1.0 - v_drift_coef).powi(2);
        let ns_c: f64 = (1.0 - self.rho.powi(2)).sqrt();
        for _ in 0..self.n_paths {
            let nv: Array1<f64> = StandardNormalBoxMuller::new_shuffle(len)?.generate()?;
            let n: Array1<f64> = StandardNormalBoxMuller::new_shuffle(len)?.generate()?;
            let mut v: Array1<f64> = Array1::from_vec(vec![self.v_0; len]);
            let mut s: Array1<f64> = Array1::from_vec(vec![self.s_0; len]);
            for i in 1..len {
                let v_: f64 = self.theta + (v[i-1] - self.theta) * v_drift_coef + (a * v[i-1] + b).sqrt() * nv[i-1];
                v[i] = v_.max(0.0);
                let ns: f64 = self.rho * nv[i-1] + ns_c * n[i-1];
                let s_: f64 = s[i-1] + (self.mu - 0.5 * v[i-1])* self.dt + self.epsilon * (v[i-1] * self.dt).sqrt() * ns;
                s[i] = s_.max(0.0)
            }
            paths.push(s);
        }
        Ok(paths)
    }
}


#[derive(Debug)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
/// Model used in option pricing.
/// 
/// # LaTeX Formula
/// - dS_{t} = \\mu*dG(t) + \\sigma*\\sqrt{dG(t)}\\mathcal{N}(0,1)
///
/// # Links
/// - Wikipedia: <https://en.wikipedia.org/wiki/Variance_gamma_process>
/// - Original Source: <https://doi.org/10.1086%2F296519>
///
/// # Example
///
/// ```rust
/// use ndarray::Array1;
/// use digifi::utilities::TEST_ACCURACY;
/// use digifi::stochastic_processes::{StochasticProcessResult, StochasticProcess, VarianceGammaProcess};
///
/// let n_paths: usize = 2;
/// let n_steps: usize = 200;
///
/// let vg: VarianceGammaProcess = VarianceGammaProcess::new(0.2, 0.3, 20.0, n_paths, n_steps, 1.0, 0.03);
/// let sp_result: StochasticProcessResult = vg.simulate().unwrap();
/// 
/// assert_eq!(sp_result.paths.len(), n_paths);
/// assert_eq!(sp_result.paths[0].len(), n_steps + 1);
/// assert_eq!(sp_result.expectations_path.unwrap().len(), n_steps + 1);
/// assert_eq!(sp_result.variances_path.unwrap().len(), n_steps + 1);
/// ```
pub struct VarianceGammaProcess {
    /// Mean of the process
    mu: f64,
    /// Standard deviation of the process
    sigma: f64,
    /// Rate parameter of the Gamma distribution
    kappa: f64,
    /// Number of paths to generate
    n_paths: usize,
    /// Number of steps
    n_steps: usize,
    /// Final time step
    t_f: f64,
    /// Initial value of the stochastic process
    s_0: f64,
    /// Time difference between two consequtive time steps
    dt: f64,
    /// Array of time steps
    t: Array1<f64>,
}

impl VarianceGammaProcess {
    /// Creates a new `VarianceGammaProcess` instance.
    /// 
    /// # Input
    /// - `mu`: Mean of the process
    /// - `sigma`: Standard deviation of the process
    /// - `kappa`: Rate parameter of the Gamma distribution
    /// - `n_paths`: Number of paths to generate
    /// - `n_steps`: Number of steps
    /// - `t_f`: Final time step
    pub fn new(mu: f64, sigma: f64, kappa: f64, n_paths: usize, n_steps: usize, t_f: f64, s_0: f64) -> Self {
        let dt: f64 = t_f / (n_steps as f64);
        let t: Array1<f64> = Array1::range(0.0, t_f + dt, dt);
        Self { mu, sigma, kappa, n_paths, n_steps, t_f, s_0, dt, t }
    }
}

impl StochasticProcess for VarianceGammaProcess {
    fn update_n_paths(&mut self, n_paths: usize) -> () {
        self.n_paths = n_paths;
    }

    fn get_n_steps(&self) -> usize {
        self.n_steps
    }

    fn get_t_f(&self) -> f64 {
        self.t_f
    }

    /// Calculates the expected path of the Variance Gamma process.
    ///
    /// # Output
    /// - An array of expected values of the stock price at each time step
    ///
    /// # LaTeX Formula
    /// - E[S_{t}] = S_{0} + \\mu t
    fn get_expectations(&self) -> Option<Array1<f64>> {
        Some(self.s_0 + self.mu * &self.t)
    }

    /// Calculates the variance of the Variance Gamma process.
    ///
    /// # Output
    /// - An array of variances of the stock price at each time step
    ///
    /// # LaTeX Formula
    /// - Var[S_{t}] = (\\sigma^{2} + \\frac{\\mu^{2}}{\\textit{rate}}) t
    fn get_variances(&self) -> Option<Array1<f64>> {
        Some((self.sigma.powi(2) + self.mu.powi(2) / self.kappa) * &self.t)
    }

    /// Generates simulation paths for the Variance Gamma process.
    ///
    /// # Output
    /// - An array of simulated paths following the Variance Gamma process
    ///
    /// # LaTeX Formula
    /// - dS_{t} = \\mu*dG(t) + \\sigma*\\sqrt{dG(t)}\\mathcal{N}(0,1)
    fn get_paths(&self) -> Result<Vec<Array1<f64>>, DigiFiError> {
        let mut paths: Vec<Array1<f64>> = Vec::with_capacity(self.n_paths);
        let len: usize = self.t.len();
        for _ in 0..self.n_paths {
            let gamma_dist: GammaDistribution = GammaDistribution::build(self.dt * self.kappa, 1.0 / self.kappa)?;
            let g: Array1<f64> = inverse_transform(&gamma_dist, len)?;
            let n: Array1<f64> = StandardNormalBoxMuller::new_shuffle(len)?.generate()?;
            let mut s: Array1<f64> = Array1::from_vec(vec![self.s_0; len]);
            for i in 1..len {
                let dg: f64 = if g[i-1].is_nan() { 0.0 } else { g[i-1] };
                s[i] = s[i-1] + self.mu * dg + dg.sqrt() * self.sigma * n[i-1];
            }
            paths.push(s);
        }
        Ok(paths)
    }
}


#[cfg(test)]
mod tests {
    use crate::utilities::TEST_ACCURACY;
    use crate::stochastic_processes::{StochasticProcessResult, StochasticProcess};

    #[test]
    fn unit_test_constant_elasticity_of_variance() -> () {
        use crate::stochastic_processes::stochastic_volatility_models::ConstantElasticityOfVariance;
        let n_paths: usize = 1_000;
        let n_steps: usize = 200;
        let cev: ConstantElasticityOfVariance = ConstantElasticityOfVariance::build(
            1.0, 0.4, 0.5, n_paths, n_steps, 1.0, 100.0
        ).unwrap();
        let sp_result: StochasticProcessResult = cev.simulate().unwrap();
        assert_eq!(sp_result.paths.len(), n_paths);
        assert_eq!(sp_result.paths[0].len(), n_steps + 1);
        assert_eq!(sp_result.expectations_path.clone().unwrap().len(), n_steps + 1);
        assert!((sp_result.mean - sp_result.expectations_path.unwrap()[n_steps]).abs() < 200_000_000.0 * TEST_ACCURACY);
    }

    #[test]
    fn unit_test_heston_stochastic_volatility() -> () {
        use crate::stochastic_processes::stochastic_volatility_models::HestonStochasticVolatility;
        let n_paths: usize = 1_000;
        let n_steps: usize = 200;
        let hsv: HestonStochasticVolatility = HestonStochasticVolatility::new(
            0.1, 5.0, 0.07, 0.2, 0.0, n_paths, n_steps, 1.0, 100.0, 0.03
        );
        let sp_result: StochasticProcessResult = hsv.simulate().unwrap();
        assert_eq!(sp_result.paths.len(), n_paths);
        assert_eq!(sp_result.paths[0].len(), n_steps + 1);
        assert_eq!(sp_result.expectations_path.clone().unwrap().len(), n_steps + 1);
        assert!((sp_result.mean - sp_result.expectations_path.unwrap()[n_steps]).abs() < 1_000_000.0 * TEST_ACCURACY);
    }

    #[test]
    fn unit_test_variance_gamma() -> () {
        use crate::stochastic_processes::stochastic_volatility_models::VarianceGammaProcess;
        let n_paths: usize = 2;
        let n_steps: usize = 200;
        let vg: VarianceGammaProcess = VarianceGammaProcess::new(0.2, 0.3, 20.0, n_paths, n_steps, 1.0, 0.03);
        let sp_result: StochasticProcessResult = vg.simulate().unwrap();
        assert_eq!(sp_result.paths.len(), n_paths);
        assert_eq!(sp_result.paths[0].len(), n_steps + 1);
        assert_eq!(sp_result.expectations_path.unwrap().len(), n_steps + 1);
        assert_eq!(sp_result.variances_path.unwrap().len(), n_steps + 1);
    }
}