use alloc::vec::Vec;
use super::FitError;
use super::bfgs;
use crate::garch::{GarchFilter, GarchSpec};
use crate::math;
const MIN_VALUES: usize = 10;
const STARTS: [(f64, f64); 4] = [(0.05, 0.9), (0.1, 0.8), (0.2, 0.5), (0.1, 0.1)];
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct Garch;
#[derive(Debug, Clone, PartialEq)]
pub struct GarchFit {
pub omega: f64,
pub alpha: f64,
pub beta: f64,
pub loglike: f64,
pub variances: Vec<f64>,
pub variance: f64,
}
impl Garch {
#[must_use]
pub const fn new() -> Self {
Self
}
pub fn fit(&self, x: &[f64]) -> Result<GarchFit, FitError> {
if !math::all_finite(x) {
return Err(FitError::Unsupported);
}
if x.len() < MIN_VALUES {
return Err(FitError::TooShort {
needed: MIN_VALUES,
present: x.len(),
});
}
let scale = x.iter().map(|v| v * v).sum::<f64>() / count_as_f64(x.len());
if !(scale > 0.0 && scale.is_finite()) {
return Err(FitError::Degenerate);
}
let mut scratch = alloc::vec![0.0; bfgs::scratch_len(3)];
let u = STARTS
.iter()
.map(|&(alpha, beta)| {
let mut u = coordinates(alpha, beta);
bfgs::minimize(
|u| deviance(x, scale, u),
&mut u,
&mut scratch,
bfgs::Options::default(),
);
(deviance(x, scale, &u), u)
})
.filter(|(value, _)| value.is_finite())
.min_by(|a, b| a.0.total_cmp(&b.0))
.map(|(_, u)| u)
.ok_or(FitError::Degenerate)?;
Self::result(x, scale, &u).ok_or(FitError::Degenerate)
}
fn result(x: &[f64], scale: f64, u: &[f64; 3]) -> Option<GarchFit> {
let spec = spec(scale, u);
let mut filter = GarchFilter::new(&spec).ok()?;
let variances = x.iter().map(|&v| filter.update(v).variance).collect();
let terms = count_as_f64(x.len() - 1);
Some(GarchFit {
omega: spec.omega,
alpha: spec.alpha,
beta: spec.beta,
loglike: -0.5 * deviance(x, scale, u) - 0.5 * terms * math::ln(core::f64::consts::TAU),
variances,
variance: filter.variance(),
})
}
}
impl GarchFit {
#[must_use]
pub const fn spec(&self) -> GarchSpec {
GarchSpec {
omega: self.omega,
alpha: self.alpha,
beta: self.beta,
variance: self.variance,
}
}
}
fn coordinates(alpha: f64, beta: f64) -> [f64; 3] {
let persistence = alpha + beta;
[
math::ln(1.0 - persistence),
logit(persistence),
logit(alpha / persistence),
]
}
fn spec(scale: f64, u: &[f64]) -> GarchSpec {
let persistence = logistic(u[1]);
let alpha = persistence * logistic(u[2]);
GarchSpec {
omega: scale * math::exp(u[0]),
alpha,
beta: persistence - alpha,
variance: scale,
}
}
fn deviance(x: &[f64], scale: f64, u: &[f64]) -> f64 {
let Ok(mut filter) = GarchFilter::new(&spec(scale, u)) else {
return f64::INFINITY;
};
let Some((&first, rest)) = x.split_first() else {
return f64::INFINITY;
};
filter.update(first);
rest.iter()
.map(|&v| {
let h = filter.update(v).variance;
math::ln(h) + v * v / h
})
.sum()
}
fn logistic(u: f64) -> f64 {
1.0 / (1.0 + math::exp(-u))
}
fn logit(p: f64) -> f64 {
math::ln(p / (1.0 - p))
}
#[expect(
clippy::cast_precision_loss,
reason = "value counts stay far below 2^53, where the conversion is exact"
)]
fn count_as_f64(count: usize) -> f64 {
count as f64
}