scirs2-integrate 0.4.2

Numerical integration module for SciRS2 (scirs2-integrate)
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
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
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
//! Volatility forecasting models for financial time series
//!
//! This module provides industry-standard volatility forecasting methods including:
//! - **GARCH(1,1)**: Generalized Autoregressive Conditional Heteroskedasticity
//! - **EWMA**: Exponentially Weighted Moving Average (RiskMetrics)
//! - **Historical volatility**: Simple and realized volatility estimators
//! - **Volatility term structure**: Forward-looking volatility estimates
//!
//! # Features
//! - Maximum likelihood estimation for GARCH parameters
//! - Adaptive EWMA with optimal decay selection
//! - Volatility forecasting with confidence intervals
//! - Rolling window estimation
//! - Model diagnostics and residual analysis
//!
//! # Example
//! ```
//! use scirs2_integrate::specialized::finance::ml::volatility_forecast::{
//!     GarchModel, EWMAModel, VolatilityForecaster,
//! };
//!
//! // Historical returns (need at least 10 for GARCH)
//! let returns = vec![
//!     0.01, -0.02, 0.015, -0.01, 0.005,
//!     0.02, -0.015, 0.01, -0.005, 0.012,
//!     -0.018, 0.025, -0.012, 0.008,
//! ];
//!
//! // GARCH(1,1) model
//! let mut garch = GarchModel::new();
//! garch.fit(&returns).expect("Operation failed");
//! let forecast = garch.forecast(5).expect("Operation failed"); // 5-day ahead forecast
//! println!("GARCH forecast: {:?}", forecast);
//!
//! // EWMA (RiskMetrics lambda = 0.94)
//! let ewma = EWMAModel::new(0.94);
//! let current_vol = ewma.estimate(&returns).expect("Operation failed");
//! println!("Current volatility: {:.4}", current_vol);
//! ```

use crate::error::{IntegrateError, IntegrateResult as Result};
use std::f64::consts::PI;

// ============================================================================
// GARCH(1,1) Model
// ============================================================================

/// GARCH(1,1) model for volatility forecasting
///
/// Model: σ²_t = ω + α*ε²_{t-1} + β*σ²_{t-1}
///
/// where:
/// - ω (omega): Long-run variance constant
/// - α (alpha): ARCH coefficient (impact of past shocks)
/// - β (beta): GARCH coefficient (persistence)
/// - Constraint: α + β < 1 (stationarity)
#[derive(Debug, Clone)]
pub struct GarchModel {
    /// Omega: long-run variance constant
    pub omega: f64,
    /// Alpha: ARCH coefficient
    pub alpha: f64,
    /// Beta: GARCH coefficient
    pub beta: f64,
    /// Fitted conditional variances
    conditional_variances: Vec<f64>,
    /// Is the model fitted?
    fitted: bool,
}

impl GarchModel {
    /// Create a new GARCH(1,1) model with default parameters
    pub fn new() -> Self {
        Self {
            omega: 0.0,
            alpha: 0.0,
            beta: 0.0,
            conditional_variances: Vec::new(),
            fitted: false,
        }
    }

    /// Create with custom initial parameters
    pub fn with_parameters(omega: f64, alpha: f64, beta: f64) -> Result<Self> {
        Self::validate_parameters(omega, alpha, beta)?;
        Ok(Self {
            omega,
            alpha,
            beta,
            conditional_variances: Vec::new(),
            fitted: false,
        })
    }

    /// Fit GARCH model to returns using quasi-maximum likelihood
    pub fn fit(&mut self, returns: &[f64]) -> Result<()> {
        if returns.len() < 10 {
            return Err(IntegrateError::ValueError(
                "At least 10 observations required for GARCH estimation".to_string(),
            ));
        }

        // Initial parameter guess (typical values)
        let initial_params = vec![
            0.00001, // omega (small positive)
            0.05,    // alpha (5% reaction to shocks)
            0.90,    // beta (90% persistence)
        ];

        // Optimize via simple search
        let optimized = self.quasi_mle_optimization(returns, initial_params)?;

        self.omega = optimized[0];
        self.alpha = optimized[1];
        self.beta = optimized[2];

        // Calculate fitted conditional variances
        self.conditional_variances = self.compute_conditional_variances(returns)?;
        self.fitted = true;

        Ok(())
    }

