wickra_core/indicators/
td_moving_average.rs1#![allow(clippy::doc_markdown)]
2
3use crate::error::{Error, Result};
6use crate::indicators::sma::Sma;
7use crate::ohlcv::Candle;
8use crate::traits::Indicator;
9
10#[derive(Debug, Clone, Copy, PartialEq)]
13pub struct TdMovingAverageOutput {
14 pub st1: f64,
16 pub st2: f64,
18}
19
20#[derive(Debug, Clone)]
53pub struct TdMovingAverage {
54 st1: Sma,
55 st2: Sma,
56 period_st1: usize,
57 period_st2: usize,
58 last: Option<TdMovingAverageOutput>,
59}
60
61impl TdMovingAverage {
62 pub fn new(period_st1: usize, period_st2: usize) -> Result<Self> {
69 if period_st1 == 0 || period_st2 == 0 {
70 return Err(Error::PeriodZero);
71 }
72 if period_st1 >= period_st2 {
73 return Err(Error::InvalidPeriod {
74 message: "TD moving average ST1 period must be strictly less than ST2",
75 });
76 }
77 Ok(Self {
78 st1: Sma::new(period_st1)?,
79 st2: Sma::new(period_st2)?,
80 period_st1,
81 period_st2,
82 last: None,
83 })
84 }
85
86 pub const fn periods(&self) -> (usize, usize) {
88 (self.period_st1, self.period_st2)
89 }
90
91 pub const fn value(&self) -> Option<TdMovingAverageOutput> {
93 self.last
94 }
95}
96
97impl Indicator for TdMovingAverage {
98 type Input = Candle;
99 type Output = TdMovingAverageOutput;
100
101 #[inline]
102 fn update(&mut self, candle: Candle) -> Option<TdMovingAverageOutput> {
103 let price = candle.median_price();
104 let fast = self.st1.update(price);
105 let slow = self.st2.update(price);
106 if let (Some(st1), Some(st2)) = (fast, slow) {
107 let out = TdMovingAverageOutput { st1, st2 };
108 self.last = Some(out);
109 return Some(out);
110 }
111 None
112 }
113
114 fn reset(&mut self) {
115 self.st1.reset();
116 self.st2.reset();
117 self.last = None;
118 }
119
120 #[inline]
121 fn warmup_period(&self) -> usize {
122 self.period_st2
123 }
124
125 #[inline]
126 fn is_ready(&self) -> bool {
127 self.last.is_some()
128 }
129
130 #[inline]
131 fn name(&self) -> &'static str {
132 "TDMovingAverage"
133 }
134}
135
136#[cfg(test)]
137mod tests {
138 use super::*;
139 use crate::traits::BatchExt;
140 use approx::assert_relative_eq;
141
142 fn c(median: f64) -> Candle {
143 Candle::new_unchecked(median, median + 1.0, median - 1.0, median, 1_000.0, 0)
144 }
145
146 #[test]
147 fn rejects_invalid_periods() {
148 assert!(matches!(
149 TdMovingAverage::new(0, 13),
150 Err(Error::PeriodZero)
151 ));
152 assert!(matches!(
153 TdMovingAverage::new(13, 5),
154 Err(Error::InvalidPeriod { .. })
155 ));
156 assert!(matches!(
157 TdMovingAverage::new(5, 5),
158 Err(Error::InvalidPeriod { .. })
159 ));
160 }
161
162 #[test]
163 fn accessors_and_metadata() {
164 let td = TdMovingAverage::new(5, 13).unwrap();
165 assert_eq!(td.periods(), (5, 13));
166 assert_eq!(td.warmup_period(), 13);
167 assert_eq!(td.name(), "TDMovingAverage");
168 assert!(!td.is_ready());
169 assert_eq!(td.value(), None);
170 }
171
172 #[test]
173 fn first_emission_at_warmup_period() {
174 let mut td = TdMovingAverage::new(2, 4).unwrap();
175 let candles: Vec<Candle> = (0..8).map(|i| c(100.0 + f64::from(i))).collect();
176 let out = td.batch(&candles);
177 for v in out.iter().take(3) {
178 assert!(v.is_none());
179 }
180 assert!(out[3].is_some());
181 }
182
183 #[test]
184 fn fast_leads_slow_in_uptrend() {
185 let mut td = TdMovingAverage::new(3, 7).unwrap();
186 let candles: Vec<Candle> = (0..40).map(|i| c(100.0 + f64::from(i))).collect();
187 let out = td.batch(&candles).into_iter().flatten().last().unwrap();
188 assert!(out.st1 > out.st2, "fast MA should lead in an uptrend");
189 }
190
191 #[test]
192 fn fast_below_slow_in_downtrend() {
193 let mut td = TdMovingAverage::new(3, 7).unwrap();
194 let candles: Vec<Candle> = (0..40).map(|i| c(200.0 - f64::from(i))).collect();
195 let out = td.batch(&candles).into_iter().flatten().last().unwrap();
196 assert!(out.st1 < out.st2, "fast MA should trail in a downtrend");
197 }
198
199 #[test]
200 fn flat_series_equal_lines() {
201 let mut td = TdMovingAverage::new(2, 4).unwrap();
202 let out = td
203 .batch(&[c(50.0); 10])
204 .into_iter()
205 .flatten()
206 .last()
207 .unwrap();
208 assert_relative_eq!(out.st1, 50.0, epsilon = 1e-9);
209 assert_relative_eq!(out.st2, 50.0, epsilon = 1e-9);
210 }
211
212 #[test]
213 fn reset_clears_state() {
214 let mut td = TdMovingAverage::new(2, 4).unwrap();
215 td.batch(&(0..10).map(|i| c(100.0 + f64::from(i))).collect::<Vec<_>>());
216 assert!(td.is_ready());
217 td.reset();
218 assert!(!td.is_ready());
219 assert_eq!(td.value(), None);
220 assert_eq!(td.update(c(100.0)), None);
221 }
222
223 #[test]
224 fn batch_equals_streaming() {
225 let candles: Vec<Candle> = (0..80)
226 .map(|i| c(100.0 + (f64::from(i) * 0.25).sin() * 9.0))
227 .collect();
228 let batch = TdMovingAverage::new(5, 13).unwrap().batch(&candles);
229 let mut b = TdMovingAverage::new(5, 13).unwrap();
230 let streamed: Vec<_> = candles.iter().map(|x| b.update(*x)).collect();
231 assert_eq!(batch, streamed);
232 }
233}