aprender-core 0.31.2

Next-generation machine learning library in pure Rust
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
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
//! Value at Risk (`VaR`) calculations
//!
//! `VaR` at confidence level α is the threshold value such that the probability
//! of loss exceeding `VaR` is (1-α).
//!
//! Reference: Jorion (2006), "Value at Risk"

use crate::monte_carlo::engine::{percentile, SimulationPath};
use crate::monte_carlo::error::{MonteCarloError, Result};

/// Value at Risk calculator
#[derive(Debug, Clone, Copy)]
pub struct VaR;

impl VaR {
    /// Calculate historical `VaR` from returns
    ///
    /// VaR(α) = -Quantile(Returns, 1-α)
    ///
    /// Returns `VaR` as a positive value (loss)
    ///
    /// # Arguments
    /// * `returns` - Vector of returns (can be positive or negative)
    /// * `confidence` - Confidence level (e.g., 0.95 for 95% `VaR`)
    ///
    /// # Example
    /// ```
    /// use aprender::monte_carlo::risk::VaR;
    ///
    /// let returns = vec![-0.05, -0.02, 0.01, 0.03, 0.05, 0.02, -0.01, 0.04, -0.03, 0.00];
    /// let var_95 = VaR::historical(&returns, 0.95);
    /// assert!(var_95 >= 0.0); // VaR is positive (represents loss)
    /// ```
    #[must_use]
    pub fn historical(returns: &[f64], confidence: f64) -> f64 {
        if returns.is_empty() {
            return 0.0;
        }

        // VaR is the negative of the (1-confidence) quantile
        let quantile_level = 1.0 - confidence;
        let loss_quantile = percentile(returns, quantile_level);

        // Return as positive loss
        -loss_quantile.min(0.0)
    }

    /// Calculate parametric `VaR` assuming normal distribution
    ///
    /// `VaR` = -μ - σ × `z_α` where `z_α` = Φ⁻¹(1-α) < 0
    ///
    /// # Arguments
    /// * `mean` - Mean of returns
    /// * `std` - Standard deviation of returns
    /// * `confidence` - Confidence level
    #[must_use]
    pub fn parametric(mean: f64, std: f64, confidence: f64) -> f64 {
        let z = quantile_normal(1.0 - confidence);
        // z is negative for left tail (e.g., -1.645 for 95% confidence)
        // VaR = -(mean + std * z) to get positive loss
        -(mean + std * z).min(0.0)
    }

    /// Calculate Cornish-Fisher `VaR` (accounts for skewness and kurtosis)
    ///
    /// Adjusts the normal quantile for non-normality
    #[must_use]
    pub fn cornish_fisher(
        mean: f64,
        std: f64,
        skewness: f64,
        excess_kurtosis: f64,
        confidence: f64,
    ) -> f64 {
        let z = quantile_normal(1.0 - confidence);

        // Cornish-Fisher adjustment
        let z_cf =
            z + (z.powi(2) - 1.0) * skewness / 6.0 + (z.powi(3) - 3.0 * z) * excess_kurtosis / 24.0
                - (2.0 * z.powi(3) - 5.0 * z) * skewness.powi(2) / 36.0;

        // z_cf is negative for left tail, so we negate to get positive loss
        -(mean + std * z_cf).min(0.0)
    }

    /// Calculate `VaR` from simulation paths
    #[must_use]
    pub fn from_paths(paths: &[SimulationPath], confidence: f64) -> f64 {
        let returns: Vec<f64> = paths
            .iter()
            .filter_map(SimulationPath::total_return)
            .collect();
        Self::historical(&returns, confidence)
    }

    /// Validate confidence level
    pub fn validate_confidence(confidence: f64) -> Result<()> {
        if confidence <= 0.0 || confidence >= 1.0 {
            return Err(MonteCarloError::InvalidConfidenceLevel { value: confidence });
        }
        Ok(())
    }
}