    /// Forecast volatility h steps ahead
    pub fn forecast(&self, steps: usize) -> Result<Vec<f64>> {
        if !self.fitted {
            return Err(IntegrateError::ValueError(
                "Model must be fitted before forecasting".to_string(),
            ));
        }

        let mut forecasts = Vec::with_capacity(steps);

        // Start from last conditional variance
        let last_variance = self.conditional_variances.last().copied().ok_or_else(|| {
            IntegrateError::ValueError("No conditional variances available".to_string())
        })?;

        // Multi-step ahead forecast
        let mut current_var = last_variance;
        for _ in 0..steps {
            // σ²_{t+h} = ω + (α + β)*σ²_{t+h-1}
            current_var = self.omega + (self.alpha + self.beta) * current_var;
            forecasts.push(current_var.sqrt()); // Return volatility (std dev)
        }

        Ok(forecasts)
    }

    /// Get unconditional (long-run) volatility
    pub fn unconditional_volatility(&self) -> Result<f64> {
        if !self.fitted {
            return Err(IntegrateError::ValueError("Model not fitted".to_string()));
        }

        let long_run_var = self.omega / (1.0 - self.alpha - self.beta);
        Ok(long_run_var.sqrt())
    }

    /// Compute conditional variances for all time points
    fn compute_conditional_variances(&self, returns: &[f64]) -> Result<Vec<f64>> {
        let n = returns.len();
        let mut variances = Vec::with_capacity(n);

        // Initialize with sample variance
        let sample_var: f64 = returns.iter().map(|r| r * r).sum::<f64>() / n as f64;
        variances.push(sample_var);

        // Recursively compute conditional variances
        for i in 1..n {
            let epsilon_sq = returns[i - 1] * returns[i - 1];
            let var_t = self.omega + self.alpha * epsilon_sq + self.beta * variances[i - 1];
            variances.push(var_t.max(1e-10)); // Prevent negative variance
        }

        Ok(variances)
    }

    /// Quasi-maximum likelihood estimation
    fn quasi_mle_optimization(&self, returns: &[f64], initial: Vec<f64>) -> Result<Vec<f64>> {
        let objective = |params: &[f64]| -> f64 {
            if Self::validate_parameters(params[0], params[1], params[2]).is_err() {
                return 1e10; // Penalty for invalid parameters
            }

            // Compute negative log-likelihood
            self.negative_log_likelihood(returns, params[0], params[1], params[2])
                .unwrap_or(1e10)
        };

        // Simple random search with local refinement
        let mut best_params = initial.clone();
        let mut best_value = objective(&best_params);

        for _ in 0..50 {
            let mut trial = best_params.clone();

            // Perturb parameters
            trial[0] *= 1.0 + (scirs2_core::random::random::<f64>() - 0.5) * 0.2; // ±10% omega
            trial[1] *= 1.0 + (scirs2_core::random::random::<f64>() - 0.5) * 0.2; // ±10% alpha
            trial[2] *= 1.0 + (scirs2_core::random::random::<f64>() - 0.5) * 0.2; // ±10% beta

            // Ensure constraints
            trial[0] = trial[0].max(1e-6).min(0.01);
            trial[1] = trial[1].max(0.01).min(0.30);
            trial[2] = trial[2].max(0.50).min(0.95);

            if trial[1] + trial[2] < 0.9999 {
                let value = objective(&trial);
                if value < best_value {
                    best_params = trial;
                    best_value = value;
                }
            }
        }

        Ok(best_params)
    }

    /// Negative log-likelihood for GARCH(1,1)
    fn negative_log_likelihood(
        &self,
        returns: &[f64],
        omega: f64,
        alpha: f64,
        beta: f64,
    ) -> Result<f64> {
        let n = returns.len();
        let mut log_likelihood = 0.0;

        // Initial variance
        let sample_var: f64 = returns.iter().map(|r| r * r).sum::<f64>() / n as f64;
        let mut var_t = sample_var;

        for &ret in returns {
            // Update variance
            let epsilon_sq = ret * ret;
            var_t = omega + alpha * epsilon_sq + beta * var_t;
            var_t = var_t.max(1e-10); // Prevent numerical issues

            // Log-likelihood contribution (assuming normal distribution)
            log_likelihood += 0.5 * ((2.0 * PI * var_t).ln() + epsilon_sq / var_t);
        }

        Ok(log_likelihood)
    }

