Skip to main content

quantwave_core/indicators/
ultimate_bands.rs

1use crate::indicators::metadata::{IndicatorMetadata, ParamDef};
2use crate::indicators::ultimate_smoother::UltimateSmoother;
3use crate::traits::Next;
4use std::collections::VecDeque;
5
6/// Ultimate Bands
7///
8/// Based on John Ehlers' "Ultimate Channel and Ultimate Bands" (S&C 2024).
9/// Replaces the SMA in Bollinger Bands with UltimateSmoother and calculates
10/// Standard Deviation relative to the smoothed center line.
11#[derive(Debug, Clone)]
12pub struct UltimateBands {
13    smoother: UltimateSmoother,
14    num_sds: f64,
15    length: usize,
16    diff_sq_history: VecDeque<f64>,
17    sum_diff_sq: f64,
18}
19
20impl UltimateBands {
21    pub fn new(length: usize, num_sds: f64) -> Self {
22        Self {
23            smoother: UltimateSmoother::new(length),
24            num_sds,
25            length,
26            diff_sq_history: VecDeque::with_capacity(length),
27            sum_diff_sq: 0.0,
28        }
29    }
30}
31
32impl Next<f64> for UltimateBands {
33    type Output = (f64, f64, f64); // (Upper, Center, Lower)
34
35    fn next(&mut self, input: f64) -> Self::Output {
36        let center = self.smoother.next(input);
37
38        let diff = input - center;
39        let diff_sq = diff * diff;
40
41        self.sum_diff_sq += diff_sq;
42        self.diff_sq_history.push_back(diff_sq);
43
44        if self.diff_sq_history.len() > self.length && let Some(old) = self.diff_sq_history.pop_front() {
45            self.sum_diff_sq -= old;
46        }
47
48        let sd = if self.sum_diff_sq > 0.0 {
49            (self.sum_diff_sq / self.diff_sq_history.len() as f64).sqrt()
50        } else {
51            0.0
52        };
53
54        let upper = center + self.num_sds * sd;
55        let lower = center - self.num_sds * sd;
56
57        (upper, center, lower)
58    }
59}
60
61pub const ULTIMATE_BANDS_METADATA: IndicatorMetadata = IndicatorMetadata {
62    name: "Ultimate Bands",
63    description: "A Bollinger-style band using UltimateSmoother for the center line and standard deviation of the price-smooth difference for width.",
64    usage: "Use as volatility bands that automatically widen during high-energy cycle phases and narrow during quiet phases. Better than fixed-multiple ATR bands in strongly cyclical markets.",
65    keywords: &["bands", "volatility", "ehlers", "dsp", "adaptive"],
66    ehlers_summary: "Ehlers Ultimate Bands compute upper and lower price envelopes using the RMS amplitude of the dominant cycle rather than a fixed ATR multiple. This makes the bands proportional to the current cycle energy, expanding when the market is actively cycling and contracting when it enters a low-energy consolidation.",
67    params: &[
68        ParamDef {
69            name: "length",
70            default: "20",
71            description: "Smoothing and SD period",
72        },
73        ParamDef {
74            name: "num_sds",
75            default: "1.0",
76            description: "Standard Deviation multiplier",
77        },
78    ],
79    formula_source: "https://github.com/lavs9/quantwave/blob/main/references/Ehlers%20Papers/UltimateChannel.pdf",
80    formula_latex: r#"
81\[
82Smooth = UltimateSmoother(Close, Length)
83\]
84\[
85SD = \sqrt{\frac{1}{n}\sum_{i=0}^{n-1} (Close_{t-i} - Smooth_{t-i})^2}
86\]
87\[
88Upper = Smooth + NumSDs \times SD
89\]
90\[
91Lower = Smooth - NumSDs \times SD
92\]
93"#,
94    gold_standard_file: "ultimate_bands.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_ultimate_bands_basic() {
106        let mut ub = UltimateBands::new(20, 1.0);
107        let inputs = vec![10.0, 11.0, 12.0, 11.0, 10.0];
108        for input in inputs {
109            let (u, c, l) = ub.next(input);
110            assert!(!u.is_nan());
111            assert!(!c.is_nan());
112            assert!(!l.is_nan());
113        }
114    }
115
116    proptest! {
117        #[test]
118        fn test_ultimate_bands_parity(
119            inputs in prop::collection::vec(1.0..100.0, 30..100),
120        ) {
121            let length = 20;
122            let num_sds = 1.0;
123            let mut ub = UltimateBands::new(length, num_sds);
124            let streaming_results: Vec<(f64, f64, f64)> = inputs.iter().map(|&x| ub.next(x)).collect();
125
126            // Reference implementation
127            let mut sm = UltimateSmoother::new(length);
128            let mut diff_sqs = Vec::with_capacity(inputs.len());
129            let mut batch_results = Vec::with_capacity(inputs.len());
130
131            for &input in &inputs {
132                let center = sm.next(input);
133                let diff = input - center;
134                diff_sqs.push(diff * diff);
135
136                let start = if diff_sqs.len() > length { diff_sqs.len() - length } else { 0 };
137                let window = &diff_sqs[start..];
138                let sd = (window.iter().sum::<f64>() / window.len() as f64).sqrt();
139
140                batch_results.push((center + num_sds * sd, center, center - num_sds * sd));
141            }
142
143            for (s, b) in streaming_results.iter().zip(batch_results.iter()) {
144                approx::assert_relative_eq!(s.0, b.0, epsilon = 1e-10);
145                approx::assert_relative_eq!(s.1, b.1, epsilon = 1e-10);
146                approx::assert_relative_eq!(s.2, b.2, epsilon = 1e-10);
147            }
148        }
149    }
150}