/// Inverse normal CDF (quantile function)
///
/// Uses the Acklam approximation which provides accuracy to ~1.15e-9
#[allow(clippy::excessive_precision)]
fn quantile_normal(p: f64) -> f64 {
    // Clamp to avoid infinities
    let p = p.clamp(1e-15, 1.0 - 1e-15);

    // Acklam's approximation constants
    const A: [f64; 6] = [
        -3.969_683_028_665_376e1,
        2.209_460_984_245_205e2,
        -2.759_285_104_469_687e2,
        1.383_577_518_672_690e2,
        -3.066_479_806_614_716e1,
        2.506_628_277_459_239,
    ];

    const B: [f64; 5] = [
        -5.447_609_879_822_406e1,
        1.615_858_368_580_409e2,
        -1.556_989_798_598_866e2,
        6.680_131_188_771_972e1,
        -1.328_068_155_288_572e1,
    ];

    const C: [f64; 6] = [
        -7.784_894_002_430_293e-3,
        -3.223_964_580_411_365e-1,
        -2.400_758_277_161_838,
        -2.549_732_539_343_734,
        4.374_664_141_464_968,
        2.938_163_982_698_783,
    ];

    const D: [f64; 4] = [
        7.784_695_709_041_462e-3,
        3.224_671_290_700_398e-1,
        2.445_134_137_142_996,
        3.754_408_661_907_416,
    ];

    const P_LOW: f64 = 0.02425;
    const P_HIGH: f64 = 1.0 - P_LOW;

    if p < P_LOW {
        // Lower tail
        let q = (-2.0 * p.ln()).sqrt();
        (((((C[0] * q + C[1]) * q + C[2]) * q + C[3]) * q + C[4]) * q + C[5])
            / ((((D[0] * q + D[1]) * q + D[2]) * q + D[3]) * q + 1.0)
    } else if p <= P_HIGH {
        // Central region
        let q = p - 0.5;
        let r = q * q;
        (((((A[0] * r + A[1]) * r + A[2]) * r + A[3]) * r + A[4]) * r + A[5]) * q
            / (((((B[0] * r + B[1]) * r + B[2]) * r + B[3]) * r + B[4]) * r + 1.0)
    } else {
        // Upper tail
        let q = (-2.0 * (1.0 - p).ln()).sqrt();
        -(((((C[0] * q + C[1]) * q + C[2]) * q + C[3]) * q + C[4]) * q + C[5])
            / ((((D[0] * q + D[1]) * q + D[2]) * q + D[3]) * q + 1.0)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_historical_var_basic() {
        // Simple test case: uniform losses from -10% to +10%
        let returns: Vec<f64> = (-100..=100).map(|i| i as f64 / 1000.0).collect();

        let var_95 = VaR::historical(&returns, 0.95);

        // 5th percentile of [-0.1, 0.1] should be around -0.09
        // VaR should be around 0.09 (positive loss)
        assert!(var_95 > 0.08 && var_95 < 0.10, "VaR(95%) = {var_95}");
    }

    #[test]
    fn test_historical_var_all_positive() {
        // All positive returns
        let returns = vec![0.01, 0.02, 0.03, 0.04, 0.05];

        let var_95 = VaR::historical(&returns, 0.95);

        // No losses, VaR should be 0 or very small
        assert!(var_95 >= 0.0);
    }

    #[test]
    fn test_historical_var_all_negative() {
        // All negative returns (losses)
        let returns = vec![-0.01, -0.02, -0.03, -0.04, -0.05];

        let var_95 = VaR::historical(&returns, 0.95);

        // VaR should be positive (representing loss)
        assert!(var_95 > 0.0);
    }

    #[test]
    fn test_historical_var_monotonic() {
        let returns: Vec<f64> = (-100..=100).map(|i| i as f64 / 1000.0).collect();

        let var_90 = VaR::historical(&returns, 0.90);
        let var_95 = VaR::historical(&returns, 0.95);
        let var_99 = VaR::historical(&returns, 0.99);

        // Higher confidence should give higher VaR
        assert!(
            var_90 <= var_95,
            "VaR(90%)={var_90} should be <= VaR(95%)={var_95}"
        );
        assert!(
            var_95 <= var_99,
            "VaR(95%)={var_95} should be <= VaR(99%)={var_99}"
        );
    }

    #[test]
    fn test_parametric_var() {
        // Normal distribution: mean=0, std=0.1
        let var_95 = VaR::parametric(0.0, 0.1, 0.95);

        // z(0.05) ≈ -1.645, so VaR ≈ 0.1 * 1.645 ≈ 0.165
        assert!((var_95 - 0.165).abs() < 0.01, "Parametric VaR = {var_95}");
    }

    #[test]
    fn test_cornish_fisher_var() {
        // With zero skewness and kurtosis, should match parametric
        let var_param = VaR::parametric(0.0, 0.1, 0.95);
        let var_cf = VaR::cornish_fisher(0.0, 0.1, 0.0, 0.0, 0.95);

        assert!(
            (var_param - var_cf).abs() < 0.01,
            "CF VaR should match parametric for normal: {} vs {}",
            var_cf,
            var_param
        );
    }

    #[test]
    fn test_cornish_fisher_positive_skew() {
        // Positive skewness (heavy right tail, lighter left tail)
        // Should reduce VaR compared to parametric
        let var_param = VaR::parametric(0.0, 0.1, 0.95);
        let var_cf = VaR::cornish_fisher(0.0, 0.1, 0.5, 0.0, 0.95);

        // Positive skew means less severe left tail
        assert!(
            var_cf < var_param + 0.05,
            "Positive skew should affect VaR: CF={var_cf} vs Param={var_param}"
        );
    }

    #[test]
    fn test_cornish_fisher_excess_kurtosis() {
        // Positive excess kurtosis (fat tails)
        // The Cornish-Fisher adjustment modifies the quantile based on kurtosis
        let var_param = VaR::parametric(0.0, 0.1, 0.95);
        let var_cf = VaR::cornish_fisher(0.0, 0.1, 0.0, 3.0, 0.95);

        // With non-zero excess kurtosis, CF should differ from parametric
        // Note: The Cornish-Fisher expansion can give counterintuitive results
        // at moderate confidence levels; this tests the formula works
        assert!(
            (var_cf - var_param).abs() > 0.001,
            "Excess kurtosis should affect VaR: CF={var_cf} vs Param={var_param}"
        );
        assert!(var_cf > 0.0, "VaR should be positive: {var_cf}");
        assert!(var_cf.is_finite(), "VaR should be finite");
    }

    #[test]
    fn test_validate_confidence() {
        assert!(VaR::validate_confidence(0.95).is_ok());
        assert!(VaR::validate_confidence(0.99).is_ok());
        assert!(VaR::validate_confidence(0.5).is_ok());

        assert!(VaR::validate_confidence(0.0).is_err());
        assert!(VaR::validate_confidence(1.0).is_err());
        assert!(VaR::validate_confidence(-0.1).is_err());
        assert!(VaR::validate_confidence(1.5).is_err());
    }

    #[test]
    fn test_quantile_normal() {
        // Test known values
        assert!((quantile_normal(0.5) - 0.0).abs() < 1e-6);
        assert!((quantile_normal(0.84134) - 1.0).abs() < 1e-3);
        assert!((quantile_normal(0.15866) - (-1.0)).abs() < 1e-3);
        assert!((quantile_normal(0.97725) - 2.0).abs() < 1e-3);
        assert!((quantile_normal(0.02275) - (-2.0)).abs() < 1e-3);
    }

    #[test]
    fn test_empty_returns() {
        let var = VaR::historical(&[], 0.95);
        assert!(var.abs() < 1e-10);
    }

    #[test]
    fn test_from_paths() {
        use crate::monte_carlo::engine::PathMetadata;
        // Paths that go from 100 down to various final values
        let paths: Vec<SimulationPath> = vec![
            SimulationPath::new(
                vec![0.0, 1.0],
                vec![100.0, 90.0], // -10% return
                PathMetadata {
                    path_id: 0,
                    seed: 1,
                    is_antithetic: false,
                },
            ),
            SimulationPath::new(
                vec![0.0, 1.0],
                vec![100.0, 95.0], // -5% return
                PathMetadata {
                    path_id: 1,
                    seed: 2,
                    is_antithetic: false,
                },
            ),
            SimulationPath::new(
                vec![0.0, 1.0],
                vec![100.0, 105.0], // +5% return
                PathMetadata {
                    path_id: 2,
                    seed: 3,
                    is_antithetic: false,
                },
            ),
            SimulationPath::new(
                vec![0.0, 1.0],
                vec![100.0, 110.0], // +10% return
                PathMetadata {
                    path_id: 3,
                    seed: 4,
                    is_antithetic: false,
                },
            ),
            SimulationPath::new(
                vec![0.0, 1.0],
                vec![100.0, 102.0], // +2% return
                PathMetadata {
                    path_id: 4,
                    seed: 5,
                    is_antithetic: false,
                },
            ),
        ];
        let var = VaR::from_paths(&paths, 0.95);
        assert!(var >= 0.0, "VaR from paths should be non-negative: {var}");
        assert!(var.is_finite());
    }

    #[test]
    fn test_from_paths_empty() {
        let paths: Vec<SimulationPath> = Vec::new();
        let var = VaR::from_paths(&paths, 0.95);
        assert!(var.abs() < 1e-10, "VaR from empty paths should be 0");
    }

    #[test]
    fn test_from_paths_single_point_paths() {
        use crate::monte_carlo::engine::PathMetadata;
        // Paths with only one value cannot compute total_return (no initial/final pair that differs)
        let paths: Vec<SimulationPath> = vec![SimulationPath::new(
            vec![0.0],
            vec![100.0],
            PathMetadata {
                path_id: 0,
                seed: 1,
                is_antithetic: false,
            },
        )];
        let var = VaR::from_paths(&paths, 0.95);
        // total_return returns None for single-element path, so returns vec is empty
        assert!(var.abs() < 1e-10);
    }

    #[test]
    fn test_quantile_normal_upper_tail() {
        // Test upper tail (p > P_HIGH = 0.97575)
        // P(Z < 3.0) ~ 0.99865
        let z_high = quantile_normal(0.99865);
        assert!(
            (z_high - 3.0).abs() < 0.01,
            "Upper tail z for p=0.99865: {z_high}"
        );

        // P(Z < 2.5) ~ 0.99379
        let z_upper = quantile_normal(0.99379);
        assert!(
            (z_upper - 2.5).abs() < 0.02,
            "Upper tail z for p=0.99379: {z_upper}"
        );
    }

    #[test]
    fn test_quantile_normal_extreme_tails() {
        // Very extreme lower tail (triggers clamping)
        let z_low = quantile_normal(1e-20);
        assert!(
            z_low < -5.0,
            "Extreme lower tail should give very negative z: {z_low}"
        );
        assert!(z_low.is_finite());

        // Very extreme upper tail (triggers clamping)
        let z_high = quantile_normal(1.0 - 1e-20);
        assert!(
            z_high > 5.0,
            "Extreme upper tail should give very positive z: {z_high}"
        );
        assert!(z_high.is_finite());
    }

    #[test]
    fn test_parametric_var_positive_mean() {
        // Large positive mean with small std: VaR should be 0 (no loss expected)
        let var = VaR::parametric(0.5, 0.01, 0.95);
        // mean + std * z = 0.5 + 0.01 * (-1.645) = 0.4836 > 0
        // -(0.4836).min(0.0) = -0.0 = 0.0
        assert!(
            var.abs() < 1e-6,
            "VaR should be ~0 when mean is large positive: {var}"
        );
    }

    #[test]
    fn test_cornish_fisher_negative_skew() {
        // Negative skewness (heavier left tail) should increase VaR
        let var_param = VaR::parametric(0.0, 0.1, 0.95);
        let var_cf = VaR::cornish_fisher(0.0, 0.1, -0.5, 0.0, 0.95);

        assert!(
            var_cf > 0.0,
            "VaR should be positive with negative skew: {var_cf}"
        );
        assert!(var_cf.is_finite());
        // Negative skew means heavier left tail, so VaR should be higher
        assert!(
            var_cf > var_param - 0.05,
            "Negative skew CF VaR={var_cf} vs Param={var_param}"
        );
    }

    // Property-based tests
    #[cfg(test)]
    mod proptests {
        use super::*;
        use proptest::prelude::*;

        proptest! {
            #[test]
            fn prop_var_non_negative(
                returns in prop::collection::vec(-1.0..1.0f64, 10..100),
                confidence in 0.5..0.999f64,
            ) {
                let var = VaR::historical(&returns, confidence);
                prop_assert!(var >= 0.0, "VaR should be non-negative: {var}");
            }

            #[test]
            fn prop_var_monotonic_in_confidence(
                returns in prop::collection::vec(-1.0..1.0f64, 100..500),
            ) {
                let var_90 = VaR::historical(&returns, 0.90);
                let var_95 = VaR::historical(&returns, 0.95);
                let var_99 = VaR::historical(&returns, 0.99);

                prop_assert!(var_90 <= var_95 + 0.001);
                prop_assert!(var_95 <= var_99 + 0.001);
            }

            #[test]
            fn prop_parametric_var_non_negative(
                mean in -0.5..0.5f64,
                std in 0.01..0.5f64,
                confidence in 0.5..0.999f64,
            ) {
                let var = VaR::parametric(mean, std, confidence);
                prop_assert!(var >= 0.0);
            }
        }
    }
}