    /// Validate GARCH parameters
    fn validate_parameters(omega: f64, alpha: f64, beta: f64) -> Result<()> {
        if omega <= 0.0 {
            return Err(IntegrateError::ValueError(
                "Omega must be positive".to_string(),
            ));
        }
        if !(0.0..=1.0).contains(&alpha) {
            return Err(IntegrateError::ValueError(
                "Alpha must be in [0, 1]".to_string(),
            ));
        }
        if !(0.0..=1.0).contains(&beta) {
            return Err(IntegrateError::ValueError(
                "Beta must be in [0, 1]".to_string(),
            ));
        }
        if alpha + beta >= 1.0 {
            return Err(IntegrateError::ValueError(
                "Alpha + Beta must be < 1 for stationarity".to_string(),
            ));
        }
        Ok(())
    }
}

impl Default for GarchModel {
    fn default() -> Self {
        Self::new()
    }
}

// ============================================================================
// EWMA (Exponentially Weighted Moving Average)
// ============================================================================

/// EWMA volatility estimator (RiskMetrics methodology)
///
/// Model: σ²_t = λ*σ²_{t-1} + (1-λ)*r²_{t-1}
///
/// Standard lambda values:
/// - λ = 0.94 (RiskMetrics daily)
/// - λ = 0.97 (RiskMetrics monthly)
#[derive(Debug, Clone)]
pub struct EWMAModel {
    /// Decay factor (lambda)
    lambda: f64,
}

impl EWMAModel {
    /// Create EWMA model with specified decay factor
    ///
    /// Standard values:
    /// - 0.94 for daily data (RiskMetrics)
    /// - 0.97 for monthly data
    pub fn new(lambda: f64) -> Self {
        assert!(lambda > 0.0 && lambda < 1.0, "Lambda must be in (0, 1)");
        Self { lambda }
    }

    /// Create with RiskMetrics daily lambda (0.94)
    pub fn riskmetrics_daily() -> Self {
        Self::new(0.94)
    }

    /// Create with RiskMetrics monthly lambda (0.97)
    pub fn riskmetrics_monthly() -> Self {
        Self::new(0.97)
    }

    /// Estimate current volatility from return series
    pub fn estimate(&self, returns: &[f64]) -> Result<f64> {
        if returns.is_empty() {
            return Err(IntegrateError::ValueError(
                "Returns array is empty".to_string(),
            ));
        }

        // Initialize with first squared return
        let mut variance = returns[0] * returns[0];

        // EWMA recursion
        for &ret in &returns[1..] {
            variance = self.lambda * variance + (1.0 - self.lambda) * ret * ret;
        }

        Ok(variance.sqrt())
    }

    /// Compute full EWMA volatility series
    pub fn compute_series(&self, returns: &[f64]) -> Result<Vec<f64>> {
        if returns.is_empty() {
            return Err(IntegrateError::ValueError(
                "Returns array is empty".to_string(),
            ));
        }

        let mut volatilities = Vec::with_capacity(returns.len());
        let mut variance = returns[0] * returns[0];
        volatilities.push(variance.sqrt());

        for &ret in &returns[1..] {
            variance = self.lambda * variance + (1.0 - self.lambda) * ret * ret;
            volatilities.push(variance.sqrt());
        }

        Ok(volatilities)
    }

    /// Forecast volatility (assumes no new shocks)
    pub fn forecast(&self, current_vol: f64, steps: usize) -> Vec<f64> {
        let mut variance = current_vol * current_vol;
        let mut forecasts = Vec::with_capacity(steps);

        for _ in 0..steps {
            // Under EWMA, without new information, variance decays
            // σ²_{t+h} = λ^h * σ²_t (with zero expected returns)
            variance *= self.lambda;
            forecasts.push(variance.sqrt());
        }

        forecasts
    }
}

// ============================================================================
// Historical Volatility Estimators
// ============================================================================

/// Historical volatility estimators
pub struct HistoricalVolatility;

