quantwave_core/indicators/
butterworth.rs1use crate::indicators::metadata::{IndicatorMetadata, ParamDef};
2use crate::traits::Next;
3use std::f64::consts::PI;
4
5#[derive(Debug, Clone)]
10pub struct Butterworth2 {
11 c1: f64,
12 b: f64,
13 aa: f64,
14 price_history: [f64; 2],
15 filt_history: [f64; 2],
16 count: usize,
17}
18
19impl Butterworth2 {
20 pub fn new(period: usize) -> Self {
21 let p = period as f64;
22 let a = (-1.414 * PI / p).exp();
23 let b = 2.0 * a * (1.414 * PI / p).cos();
24 let aa = a * a;
25 let c1 = (1.0 - b + aa) / 4.0;
26 Self {
27 c1,
28 b,
29 aa,
30 price_history: [0.0; 2],
31 filt_history: [0.0; 2],
32 count: 0,
33 }
34 }
35}
36
37impl Next<f64> for Butterworth2 {
38 type Output = f64;
39
40 fn next(&mut self, input: f64) -> Self::Output {
41 self.count += 1;
42 let res = if self.count < 3 {
43 input
44 } else {
45 self.b * self.filt_history[0] - self.aa * self.filt_history[1]
46 + self.c1 * (input + 2.0 * self.price_history[0] + self.price_history[1])
47 };
48
49 self.filt_history[1] = self.filt_history[0];
50 self.filt_history[0] = res;
51 self.price_history[1] = self.price_history[0];
52 self.price_history[0] = input;
53 res
54 }
55}
56
57#[derive(Debug, Clone)]
62pub struct Butterworth3 {
63 c1: f64,
64 b: f64,
65 c: f64,
66 bc: f64,
67 cc: f64,
68 price_history: [f64; 3],
69 filt_history: [f64; 3],
70 count: usize,
71}
72
73impl Butterworth3 {
74 pub fn new(period: usize) -> Self {
75 let p = period as f64;
76 let a = (-PI / p).exp();
77 let b = 2.0 * a * (1.738 * PI / p).cos();
78 let c = a * a;
79 let bc = b * c;
80 let cc = c * c;
81 let c1 = (1.0 - b + c) * (1.0 - c) / 8.0;
82 Self {
83 c1,
84 b,
85 c,
86 bc,
87 cc,
88 price_history: [0.0; 3],
89 filt_history: [0.0; 3],
90 count: 0,
91 }
92 }
93}
94
95impl Next<f64> for Butterworth3 {
96 type Output = f64;
97
98 fn next(&mut self, input: f64) -> Self::Output {
99 self.count += 1;
100 let res = if self.count < 4 {
101 input
102 } else {
103 (self.b + self.c) * self.filt_history[0]
104 - (self.c + self.bc) * self.filt_history[1]
105 + self.cc * self.filt_history[2]
106 + self.c1 * (input + 3.0 * self.price_history[0] + 3.0 * self.price_history[1] + self.price_history[2])
107 };
108
109 self.filt_history[2] = self.filt_history[1];
110 self.filt_history[1] = self.filt_history[0];
111 self.filt_history[0] = res;
112 self.price_history[2] = self.price_history[1];
113 self.price_history[1] = self.price_history[0];
114 self.price_history[0] = input;
115 res
116 }
117}
118
119pub const BUTTERWORTH2_METADATA: IndicatorMetadata = IndicatorMetadata {
120 name: "Butterworth2",
121 description: "2-pole Butterworth low-pass filter.",
122 usage: "Use to smooth price or intermediate indicator values with a flat passband and sharp rolloff. The 3-pole version provides steeper attenuation at the cost of marginally more lag.",
123 keywords: &["filter", "ehlers", "dsp", "smoothing", "low-pass"],
124 ehlers_summary: "Butterworth filters are maximally flat in the passband, introducing no ripple. Ehlers implements 2-pole and 3-pole Butterworth IIR designs in Cycle Analytics for Traders, noting that the SuperSmoother is actually a critically-damped 2-pole Butterworth variant.",
125 params: &[ParamDef {
126 name: "period",
127 default: "14",
128 description: "Critical period",
129 }],
130 formula_source: "https://github.com/lavs9/quantwave/blob/main/references/Ehlers%20Papers/Poles.pdf",
131 formula_latex: r#"
132\[
133a = \exp(-1.414\pi/P)
134\]
135\[
136b = 2a \cos(1.414\pi/P)
137\]
138\[
139f = bf_{t-1} - a^2f_{t-2} + \frac{1-b+a^2}{4}(g + 2g_{t-1} + g_{t-2})
140\]
141"#,
142 gold_standard_file: "butterworth2.json",
143 category: "Ehlers DSP",
144};
145
146pub const BUTTERWORTH3_METADATA: IndicatorMetadata = IndicatorMetadata {
147 name: "Butterworth3",
148 description: "3-pole Butterworth low-pass filter.",
149 usage: "Use to smooth price or intermediate indicator values with a flat passband and sharp rolloff. The 3-pole version provides steeper attenuation at the cost of marginally more lag.",
150 keywords: &["filter", "ehlers", "dsp", "smoothing", "low-pass"],
151 ehlers_summary: "Butterworth filters are maximally flat in the passband, introducing no ripple. Ehlers implements 2-pole and 3-pole Butterworth IIR designs in Cycle Analytics for Traders, noting that the SuperSmoother is actually a critically-damped 2-pole Butterworth variant.",
152 params: &[ParamDef {
153 name: "period",
154 default: "14",
155 description: "Critical period",
156 }],
157 formula_source: "https://github.com/lavs9/quantwave/blob/main/references/Ehlers%20Papers/Poles.pdf",
158 formula_latex: r#"
159\[
160a = \exp(-\pi/P)
161\]
162\[
163b = 2a \cos(1.738\pi/P)
164\]
165\[
166c = a^2
167\]
168\[
169f = (b+c)f_{t-1} - (c+bc)f_{t-2} + c^2f_{t-3} + \frac{(1-b+c)(1-c)}{8}(g + 3g_{t-1} + 3g_{t-2} + g_{t-3})
170\]
171"#,
172 gold_standard_file: "butterworth3.json",
173 category: "Ehlers DSP",
174};
175
176#[cfg(test)]
177mod tests {
178 use super::*;
179 use crate::traits::Next;
180 use proptest::prelude::*;
181
182 #[test]
183 fn test_butterworth_basic() {
184 let mut b2 = Butterworth2::new(14);
185 let mut b3 = Butterworth3::new(14);
186 for i in 0..20 {
187 let val = i as f64;
188 assert!(!b2.next(val).is_nan());
189 assert!(!b3.next(val).is_nan());
190 }
191 }
192
193 proptest! {
194 #[test]
195 fn test_butterworth2_parity(
196 inputs in prop::collection::vec(1.0..100.0, 10..100),
197 ) {
198 let p = 14;
199 let mut b2 = Butterworth2::new(p);
200 let streaming_results: Vec<f64> = inputs.iter().map(|&x| b2.next(x)).collect();
201
202 let mut batch_results = Vec::with_capacity(inputs.len());
204 let p_f = p as f64;
205 let a = (-1.414 * PI / p_f).exp();
206 let b = 2.0 * a * (1.414 * PI / p_f).cos();
207 let aa = a * a;
208 let c1 = (1.0 - b + aa) / 4.0;
209
210 let mut f_hist = [0.0; 2];
211 let mut g_hist = [0.0; 2];
212
213 for (i, &input) in inputs.iter().enumerate() {
214 let bar = i + 1;
215 let res = if bar < 3 {
216 input
217 } else {
218 b * f_hist[0] - aa * f_hist[1] + c1 * (input + 2.0 * g_hist[0] + g_hist[1])
219 };
220 f_hist[1] = f_hist[0];
221 f_hist[0] = res;
222 g_hist[1] = g_hist[0];
223 g_hist[0] = input;
224 batch_results.push(res);
225 }
226
227 for (s, b) in streaming_results.iter().zip(batch_results.iter()) {
228 approx::assert_relative_eq!(s, b, epsilon = 1e-10);
229 }
230 }
231
232 #[test]
233 fn test_butterworth3_parity(
234 inputs in prop::collection::vec(1.0..100.0, 10..100),
235 ) {
236 let p = 14;
237 let mut b3 = Butterworth3::new(p);
238 let streaming_results: Vec<f64> = inputs.iter().map(|&x| b3.next(x)).collect();
239
240 let mut batch_results = Vec::with_capacity(inputs.len());
242 let p_f = p as f64;
243 let a = (-PI / p_f).exp();
244 let b = 2.0 * a * (1.738 * PI / p_f).cos();
245 let c = a * a;
246 let bc = b * c;
247 let cc = c * c;
248 let c1 = (1.0 - b + c) * (1.0 - c) / 8.0;
249
250 let mut f_hist = [0.0; 3];
251 let mut g_hist = [0.0; 3];
252
253 for (i, &input) in inputs.iter().enumerate() {
254 let bar = i + 1;
255 let res = if bar < 4 {
256 input
257 } else {
258 (b + c) * f_hist[0] - (c + bc) * f_hist[1] + cc * f_hist[2]
259 + c1 * (input + 3.0 * g_hist[0] + 3.0 * g_hist[1] + g_hist[2])
260 };
261 f_hist[2] = f_hist[1];
262 f_hist[1] = f_hist[0];
263 f_hist[0] = res;
264 g_hist[2] = g_hist[1];
265 g_hist[1] = g_hist[0];
266 g_hist[0] = input;
267 batch_results.push(res);
268 }
269
270 for (s, b) in streaming_results.iter().zip(batch_results.iter()) {
271 approx::assert_relative_eq!(s, b, epsilon = 1e-10);
272 }
273 }
274 }
275}