quantwave_core/indicators/
triangle.rs1use crate::indicators::metadata::{IndicatorMetadata, ParamDef};
2use crate::traits::Next;
3use std::collections::VecDeque;
4
5#[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: &[
81 ParamDef {
82 name: "length",
83 default: "20",
84 description: "Filter length",
85 },
86 ],
87 formula_source: "https://github.com/lavs9/quantwave/blob/main/references/traderstipsreference/TRADERS’ TIPS - SEPTEMBER 2021.html",
88 formula_latex: r#"
89\[
90Coef(n) = \begin{cases} n & n < L/2 \\ L/2 & n = L/2 \\ L + 1 - n & n > L/2 \end{cases}
91\]
92\[
93Filt = \frac{\sum_{n=1}^L Coef(n) \cdot Price_{t-n+1}}{\sum Coef(n)}
94\]
95"#,
96 gold_standard_file: "triangle_filter.json",
97 category: "Ehlers DSP",
98};
99
100#[cfg(test)]
101mod tests {
102 use super::*;
103 use crate::traits::Next;
104 use proptest::prelude::*;
105
106 #[test]
107 fn test_triangle_basic() {
108 let mut tri = TriangleFilter::new(20);
109 for _ in 0..50 {
110 let val = tri.next(100.0);
111 approx::assert_relative_eq!(val, 100.0, epsilon = 1e-10);
112 }
113 }
114
115 proptest! {
116 #[test]
117 fn test_triangle_parity(
118 inputs in prop::collection::vec(1.0..100.0, 50..100),
119 ) {
120 let length = 20;
121 let mut tri = TriangleFilter::new(length);
122 let streaming_results: Vec<f64> = inputs.iter().map(|&x| tri.next(x)).collect();
123
124 let mut batch_results = Vec::with_capacity(inputs.len());
126 let mut coeffs = Vec::new();
127 let mut c_sum = 0.0;
128 for count in 1..=length {
129 let coef = if (count as f64) < (length as f64 / 2.0) {
130 count as f64
131 } else if (count as f64) == (length as f64 / 2.0) {
132 length as f64 / 2.0
133 } else {
134 length as f64 + 1.0 - count as f64
135 };
136 coeffs.push(coef);
137 c_sum += coef;
138 }
139
140 for i in 0..inputs.len() {
141 if i < length - 1 {
142 batch_results.push(inputs[i]);
143 continue;
144 }
145 let mut f = 0.0;
146 for j in 0..length {
147 f += coeffs[j] * inputs[i - j];
148 }
149 batch_results.push(f / c_sum);
150 }
151
152 for (s, b) in streaming_results.iter().zip(batch_results.iter()) {
153 approx::assert_relative_eq!(s, b, epsilon = 1e-10);
154 }
155 }
156 }
157}