impl HistoricalVolatility {
    /// Simple standard deviation of returns
    pub fn simple(returns: &[f64]) -> Result<f64> {
        if returns.is_empty() {
            return Err(IntegrateError::ValueError(
                "Returns array is empty".to_string(),
            ));
        }

        let mean: f64 = returns.iter().sum::<f64>() / returns.len() as f64;
        let variance: f64 =
            returns.iter().map(|r| (r - mean).powi(2)).sum::<f64>() / returns.len() as f64;

        Ok(variance.sqrt())
    }

    /// Realized volatility (sum of squared returns)
    pub fn realized(returns: &[f64]) -> Result<f64> {
        if returns.is_empty() {
            return Err(IntegrateError::ValueError(
                "Returns array is empty".to_string(),
            ));
        }

        let sum_sq: f64 = returns.iter().map(|r| r * r).sum();
        Ok((sum_sq / returns.len() as f64).sqrt())
    }

    /// Parkinson estimator (high-low range based)
    /// More efficient than close-to-close for intraday data
    pub fn parkinson(high_prices: &[f64], low_prices: &[f64]) -> Result<f64> {
        if high_prices.len() != low_prices.len() {
            return Err(IntegrateError::ValueError(
                "High and low price arrays must have same length".to_string(),
            ));
        }
        if high_prices.is_empty() {
            return Err(IntegrateError::ValueError(
                "Price arrays are empty".to_string(),
            ));
        }

        let n = high_prices.len() as f64;
        let sum: f64 = high_prices
            .iter()
            .zip(low_prices.iter())
            .map(|(&h, &l)| {
                let ratio = h / l;
                ratio.ln().powi(2)
            })
            .sum();

        // Parkinson constant: 1 / (4 * ln(2))
        let constant = 1.0 / (4.0 * 2_f64.ln());
        Ok((constant * sum / n).sqrt())
    }

    /// Annualize volatility (from periodic to annual)
    ///
    /// # Arguments
    /// * `vol` - Periodic volatility (e.g., daily)
    /// * `periods_per_year` - Number of periods per year (e.g., 252 for daily, 12 for monthly)
    pub fn annualize(vol: f64, periods_per_year: f64) -> f64 {
        vol * periods_per_year.sqrt()
    }
}

// ============================================================================
// Unified Volatility Forecaster Interface
// ============================================================================

/// Unified interface for volatility forecasting
pub trait VolatilityForecaster {
    /// Fit model to historical returns
    fn fit(&mut self, returns: &[f64]) -> Result<()>;

    /// Forecast volatility for multiple periods
    fn forecast(&self, steps: usize) -> Result<Vec<f64>>;

    /// Get current volatility estimate
    fn current_volatility(&self) -> Result<f64>;
}

impl VolatilityForecaster for GarchModel {
    fn fit(&mut self, returns: &[f64]) -> Result<()> {
        GarchModel::fit(self, returns)
    }

    fn forecast(&self, steps: usize) -> Result<Vec<f64>> {
        GarchModel::forecast(self, steps)
    }

