Skip to main content

quantwave_core/indicators/
fisher_high_pass.rs

1use crate::indicators::metadata::{IndicatorMetadata, ParamDef};
2use crate::traits::Next;
3use crate::indicators::high_pass::HighPass;
4use std::collections::VecDeque;
5
6/// Fisher HighPass Indicator
7///
8/// Based on John Ehlers' "Inferring Trading Strategies from Probability Distribution Functions".
9/// Applies a HighPass filter, normalizes the result to [-1, 1], smooths it with a 3-tap FIR,
10/// and then applies the Fisher Transform.
11#[derive(Debug, Clone)]
12pub struct FisherHighPass {
13    hp: HighPass,
14    period: usize,
15    hp_window: VecDeque<f64>,
16    smooth_history: [f64; 2],
17    count: usize,
18}
19
20impl FisherHighPass {
21    pub fn new(hp_len: usize, norm_len: usize) -> Self {
22        Self {
23            hp: HighPass::new(hp_len),
24            period: norm_len,
25            hp_window: VecDeque::with_capacity(norm_len),
26            smooth_history: [0.0; 2],
27            count: 0,
28        }
29    }
30}
31
32impl Default for FisherHighPass {
33    fn default() -> Self {
34        Self::new(20, 20)
35    }
36}
37
38impl Next<f64> for FisherHighPass {
39    type Output = f64;
40
41    fn next(&mut self, input: f64) -> Self::Output {
42        self.count += 1;
43        let hp_val = self.hp.next(input);
44
45        self.hp_window.push_front(hp_val);
46        if self.hp_window.len() > self.period {
47            self.hp_window.pop_back();
48        }
49
50        if self.hp_window.len() < self.period {
51            return 0.0;
52        }
53
54        let mut high = f64::MIN;
55        let mut low = f64::MAX;
56        for &v in &self.hp_window {
57            if v > high { high = v; }
58            if v < low { low = v; }
59        }
60
61        let normalized = if high != low {
62            2.0 * (hp_val - low) / (high - low) - 1.0
63        } else {
64            0.0
65        };
66
67        // 3-tap FIR smoothing: (N + N[1] + N[2]) / 3
68        let smoothed = (normalized + self.smooth_history[0] + self.smooth_history[1]) / 3.0;
69        
70        self.smooth_history[1] = self.smooth_history[0];
71        self.smooth_history[0] = normalized;
72
73        // Fisher Transform
74        // y = 0.5 * ln((1+x)/(1-x))
75        // Clip to avoid log(0)
76        let x = smoothed.clamp(-0.999, 0.999);
77        0.5 * ((1.0 + x) / (1.0 - x)).ln()
78    }
79}
80
81pub const FISHER_HIGH_PASS_METADATA: IndicatorMetadata = IndicatorMetadata {
82    name: "FisherHighPass",
83    description: "Fisher Transform applied to normalized HighPass filtered prices.",
84    usage: "Use to isolate high-frequency momentum from the cyclical component of price after trend removal. Provides a purer momentum signal than standard Fisher Transform applied to raw price.",
85    keywords: &["oscillator", "ehlers", "dsp", "high-pass", "momentum"],
86    ehlers_summary: "FisherHighPass applies the Fisher Transform to the high-pass filtered price rather than raw price. By first removing the low-frequency trend component with a high-pass filter, the resulting Fisher output captures only the cycle-domain momentum, producing an oscillator that is unaffected by the prevailing trend direction.",
87    params: &[
88        ParamDef {
89            name: "hp_len",
90            default: "20",
91            description: "HighPass filter length",
92        },
93        ParamDef {
94            name: "norm_len",
95            default: "20",
96            description: "Normalization lookback period",
97        },
98    ],
99    formula_source: "https://github.com/lavs9/quantwave/blob/main/references/Ehlers%20Papers/InferringTradingStrategies.pdf",
100    formula_latex: r#"
101\[
102HP = \text{HighPass}(Price, hp\_len)
103\]
104\[
105N = 2 \cdot \frac{HP - Low(HP, norm\_len)}{High(HP, norm\_len) - Low(HP, norm\_len)} - 1
106\]
107\[
108S = \frac{N + N_{t-1} + N_{t-2}}{3}
109\]
110\[
111Fisher = 0.5 \cdot \ln\left(\frac{1+S}{1-S}\right)
112\]
113"#,
114    gold_standard_file: "fisher_high_pass.json",
115    category: "Ehlers DSP",
116};
117
118#[cfg(test)]
119mod tests {
120    use super::*;
121    use crate::traits::Next;
122    use proptest::prelude::*;
123
124    #[test]
125    fn test_fisher_hp_basic() {
126        let mut fhp = FisherHighPass::new(20, 20);
127        for i in 0..100 {
128            let val = fhp.next(100.0 + (i as f64 * 0.1).sin());
129            assert!(!val.is_nan());
130        }
131    }
132
133    proptest! {
134        #[test]
135        fn test_fisher_hp_parity(
136            inputs in prop::collection::vec(1.0..100.0, 100..200),
137        ) {
138            let hp_len = 20;
139            let norm_len = 20;
140            let mut fhp = FisherHighPass::new(hp_len, norm_len);
141            let streaming_results: Vec<f64> = inputs.iter().map(|&x| fhp.next(x)).collect();
142
143            // Batch implementation
144            let mut batch_results = Vec::with_capacity(inputs.len());
145            let mut hp = HighPass::new(hp_len);
146            let hp_vals: Vec<f64> = inputs.iter().map(|&x| hp.next(x)).collect();
147
148            let mut norm_vals = Vec::new();
149            for i in 0..hp_vals.len() {
150                let start = if i >= norm_len - 1 { i + 1 - norm_len } else { 0 };
151                let window = &hp_vals[start..i + 1];
152                
153                if window.len() < norm_len {
154                    batch_results.push(0.0);
155                    norm_vals.push(0.0);
156                    continue;
157                }
158
159                let mut high = f64::MIN;
160                let mut low = f64::MAX;
161                for &v in window {
162                    if v > high { high = v; }
163                    if v < low { low = v; }
164                }
165
166                let n = if high != low {
167                    2.0 * (hp_vals[i] - low) / (high - low) - 1.0
168                } else {
169                    0.0
170                };
171                norm_vals.push(n);
172
173                let s = (norm_vals[i] + (if i > 0 { norm_vals[i-1] } else { 0.0 }) + (if i > 1 { norm_vals[i-2] } else { 0.0 })) / 3.0;
174                let x = s.clamp(-0.999, 0.999);
175                batch_results.push(0.5 * ((1.0 + x) / (1.0 - x)).ln());
176            }
177
178            for (s, b) in streaming_results.iter().zip(batch_results.iter()) {
179                approx::assert_relative_eq!(s, b, epsilon = 1e-10);
180            }
181        }
182    }
183}