Skip to main content

quantwave_core/indicators/
cycle_trend_analytics.rs

1use crate::indicators::metadata::{IndicatorMetadata, ParamDef};
2use crate::indicators::smoothing::SMA;
3use crate::traits::Next;
4
5/// Cycle/Trend Analytics Indicator
6///
7/// Based on John Ehlers' "Cycle/Trend Analytics And The MAD Indicator" (2021).
8/// It computes a series of oscillators: Price - SMA(Price, Length) for Length 5 to 30.
9#[derive(Debug, Clone)]
10pub struct CycleTrendAnalytics {
11    smas: Vec<SMA>,
12}
13
14impl CycleTrendAnalytics {
15    pub fn new(min_length: usize, max_length: usize) -> Self {
16        let smas = (min_length..=max_length).map(SMA::new).collect();
17        Self {
18            smas,
19        }
20    }
21}
22
23impl Next<f64> for CycleTrendAnalytics {
24    type Output = Vec<f64>; // Price - SMA for each length from min to max
25
26    fn next(&mut self, input: f64) -> Self::Output {
27        self.smas.iter_mut().map(|sma| input - sma.next(input)).collect()
28    }
29}
30
31pub const CYCLE_TREND_ANALYTICS_METADATA: IndicatorMetadata = IndicatorMetadata {
32    name: "Cycle/Trend Analytics",
33    description: "A set of oscillators (Price - SMA) with lengths from 5 to 30 used to visualize cycles and trends.",
34    usage: "Use to classify the current market mode as trending or cycling before selecting your strategy. Apply trend-following systems in trend mode and mean-reversion systems in cycle mode.",
35    keywords: &["cycle", "trend", "ehlers", "classification", "adaptive"],
36    ehlers_summary: "Ehlers presents Cycle/Trend Analytics in Cycle Analytics for Traders as a framework for determining the dominant market mode. By measuring the correlation between price and the best-fit dominant cycle, the indicator classifies market behavior, enabling traders to switch between trend and cycle trading strategies dynamically.",
37    params: &[
38        ParamDef {
39            name: "min_length",
40            default: "5",
41            description: "Minimum SMA length",
42        },
43        ParamDef {
44            name: "max_length",
45            default: "30",
46            description: "Maximum SMA length",
47        },
48    ],
49    formula_source: "https://github.com/lavs9/quantwave/blob/main/references/traderstipsreference/TRADERS’ TIPS - OCTOBER 2021.html",
50    formula_latex: r#"
51\[
52Osc(L) = Price - SMA(Price, L) \quad \text{for } L \in [min, max]
53\]
54"#,
55    gold_standard_file: "cycle_trend_analytics.json",
56    category: "Ehlers DSP",
57};
58
59#[cfg(test)]
60mod tests {
61    use super::*;
62    use crate::traits::Next;
63    use crate::test_utils::{load_gold_standard_vec, assert_indicator_parity_vec};
64    use proptest::prelude::*;
65
66    #[test]
67    fn test_cycle_trend_analytics_gold_standard() {
68        let case = load_gold_standard_vec("cycle_trend_analytics");
69        let cta = CycleTrendAnalytics::new(5, 15);
70        assert_indicator_parity_vec(cta, &case.input, &case.expected);
71    }
72
73    #[test]
74    fn test_cycle_trend_analytics_basic() {
75        let mut cta = CycleTrendAnalytics::new(5, 10);
76        let inputs = vec![10.0, 11.0, 12.0, 13.0, 14.0, 15.0];
77        for input in inputs {
78            let res = cta.next(input);
79            assert_eq!(res.len(), 6);
80        }
81    }
82
83    proptest! {
84        #[test]
85        fn test_cycle_trend_analytics_parity(
86            inputs in prop::collection::vec(1.0..100.0, 30..100),
87        ) {
88            let min = 5;
89            let max = 15;
90            let mut cta = CycleTrendAnalytics::new(min, max);
91            let streaming_results: Vec<Vec<f64>> = inputs.iter().map(|&x| cta.next(x)).collect();
92
93            // Batch implementation
94            let mut batch_results = Vec::with_capacity(inputs.len());
95            for i in 0..inputs.len() {
96                let mut bar_results = Vec::with_capacity(max - min + 1);
97                for length in min..=max {
98                    let sum: f64 = inputs[(i.saturating_sub(length - 1))..=i].iter().sum();
99                    let count = (i + 1).min(length);
100                    let sma = sum / count as f64;
101                    bar_results.push(inputs[i] - sma);
102                }
103                batch_results.push(bar_results);
104            }
105
106            for (s, b) in streaming_results.iter().zip(batch_results.iter()) {
107                for (sv, bv) in s.iter().zip(b.iter()) {
108                    approx::assert_relative_eq!(sv, bv, epsilon = 1e-10);
109                }
110            }
111        }
112    }
113}