    fn current_volatility(&self) -> Result<f64> {
        if !self.fitted {
            return Err(IntegrateError::ValueError("Model not fitted".to_string()));
        }
        self.conditional_variances
            .last()
            .map(|v| v.sqrt())
            .ok_or_else(|| IntegrateError::ValueError("No variances available".to_string()))
    }
}

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

    fn generate_test_returns() -> Vec<f64> {
        vec![
            0.01, -0.02, 0.015, -0.01, 0.005, 0.02, -0.015, 0.01, -0.005, 0.012, -0.018, 0.025,
            -0.012, 0.008, -0.022, 0.014, -0.009, 0.016, -0.013, 0.011,
        ]
    }

    #[test]
    fn test_garch_model_creation() {
        let garch = GarchModel::new();
        assert!(!garch.fitted);
        assert_eq!(garch.omega, 0.0);
        assert_eq!(garch.alpha, 0.0);
        assert_eq!(garch.beta, 0.0);
    }

    #[test]
    fn test_garch_parameter_validation() {
        // Valid parameters
        assert!(GarchModel::with_parameters(0.00001, 0.05, 0.90).is_ok());

        // Invalid: omega <= 0
        assert!(GarchModel::with_parameters(0.0, 0.05, 0.90).is_err());

        // Invalid: alpha + beta >= 1
        assert!(GarchModel::with_parameters(0.00001, 0.50, 0.50).is_err());

        // Invalid: negative alpha
        assert!(GarchModel::with_parameters(0.00001, -0.05, 0.90).is_err());
    }

    #[test]
    fn test_garch_fit() {
        let returns = generate_test_returns();
        let mut garch = GarchModel::new();

        let result = garch.fit(&returns);
        assert!(result.is_ok());
        assert!(garch.fitted);

        // Check parameters are in reasonable ranges
        assert!(garch.omega > 0.0);
        assert!(garch.alpha >= 0.0 && garch.alpha < 1.0);
        assert!(garch.beta >= 0.0 && garch.beta < 1.0);
        assert!(garch.alpha + garch.beta < 1.0);

        // Check conditional variances computed
        assert_eq!(garch.conditional_variances.len(), returns.len());
    }

    #[test]
    fn test_garch_forecast() {
        let returns = generate_test_returns();
        let mut garch = GarchModel::new();
        garch.fit(&returns).expect("Operation failed");

        let forecast = garch.forecast(5).expect("Operation failed");
        assert_eq!(forecast.len(), 5);

        // All forecasts should be positive
        assert!(forecast.iter().all(|&v| v > 0.0));

        // Forecasts should converge to long-run volatility
        let long_run = garch.unconditional_volatility().expect("Operation failed");
        assert!(forecast[4] > forecast[0] * 0.5); // Some convergence observed
    }

    #[test]
    fn test_ewma_basic() {
        let ewma = EWMAModel::new(0.94);
        assert_eq!(ewma.lambda, 0.94);

        let returns = generate_test_returns();
        let vol = ewma.estimate(&returns).expect("Operation failed");

        assert!(vol > 0.0);
        assert!(vol < 1.0); // Reasonable volatility range
    }

    #[test]
    fn test_ewma_riskmetrics() {
        let daily = EWMAModel::riskmetrics_daily();
        assert_eq!(daily.lambda, 0.94);

        let monthly = EWMAModel::riskmetrics_monthly();
        assert_eq!(monthly.lambda, 0.97);
    }

    #[test]
    fn test_ewma_series() {
        let ewma = EWMAModel::new(0.94);
        let returns = generate_test_returns();

        let series = ewma.compute_series(&returns).expect("Operation failed");
        assert_eq!(series.len(), returns.len());

        // All volatilities should be positive
        assert!(series.iter().all(|&v| v > 0.0));
    }

    #[test]
    fn test_ewma_forecast() {
        let ewma = EWMAModel::new(0.94);
        let current_vol = 0.15; // 15% volatility

        let forecast = ewma.forecast(current_vol, 5);
        assert_eq!(forecast.len(), 5);

        // Volatility should decay without new information
        assert!(forecast[0] < current_vol);
        assert!(forecast[4] < forecast[0]);
    }

    #[test]
    fn test_historical_simple() {
        let returns = generate_test_returns();
        let vol = HistoricalVolatility::simple(&returns).expect("Operation failed");

        assert!(vol > 0.0);
        assert!(vol < 0.5); // Reasonable range
    }

    #[test]
    fn test_historical_realized() {
        let returns = generate_test_returns();
        let vol = HistoricalVolatility::realized(&returns).expect("Operation failed");

        assert!(vol > 0.0);
        assert!(vol < 0.5);
    }

    #[test]
    fn test_parkinson_estimator() {
        let highs = vec![101.0, 102.5, 103.0, 102.0, 104.0];
        let lows = vec![99.0, 100.5, 101.0, 100.0, 102.0];

        let vol = HistoricalVolatility::parkinson(&highs, &lows).expect("Operation failed");
        assert!(vol > 0.0);
    }

    #[test]
    fn test_annualization() {
        let daily_vol = 0.01; // 1% daily
        let annual_vol = HistoricalVolatility::annualize(daily_vol, 252.0);

        // Should be approximately daily_vol * sqrt(252) ≈ 0.1587
        assert!((annual_vol - 0.1587).abs() < 0.001);
    }

    #[test]
    fn test_garch_insufficient_data() {
        let short_returns = vec![0.01, 0.02]; // Only 2 observations
        let mut garch = GarchModel::new();

        assert!(garch.fit(&short_returns).is_err());
    }

    #[test]
    fn test_ewma_empty_returns() {
        let ewma = EWMAModel::new(0.94);
        let empty: Vec<f64> = vec![];

        assert!(ewma.estimate(&empty).is_err());
    }
}