use crate::filter::FilterError;
use crate::state_space::Innovation;
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct GarchSpec {
pub omega: f64,
pub alpha: f64,
pub beta: f64,
pub variance: f64,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct GarchFilter {
omega: f64,
alpha: f64,
beta: f64,
variance: f64,
}
impl GarchFilter {
pub fn new(spec: &GarchSpec) -> Result<Self, FilterError> {
let finite = [spec.omega, spec.alpha, spec.beta, spec.variance]
.iter()
.all(|v| v.is_finite());
let valid = finite
&& spec.omega > 0.0
&& spec.variance > 0.0
&& spec.alpha >= 0.0
&& spec.beta >= 0.0
&& spec.alpha + spec.beta < 1.0;
if !valid {
return Err(FilterError::InvalidParameter);
}
Ok(Self {
omega: spec.omega,
alpha: spec.alpha,
beta: spec.beta,
variance: spec.variance,
})
}
pub fn update(&mut self, x: f64) -> Innovation {
let square = x * x;
let observed = square.is_finite();
let innovation = Innovation {
value: if observed { x } else { f64::NAN },
variance: self.variance,
};
let shock = if observed { square } else { self.variance };
self.variance = self.omega + self.alpha * shock + self.beta * self.variance;
innovation
}
pub fn warm_up(&mut self, history: &[f64]) {
for &x in history {
self.update(x);
}
}
pub fn forecast_into(&self, variance: &mut [f64]) {
let persistence = self.alpha + self.beta;
let mut h = self.variance;
for value in variance.iter_mut() {
*value = h;
h = self.omega + persistence * h;
}
}
#[must_use]
pub const fn variance(&self) -> f64 {
self.variance
}
#[must_use]
pub fn unconditional_variance(&self) -> f64 {
self.omega / (1.0 - self.alpha - self.beta)
}
}
#[cfg(test)]
mod tests {
use super::*;
const fn spec(variance: f64) -> GarchSpec {
GarchSpec {
omega: 0.2,
alpha: 0.1,
beta: 0.7,
variance,
}
}
#[test]
fn forecasts_decay_to_the_long_run_variance() {
let filter = GarchFilter::new(&spec(5.0)).unwrap();
let mut variance = [0.0; 200];
filter.forecast_into(&mut variance);
assert_eq!(variance[0], 5.0);
assert!((variance[1] - (0.2 + 0.8 * 5.0)).abs() < 1e-15);
assert!((variance[199] - filter.unconditional_variance()).abs() < 1e-12);
}
#[test]
fn missing_and_overflowing_values_use_the_expectation() {
for missing in [f64::NAN, f64::INFINITY, 1e200] {
let mut filter = GarchFilter::new(&spec(2.0)).unwrap();
assert!(filter.update(missing).value.is_nan());
assert!((filter.variance() - (0.2 + 0.8 * 2.0)).abs() < 1e-15);
}
}
#[test]
fn rejects_invalid_parameters() {
let bad = [
GarchSpec {
omega: 0.0,
..spec(1.0)
},
GarchSpec {
alpha: -0.1,
..spec(1.0)
},
GarchSpec {
beta: 0.9,
..spec(1.0)
},
GarchSpec {
variance: f64::NAN,
..spec(1.0)
},
];
for spec in bad {
assert_eq!(GarchFilter::new(&spec), Err(FilterError::InvalidParameter));
}
}
}