Skip to main content

quantwave_core/indicators/
hann.rs

1use crate::indicators::metadata::{IndicatorMetadata, ParamDef};
2use crate::traits::Next;
3use std::collections::VecDeque;
4use std::f64::consts::PI;
5
6/// Hann Windowed Lowpass FIR Filter
7///
8/// Based on John Ehlers' "Just Ignore Them".
9/// A finite impulse response (FIR) filter using a Hann window for smoothing.
10#[derive(Debug, Clone)]
11pub struct HannFilter {
12    length: usize,
13    window: VecDeque<f64>,
14    coefficients: Vec<f64>,
15    coef_sum: f64,
16}
17
18impl HannFilter {
19    pub fn new(length: usize) -> Self {
20        let mut coefficients = Vec::with_capacity(length);
21        let mut coef_sum = 0.0;
22        for count in 1..=length {
23            let coef = 1.0 - (2.0 * PI * count as f64 / (length as f64 + 1.0)).cos();
24            coefficients.push(coef);
25            coef_sum += coef;
26        }
27        
28        Self {
29            length,
30            window: VecDeque::with_capacity(length),
31            coefficients,
32            coef_sum,
33        }
34    }
35}
36
37impl Default for HannFilter {
38    fn default() -> Self {
39        Self::new(20)
40    }
41}
42
43impl Next<f64> for HannFilter {
44    type Output = f64;
45
46    fn next(&mut self, input: f64) -> Self::Output {
47        self.window.push_front(input);
48        if self.window.len() > self.length {
49            self.window.pop_back();
50        }
51
52        if self.window.len() < self.length {
53            return input;
54        }
55
56        let mut filt = 0.0;
57        for (i, &val) in self.window.iter().enumerate() {
58            filt += self.coefficients[i] * val;
59        }
60
61        if self.coef_sum != 0.0 {
62            filt / self.coef_sum
63        } else {
64            input
65        }
66    }
67}
68
69pub const HANN_FILTER_METADATA: IndicatorMetadata = IndicatorMetadata {
70    name: "HannFilter",
71    description: "Hann windowed lowpass FIR filter.",
72    params: &[
73        ParamDef {
74            name: "length",
75            default: "20",
76            description: "Filter length",
77        },
78    ],
79    formula_source: "https://github.com/lavs9/quantwave/blob/main/references/Ehlers%20Papers/JustIgnoreThem.pdf",
80    formula_latex: r#"
81\[
82H(n) = 1 - \cos\left(\frac{2\pi n}{L+1}\right)
83\]
84\[
85Filt = \frac{\sum_{n=1}^L H(n) \cdot Price_{t-n+1}}{\sum H(n)}
86\]
87"#,
88    gold_standard_file: "hann_filter.json",
89    category: "Ehlers DSP",
90};
91
92#[cfg(test)]
93mod tests {
94    use super::*;
95    use crate::traits::Next;
96    use proptest::prelude::*;
97
98    #[test]
99    fn test_hann_basic() {
100        let mut hann = HannFilter::new(20);
101        for _ in 0..50 {
102            let val = hann.next(100.0);
103            approx::assert_relative_eq!(val, 100.0, epsilon = 1e-10);
104        }
105    }
106
107    proptest! {
108        #[test]
109        fn test_hann_parity(
110            inputs in prop::collection::vec(1.0..100.0, 50..100),
111        ) {
112            let length = 20;
113            let mut hann = HannFilter::new(length);
114            let streaming_results: Vec<f64> = inputs.iter().map(|&x| hann.next(x)).collect();
115
116            // Batch implementation
117            let mut batch_results = Vec::with_capacity(inputs.len());
118            let mut coeffs = Vec::new();
119            let mut c_sum = 0.0;
120            for count in 1..=length {
121                let c = 1.0 - (2.0 * PI * count as f64 / (length as f64 + 1.0)).cos();
122                coeffs.push(c);
123                c_sum += c;
124            }
125
126            for i in 0..inputs.len() {
127                if i < length - 1 {
128                    batch_results.push(inputs[i]);
129                    continue;
130                }
131                let mut f = 0.0;
132                for j in 0..length {
133                    f += coeffs[j] * inputs[i - j];
134                }
135                batch_results.push(f / c_sum);
136            }
137
138            for (s, b) in streaming_results.iter().zip(batch_results.iter()) {
139                approx::assert_relative_eq!(s, b, epsilon = 1e-10);
140            }
141        }
142    }
143}