Skip to main content

wickra_core/indicators/
cybernetic_cycle.rs

1//! Ehlers Cybernetic Cycle Component.
2#![allow(clippy::doc_markdown)]
3
4use crate::error::{Error, Result};
5use crate::traits::Indicator;
6
7/// Ehlers' Cybernetic Cycle Component (CCC).
8///
9/// Classic EasyLanguage construct from *Cybernetic Analysis for Stocks and
10/// Futures* (Ehlers 2004, ch. 4):
11///
12/// ```text
13/// smooth[t] = (x[t] + 2*x[t-1] + 2*x[t-2] + x[t-3]) / 6
14/// cycle[t]  = (1 - alpha/2)^2 * (smooth[t] - 2*smooth[t-1] + smooth[t-2])
15///           + 2 * (1 - alpha) * cycle[t-1]
16///           - (1 - alpha)^2 * cycle[t-2]
17/// ```
18///
19/// The result is a near-zero-mean oscillator that tracks the dominant cycle
20/// component while filtering trend. `alpha` is a smoothing fraction in
21/// `(0, 1]`; Ehlers recommends `2 / (period + 1)` for a given critical period.
22///
23/// The first six outputs follow Ehlers' "use the input directly" initial
24/// condition so downstream consumers stay reactive.
25///
26/// # Example
27///
28/// ```
29/// use wickra_core::{Indicator, CyberneticCycle};
30///
31/// let mut cc = CyberneticCycle::new(10).unwrap();
32/// let mut last = None;
33/// for i in 0..30 {
34///     last = cc.update(100.0 + (f64::from(i) * 0.3).sin() * 5.0);
35/// }
36/// assert!(last.is_some());
37/// ```
38#[derive(Debug, Clone)]
39pub struct CyberneticCycle {
40    period: usize,
41    alpha: f64,
42    in_buf: [Option<f64>; 4],
43    smooth_buf: [Option<f64>; 3],
44    cycle_buf: [Option<f64>; 3],
45    count: usize,
46    last_value: Option<f64>,
47}
48
49impl CyberneticCycle {
50    /// Construct with the dominant-cycle period (alpha = 2 / (period + 1)).
51    ///
52    /// # Errors
53    ///
54    /// Returns [`Error::PeriodZero`] if `period == 0`.
55    pub fn new(period: usize) -> Result<Self> {
56        if period == 0 {
57            return Err(Error::PeriodZero);
58        }
59        if period > crate::error::MAX_PERIOD {
60            return Err(Error::InvalidPeriod {
61                message: crate::error::PERIOD_ABOVE_MAX,
62            });
63        }
64        let alpha = 2.0 / (period as f64 + 1.0);
65        Ok(Self {
66            period,
67            alpha,
68            in_buf: [None; 4],
69            smooth_buf: [None; 3],
70            cycle_buf: [None; 3],
71            count: 0,
72            last_value: None,
73        })
74    }
75
76    /// Configured period.
77    pub const fn period(&self) -> usize {
78        self.period
79    }
80
81    /// Smoothing alpha.
82    pub const fn alpha(&self) -> f64 {
83        self.alpha
84    }
85
86    /// Current value if available.
87    pub const fn value(&self) -> Option<f64> {
88        self.last_value
89    }
90
91    /// Shift in `x` at position 0 of a 3-slot buffer.
92    fn push3(buf: &mut [Option<f64>; 3], x: f64) {
93        buf[2] = buf[1];
94        buf[1] = buf[0];
95        buf[0] = Some(x);
96    }
97    fn push4(buf: &mut [Option<f64>; 4], x: f64) {
98        buf[3] = buf[2];
99        buf[2] = buf[1];
100        buf[1] = buf[0];
101        buf[0] = Some(x);
102    }
103}
104
105impl Indicator for CyberneticCycle {
106    type Input = f64;
107    type Output = f64;
108
109    fn update(&mut self, input: f64) -> Option<f64> {
110        if !input.is_finite() {
111            return None;
112        }
113        self.count += 1;
114        Self::push4(&mut self.in_buf, input);
115
116        // Smooth needs four prior inputs (positions 0..=3).
117        let smooth = if let (Some(a), Some(b), Some(c), Some(d)) = (
118            self.in_buf[0],
119            self.in_buf[1],
120            self.in_buf[2],
121            self.in_buf[3],
122        ) {
123            (a + 2.0 * b + 2.0 * c + d) / 6.0
124        } else {
125            // Initial condition: use the raw input.
126            input
127        };
128        Self::push3(&mut self.smooth_buf, smooth);
129
130        // Cycle needs two prior smooths and two prior cycles.
131        let one_minus_half_alpha = 1.0 - self.alpha / 2.0;
132        let one_minus_alpha = 1.0 - self.alpha;
133        let drv = one_minus_half_alpha * one_minus_half_alpha;
134
135        // The 3-slot `smooth_buf` and `cycle_buf` ring buffers fill within a
136        // few updates, so the pattern match only fails during warmup. The
137        // `else` branch is therefore the Ehlers initial condition: the
138        // second-difference of the raw input series, scaled by 0.5 — matches
139        // the EasyLanguage implementation's first-bar fallback.
140        let cycle = if let (Some(s0), Some(s1), Some(s2), Some(c1), Some(c2)) = (
141            self.smooth_buf[0],
142            self.smooth_buf[1],
143            self.smooth_buf[2],
144            self.cycle_buf[0],
145            self.cycle_buf[1],
146        ) {
147            drv * (s0 - 2.0 * s1 + s2) + 2.0 * one_minus_alpha * c1
148                - one_minus_alpha * one_minus_alpha * c2
149        } else {
150            let (x0, x1, x2) = (
151                self.in_buf[0].unwrap_or(input),
152                self.in_buf[1].unwrap_or(input),
153                self.in_buf[2].unwrap_or(input),
154            );
155            (x0 - 2.0 * x1 + x2) / 4.0
156        };
157
158        Self::push3(&mut self.cycle_buf, cycle);
159        self.last_value = Some(cycle);
160        Some(cycle)
161    }
162
163    fn reset(&mut self) {
164        self.in_buf = [None; 4];
165        self.smooth_buf = [None; 3];
166        self.cycle_buf = [None; 3];
167        self.count = 0;
168        self.last_value = None;
169    }
170
171    #[inline]
172    fn warmup_period(&self) -> usize {
173        1
174    }
175
176    #[inline]
177    fn is_ready(&self) -> bool {
178        self.last_value.is_some()
179    }
180
181    #[inline]
182    fn name(&self) -> &'static str {
183        "CyberneticCycle"
184    }
185}
186
187#[cfg(test)]
188mod tests {
189    use super::*;
190    use crate::traits::BatchExt;
191    use approx::assert_relative_eq;
192
193    #[test]
194    fn new_rejects_zero_period() {
195        assert!(matches!(CyberneticCycle::new(0), Err(Error::PeriodZero)));
196    }
197
198    #[test]
199    fn accessors_and_metadata() {
200        let mut cc = CyberneticCycle::new(10).unwrap();
201        assert_eq!(cc.period(), 10);
202        assert_relative_eq!(cc.alpha(), 2.0 / 11.0, epsilon = 1e-15);
203        assert_eq!(cc.warmup_period(), 1);
204        assert_eq!(cc.name(), "CyberneticCycle");
205        assert!(!cc.is_ready());
206        cc.update(100.0);
207        assert!(cc.is_ready());
208    }
209
210    #[test]
211    fn constant_series_converges_to_zero() {
212        let mut cc = CyberneticCycle::new(10).unwrap();
213        let out = cc.batch(&[50.0_f64; 200]);
214        for x in out.iter().skip(50).flatten() {
215            assert_relative_eq!(*x, 0.0, epsilon = 1e-9);
216        }
217    }
218
219    #[test]
220    fn batch_equals_streaming() {
221        let prices: Vec<f64> = (0..120)
222            .map(|i| 100.0 + (f64::from(i) * 0.25).sin() * 5.0)
223            .collect();
224        let mut a = CyberneticCycle::new(15).unwrap();
225        let mut b = CyberneticCycle::new(15).unwrap();
226        let batch = a.batch(&prices);
227        let streamed: Vec<_> = prices.iter().map(|p| b.update(*p)).collect();
228        assert_eq!(batch, streamed);
229    }
230
231    #[test]
232    fn ignores_non_finite_input() {
233        let mut cc = CyberneticCycle::new(10).unwrap();
234        cc.batch(&(1..=30).map(f64::from).collect::<Vec<_>>());
235        let before = cc.value();
236        assert!(before.is_some());
237        assert_eq!(cc.update(f64::NAN), None);
238    }
239
240    #[test]
241    fn reset_clears_state() {
242        let mut cc = CyberneticCycle::new(10).unwrap();
243        cc.batch(&(1..=30).map(f64::from).collect::<Vec<_>>());
244        assert!(cc.is_ready());
245        cc.reset();
246        assert!(!cc.is_ready());
247    }
248}