Skip to main content

wickra_core/indicators/
tema.rs

1//! Triple Exponential Moving Average (TEMA).
2
3use crate::error::Result;
4use crate::indicators::ema::Ema;
5use crate::traits::Indicator;
6
7/// Triple Exponential Moving Average: `3 * EMA1 - 3 * EMA2 + EMA3`,
8/// where `EMA2 = EMA(EMA1)` and `EMA3 = EMA(EMA2)`.
9///
10/// Reduces lag further than DEMA at the cost of more responsiveness to noise.
11///
12/// # Example
13///
14/// ```
15/// use wickra_core::{Indicator, Tema};
16///
17/// let mut indicator = Tema::new(3).unwrap();
18/// let mut last = None;
19/// for i in 0..80 {
20///     last = indicator.update(100.0 + f64::from(i));
21/// }
22/// assert!(last.is_some());
23/// ```
24#[derive(Debug, Clone)]
25pub struct Tema {
26    ema1: Ema,
27    ema2: Ema,
28    ema3: Ema,
29    period: usize,
30}
31
32impl Tema {
33    /// # Errors
34    /// Returns [`crate::Error::PeriodZero`] if `period == 0`.
35    pub fn new(period: usize) -> Result<Self> {
36        Ok(Self {
37            ema1: Ema::new(period)?,
38            ema2: Ema::new(period)?,
39            ema3: Ema::new(period)?,
40            period,
41        })
42    }
43
44    /// Configured period.
45    pub const fn period(&self) -> usize {
46        self.period
47    }
48}
49
50impl Indicator for Tema {
51    type Input = f64;
52    type Output = f64;
53
54    #[inline]
55    fn update(&mut self, input: f64) -> Option<f64> {
56        let e1 = self.ema1.update(input)?;
57        let e2 = self.ema2.update(e1)?;
58        let e3 = self.ema3.update(e2)?;
59        Some(3.0 * e1 - 3.0 * e2 + e3)
60    }
61
62    fn reset(&mut self) {
63        self.ema1.reset();
64        self.ema2.reset();
65        self.ema3.reset();
66    }
67
68    #[inline]
69    fn warmup_period(&self) -> usize {
70        3 * self.period - 2
71    }
72
73    #[inline]
74    fn is_ready(&self) -> bool {
75        self.ema3.is_ready()
76    }
77
78    #[inline]
79    fn name(&self) -> &'static str {
80        "TEMA"
81    }
82}
83
84#[cfg(test)]
85mod tests {
86    use super::*;
87    use crate::traits::BatchExt;
88    use approx::assert_relative_eq;
89
90    #[test]
91    fn constant_series_yields_constant_tema() {
92        let mut tema = Tema::new(5).unwrap();
93        let out = tema.batch(&[42.0_f64; 80]);
94        let last = out.iter().rev().flatten().next().unwrap();
95        assert_relative_eq!(*last, 42.0, epsilon = 1e-9);
96    }
97
98    #[test]
99    fn batch_equals_streaming() {
100        let prices: Vec<f64> = (1..=80)
101            .map(|i| (f64::from(i) * 0.3).sin() * 10.0)
102            .collect();
103        let mut a = Tema::new(5).unwrap();
104        let mut b = Tema::new(5).unwrap();
105        assert_eq!(
106            a.batch(&prices),
107            prices.iter().map(|p| b.update(*p)).collect::<Vec<_>>()
108        );
109    }
110
111    #[test]
112    fn reset_clears_state() {
113        let mut tema = Tema::new(5).unwrap();
114        tema.batch(&(1..=80).map(f64::from).collect::<Vec<_>>());
115        assert!(tema.is_ready());
116        tema.reset();
117        assert!(!tema.is_ready());
118    }
119
120    #[test]
121    fn rejects_zero_period() {
122        assert!(Tema::new(0).is_err());
123    }
124
125    /// Cover the const accessor `period` (45-47) and the Indicator-impl
126    /// `warmup_period` (67-69) + `name` (75-77). Existing tests inspect
127    /// TEMA output but never query the metadata.
128    #[test]
129    fn accessors_and_metadata() {
130        let tema = Tema::new(5).unwrap();
131        assert_eq!(tema.period(), 5);
132        // EMA1 seeds at period (5), each cascade stage needs another (period-1) inputs.
133        assert_eq!(tema.warmup_period(), 3 * 5 - 2);
134        assert_eq!(tema.name(), "TEMA");
135    }
136}