Skip to main content

wickra_core/indicators/
vidya.rs

1//! Variable Index Dynamic Average (VIDYA).
2
3use crate::error::{Error, Result};
4use crate::indicators::cmo::Cmo;
5use crate::traits::Indicator;
6
7/// Tushar Chande's Variable Index Dynamic Average — an EMA whose smoothing
8/// factor is scaled by the absolute Chande Momentum Oscillator (`CMO`).
9///
10/// Strong directional momentum (high `|CMO|`) pushes the effective smoothing
11/// constant toward the EMA-of-`period`'s natural rate; flat / choppy windows
12/// (`|CMO|` close to zero) shrink it toward zero so VIDYA coasts on its prior
13/// value:
14///
15/// ```text
16/// alpha_base = 2 / (period + 1)
17/// alpha_t    = alpha_base * |CMO(cmo_period)| / 100
18/// VIDYA_t    = alpha_t * price_t + (1 - alpha_t) * VIDYA_{t-1}
19/// ```
20///
21/// The series is seeded with the first price emitted after the `CMO`
22/// warm-up (i.e. after `cmo_period + 1` inputs).
23///
24/// Reference: Tushar Chande, *Stocks & Commodities*, 1992.
25///
26/// # Example
27///
28/// ```
29/// use wickra_core::{Indicator, Vidya};
30///
31/// let mut vidya = Vidya::new(14, 9).unwrap();
32/// let mut last = None;
33/// for i in 0..80 {
34///     last = vidya.update(100.0 + f64::from(i));
35/// }
36/// assert!(last.is_some());
37/// ```
38#[derive(Debug, Clone)]
39pub struct Vidya {
40    period: usize,
41    cmo_period: usize,
42    alpha_base: f64,
43    cmo: Cmo,
44    current: Option<f64>,
45}
46
47impl Vidya {
48    /// # Errors
49    /// Returns [`Error::PeriodZero`] if either period is zero.
50    pub fn new(period: usize, cmo_period: usize) -> Result<Self> {
51        if period == 0 || cmo_period == 0 {
52            return Err(Error::PeriodZero);
53        }
54        let alpha_base = 2.0 / (period as f64 + 1.0);
55        Ok(Self {
56            period,
57            cmo_period,
58            alpha_base,
59            cmo: Cmo::new(cmo_period)?,
60            current: None,
61        })
62    }
63
64    /// Configured `(period, cmo_period)`.
65    pub const fn periods(&self) -> (usize, usize) {
66        (self.period, self.cmo_period)
67    }
68}
69
70impl Indicator for Vidya {
71    type Input = f64;
72    type Output = f64;
73
74    #[inline]
75    fn update(&mut self, input: f64) -> Option<f64> {
76        if !input.is_finite() {
77            return None;
78        }
79        let cmo = self.cmo.update(input)?;
80        let alpha = self.alpha_base * (cmo.abs() / 100.0);
81        let prev = self.current.unwrap_or(input);
82        let next = alpha * input + (1.0 - alpha) * prev;
83        self.current = Some(next);
84        Some(next)
85    }
86
87    fn reset(&mut self) {
88        self.cmo.reset();
89        self.current = None;
90    }
91
92    #[inline]
93    fn warmup_period(&self) -> usize {
94        self.cmo_period + 1
95    }
96
97    #[inline]
98    fn is_ready(&self) -> bool {
99        self.current.is_some()
100    }
101
102    #[inline]
103    fn name(&self) -> &'static str {
104        "VIDYA"
105    }
106}
107
108#[cfg(test)]
109mod tests {
110    use super::*;
111    use crate::traits::BatchExt;
112    use approx::assert_relative_eq;
113
114    #[test]
115    fn rejects_zero_period() {
116        assert!(matches!(Vidya::new(0, 9), Err(Error::PeriodZero)));
117        assert!(matches!(Vidya::new(14, 0), Err(Error::PeriodZero)));
118    }
119
120    #[test]
121    fn accessors_and_metadata() {
122        let v = Vidya::new(14, 9).unwrap();
123        assert_eq!(v.periods(), (14, 9));
124        assert_eq!(v.warmup_period(), 10);
125        assert_eq!(v.name(), "VIDYA");
126    }
127
128    #[test]
129    fn constant_series_yields_the_constant() {
130        // Flat input -> CMO = 0 -> alpha = 0 -> VIDYA holds its seed value.
131        let mut v = Vidya::new(14, 4).unwrap();
132        let out = v.batch(&[42.0_f64; 30]);
133        for x in out.iter().skip(4).flatten() {
134            assert_relative_eq!(*x, 42.0, epsilon = 1e-12);
135        }
136    }
137
138    #[test]
139    fn pure_uptrend_alpha_equals_base() {
140        // Monotonic uptrend: CMO saturates at +100, so alpha = alpha_base.
141        // After warmup the recurrence is a plain EMA with that alpha; once
142        // the series is long enough VIDYA closely tracks the latest input.
143        let mut v = Vidya::new(2, 4).unwrap();
144        let prices: Vec<f64> = (1..=40).map(f64::from).collect();
145        let out = v.batch(&prices);
146        let last = out.last().unwrap().unwrap();
147        let latest = *prices.last().unwrap();
148        // alpha_base = 2/3, EMA(2) tracks close — last value is within 2 of
149        // the latest input after this many bars.
150        assert!(
151            (latest - last).abs() < 2.0,
152            "VIDYA should track close on a clean uptrend: {last} vs {latest}"
153        );
154    }
155
156    #[test]
157    fn warmup_emits_first_value_at_cmo_period_plus_one() {
158        let mut v = Vidya::new(14, 3).unwrap();
159        assert_eq!(v.warmup_period(), 4);
160        assert_eq!(v.update(10.0), None);
161        assert_eq!(v.update(11.0), None);
162        assert_eq!(v.update(12.0), None);
163        assert!(v.update(13.0).is_some());
164    }
165
166    #[test]
167    fn batch_equals_streaming() {
168        let prices: Vec<f64> = (1..=60)
169            .map(|i| 100.0 + (f64::from(i) * 0.2).sin() * 5.0)
170            .collect();
171        let mut a = Vidya::new(14, 9).unwrap();
172        let mut b = Vidya::new(14, 9).unwrap();
173        assert_eq!(
174            a.batch(&prices),
175            prices.iter().map(|p| b.update(*p)).collect::<Vec<_>>()
176        );
177    }
178
179    #[test]
180    fn reset_clears_state() {
181        let mut v = Vidya::new(14, 9).unwrap();
182        v.batch(&(1..=40).map(f64::from).collect::<Vec<_>>());
183        assert!(v.is_ready());
184        v.reset();
185        assert!(!v.is_ready());
186        assert_eq!(v.update(1.0), None);
187    }
188
189    #[test]
190    fn ignores_non_finite_input() {
191        let mut v = Vidya::new(14, 4).unwrap();
192        v.batch(&(1..=20).map(f64::from).collect::<Vec<_>>());
193        v.update(21.0).unwrap();
194        assert_eq!(v.update(f64::NAN), None);
195        assert_eq!(v.update(f64::INFINITY), None);
196    }
197}