Skip to main content

quantwave_core/indicators/
triangle.rs

1use crate::indicators::metadata::{IndicatorMetadata, ParamDef};
2use crate::traits::Next;
3use crate::utils::RingBuffer as VecDeque;
4
5/// Triangle Windowed FIR Filter
6///
7/// Based on John Ehlers' "Windowing" (S&C 2021).
8/// A finite impulse response (FIR) filter using a triangle-shaped window for smoothing.
9#[derive(Debug, Clone)]
10pub struct TriangleFilter {
11    length: usize,
12    window: VecDeque<f64>,
13    coefficients: Vec<f64>,
14    coef_sum: f64,
15}
16
17impl TriangleFilter {
18    pub fn new(length: usize) -> Self {
19        let mut coefficients = Vec::with_capacity(length);
20        let mut coef_sum = 0.0;
21        for count in 1..=length {
22            let coef = if (count as f64) < (length as f64 / 2.0) {
23                count as f64
24            } else if (count as f64) == (length as f64 / 2.0) {
25                length as f64 / 2.0
26            } else {
27                length as f64 + 1.0 - count as f64
28            };
29            coefficients.push(coef);
30            coef_sum += coef;
31        }
32
33        Self {
34            length,
35            window: VecDeque::with_capacity(length),
36            coefficients,
37            coef_sum,
38        }
39    }
40}
41
42impl Default for TriangleFilter {
43    fn default() -> Self {
44        Self::new(20)
45    }
46}
47
48impl Next<f64> for TriangleFilter {
49    type Output = f64;
50
51    fn next(&mut self, input: f64) -> Self::Output {
52        self.window.push_front(input);
53        if self.window.len() > self.length {
54            self.window.pop_back();
55        }
56
57        if self.window.len() < self.length {
58            return input;
59        }
60
61        let mut filt = 0.0;
62        for (i, &val) in self.window.iter().enumerate() {
63            filt += self.coefficients[i] * val;
64        }
65
66        if self.coef_sum.abs() > 1e-10 {
67            filt / self.coef_sum
68        } else {
69            input
70        }
71    }
72}
73
74pub const TRIANGLE_FILTER_METADATA: IndicatorMetadata = IndicatorMetadata {
75    name: "TriangleFilter",
76    description: "Triangle windowed FIR filter.",
77    usage: "Use as a pre-smoother to reduce noise before applying cycle or momentum indicators when a symmetric low-ripple response is needed.",
78    keywords: &["filter", "ehlers", "dsp", "smoothing", "triangle"],
79    ehlers_summary: "The Triangle (Bartlett) window is a linearly-tapered FIR filter equivalent to applying two rectangular windows in sequence. It provides moderate sidelobe suppression and is useful when computational simplicity is preferred over maximum spectral attenuation.",
80    params: &[ParamDef {
81        name: "length",
82        default: "20",
83        description: "Filter length",
84    }],
85    formula_source: "https://github.com/lavs9/quantwave/blob/main/references/traderstipsreference/TRADERS’ TIPS - SEPTEMBER 2021.html",
86    formula_latex: r#"
87\[
88Coef(n) = \begin{cases} n & n < L/2 \\ L/2 & n = L/2 \\ L + 1 - n & n > L/2 \end{cases}
89\]
90\[
91Filt = \frac{\sum_{n=1}^L Coef(n) \cdot Price_{t-n+1}}{\sum Coef(n)}
92\]
93"#,
94    gold_standard_file: "triangle_filter.json",
95    category: "Ehlers DSP",
96};
97
98#[cfg(test)]
99mod tests {
100    use super::*;
101    use crate::traits::Next;
102    use proptest::prelude::*;
103
104    #[test]
105    fn test_triangle_basic() {
106        let mut tri = TriangleFilter::new(20);
107        for _ in 0..50 {
108            let val = tri.next(100.0);
109            approx::assert_relative_eq!(val, 100.0, epsilon = 1e-10);
110        }
111    }
112
113    proptest! {
114        #[test]
115        fn test_triangle_parity(
116            inputs in prop::collection::vec(1.0..100.0, 50..100),
117        ) {
118            let length = 20;
119            let mut tri = TriangleFilter::new(length);
120            let streaming_results: Vec<f64> = inputs.iter().map(|&x| tri.next(x)).collect();
121
122            // Batch implementation
123            let mut batch_results = Vec::with_capacity(inputs.len());
124            let mut coeffs = Vec::new();
125            let mut c_sum = 0.0;
126            for count in 1..=length {
127                let coef = if (count as f64) < (length as f64 / 2.0) {
128                    count as f64
129                } else if (count as f64) == (length as f64 / 2.0) {
130                    length as f64 / 2.0
131                } else {
132                    length as f64 + 1.0 - count as f64
133                };
134                coeffs.push(coef);
135                c_sum += coef;
136            }
137
138            for i in 0..inputs.len() {
139                if i < length - 1 {
140                    batch_results.push(inputs[i]);
141                    continue;
142                }
143                let mut f = 0.0;
144                for j in 0..length {
145                    f += coeffs[j] * inputs[i - j];
146                }
147                batch_results.push(f / c_sum);
148            }
149
150            for (s, b) in streaming_results.iter().zip(batch_results.iter()) {
151                approx::assert_relative_eq!(s, b, epsilon = 1e-10);
152            }
153        }
154    }
155}