nautilus_indicators/average/
ema.rs1use std::fmt::Display;
17
18use nautilus_model::{
19 data::{Bar, QuoteTick, TradeTick},
20 enums::PriceType,
21};
22
23use crate::indicator::{Indicator, MovingAverage};
24
25#[repr(C)]
26#[derive(Debug)]
27#[cfg_attr(
28 feature = "python",
29 pyo3::pyclass(module = "posei_trader.core.nautilus_pyo3.indicators")
30)]
31pub struct ExponentialMovingAverage {
32 pub period: usize,
33 pub price_type: PriceType,
34 pub alpha: f64,
35 pub value: f64,
36 pub count: usize,
37 pub initialized: bool,
38 has_inputs: bool,
39}
40
41impl Display for ExponentialMovingAverage {
42 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
43 write!(f, "{}({})", self.name(), self.period)
44 }
45}
46
47impl Indicator for ExponentialMovingAverage {
48 fn name(&self) -> String {
49 stringify!(ExponentialMovingAverage).to_string()
50 }
51
52 fn has_inputs(&self) -> bool {
53 self.has_inputs
54 }
55
56 fn initialized(&self) -> bool {
57 self.initialized
58 }
59
60 fn handle_quote(&mut self, quote: &QuoteTick) {
61 self.update_raw(quote.extract_price(self.price_type).into());
62 }
63
64 fn handle_trade(&mut self, trade: &TradeTick) {
65 self.update_raw((&trade.price).into());
66 }
67
68 fn handle_bar(&mut self, bar: &Bar) {
69 self.update_raw((&bar.close).into());
70 }
71
72 fn reset(&mut self) {
73 self.value = 0.0;
74 self.count = 0;
75 self.has_inputs = false;
76 self.initialized = false;
77 }
78}
79
80impl ExponentialMovingAverage {
81 #[must_use]
87 pub fn new(period: usize, price_type: Option<PriceType>) -> Self {
88 assert!(
89 period > 0,
90 "ExponentialMovingAverage::new → `period` must be positive (> 0); got {period}"
91 );
92 Self {
93 period,
94 price_type: price_type.unwrap_or(PriceType::Last),
95 alpha: 2.0 / (period as f64 + 1.0),
96 value: 0.0,
97 count: 0,
98 has_inputs: false,
99 initialized: false,
100 }
101 }
102}
103
104impl MovingAverage for ExponentialMovingAverage {
105 fn value(&self) -> f64 {
106 self.value
107 }
108
109 fn count(&self) -> usize {
110 self.count
111 }
112
113 fn update_raw(&mut self, value: f64) {
114 if !self.has_inputs {
115 self.has_inputs = true;
116 self.value = value;
117 self.count = 1;
118
119 if self.period == 1 {
120 self.initialized = true;
121 }
122 return;
123 }
124
125 self.value = self.alpha.mul_add(value, (1.0 - self.alpha) * self.value);
126 self.count += 1;
127
128 if !self.initialized && self.count >= self.period {
130 self.initialized = true;
131 }
132 }
133}
134
135#[cfg(test)]
139mod tests {
140 use nautilus_model::{
141 data::{Bar, QuoteTick, TradeTick},
142 enums::PriceType,
143 };
144 use rstest::rstest;
145
146 use crate::{
147 average::ema::ExponentialMovingAverage,
148 indicator::{Indicator, MovingAverage},
149 stubs::*,
150 };
151
152 #[rstest]
153 fn test_ema_initialized(indicator_ema_10: ExponentialMovingAverage) {
154 let ema = indicator_ema_10;
155 let display_str = format!("{ema}");
156 assert_eq!(display_str, "ExponentialMovingAverage(10)");
157 assert_eq!(ema.period, 10);
158 assert_eq!(ema.price_type, PriceType::Mid);
159 assert_eq!(ema.alpha, 0.181_818_181_818_181_82);
160 assert!(!ema.initialized);
161 }
162
163 #[rstest]
164 fn test_one_value_input(indicator_ema_10: ExponentialMovingAverage) {
165 let mut ema = indicator_ema_10;
166 ema.update_raw(1.0);
167 assert_eq!(ema.count, 1);
168 assert_eq!(ema.value, 1.0);
169 }
170
171 #[rstest]
172 fn test_ema_update_raw(indicator_ema_10: ExponentialMovingAverage) {
173 let mut ema = indicator_ema_10;
174 ema.update_raw(1.0);
175 ema.update_raw(2.0);
176 ema.update_raw(3.0);
177 ema.update_raw(4.0);
178 ema.update_raw(5.0);
179 ema.update_raw(6.0);
180 ema.update_raw(7.0);
181 ema.update_raw(8.0);
182 ema.update_raw(9.0);
183 ema.update_raw(10.0);
184
185 assert!(ema.has_inputs());
186 assert!(ema.initialized());
187 assert_eq!(ema.count, 10);
188 assert_eq!(ema.value, 6.239_368_480_121_215_5);
189 }
190
191 #[rstest]
192 fn test_reset(indicator_ema_10: ExponentialMovingAverage) {
193 let mut ema = indicator_ema_10;
194 ema.update_raw(1.0);
195 assert_eq!(ema.count, 1);
196 ema.reset();
197 assert_eq!(ema.count, 0);
198 assert_eq!(ema.value, 0.0);
199 assert!(!ema.initialized);
200 }
201
202 #[rstest]
203 fn test_handle_quote_tick_single(
204 indicator_ema_10: ExponentialMovingAverage,
205 stub_quote: QuoteTick,
206 ) {
207 let mut ema = indicator_ema_10;
208 ema.handle_quote(&stub_quote);
209 assert!(ema.has_inputs());
210 assert_eq!(ema.value, 1501.0);
211 }
212
213 #[rstest]
214 fn test_handle_quote_tick_multi(mut indicator_ema_10: ExponentialMovingAverage) {
215 let tick1 = stub_quote("1500.0", "1502.0");
216 let tick2 = stub_quote("1502.0", "1504.0");
217
218 indicator_ema_10.handle_quote(&tick1);
219 indicator_ema_10.handle_quote(&tick2);
220 assert_eq!(indicator_ema_10.count, 2);
221 assert_eq!(indicator_ema_10.value, 1_501.363_636_363_636_3);
222 }
223
224 #[rstest]
225 fn test_handle_trade_tick(indicator_ema_10: ExponentialMovingAverage, stub_trade: TradeTick) {
226 let mut ema = indicator_ema_10;
227 ema.handle_trade(&stub_trade);
228 assert!(ema.has_inputs());
229 assert_eq!(ema.value, 1500.0);
230 }
231
232 #[rstest]
233 fn handle_handle_bar(
234 mut indicator_ema_10: ExponentialMovingAverage,
235 bar_ethusdt_binance_minute_bid: Bar,
236 ) {
237 indicator_ema_10.handle_bar(&bar_ethusdt_binance_minute_bid);
238 assert!(indicator_ema_10.has_inputs);
239 assert!(!indicator_ema_10.initialized);
240 assert_eq!(indicator_ema_10.value, 1522.0);
241 }
242
243 #[rstest]
244 fn test_period_one_behaviour() {
245 let mut ema = ExponentialMovingAverage::new(1, None);
246 assert_eq!(ema.alpha, 1.0, "α must be 1 when period = 1");
247
248 ema.update_raw(10.0);
249 assert!(ema.initialized());
250 assert_eq!(ema.value(), 10.0);
251
252 ema.update_raw(42.0);
253 assert_eq!(
254 ema.value(),
255 42.0,
256 "With α = 1, the EMA must track the latest sample exactly"
257 );
258 }
259
260 #[rstest]
261 fn test_default_price_type_is_last() {
262 let ema = ExponentialMovingAverage::new(3, None);
263 assert_eq!(
264 ema.price_type,
265 PriceType::Last,
266 "`price_type` default mismatch"
267 );
268 }
269
270 #[rstest]
271 fn test_nan_poisoning_and_reset_recovery() {
272 let mut ema = ExponentialMovingAverage::new(4, None);
273 for x in 0..3 {
274 ema.update_raw(f64::from(x));
275 assert!(ema.value().is_finite());
276 }
277
278 ema.update_raw(f64::NAN);
279 assert!(ema.value().is_nan());
280
281 ema.update_raw(123.456);
282 assert!(ema.value().is_nan());
283
284 ema.reset();
285 assert!(!ema.has_inputs());
286 ema.update_raw(7.0);
287 assert_eq!(ema.value(), 7.0);
288 assert!(ema.value().is_finite());
289 }
290
291 #[rstest]
292 fn test_reset_without_inputs_is_safe() {
293 let mut ema = ExponentialMovingAverage::new(8, None);
294 ema.reset();
295 assert!(!ema.has_inputs());
296 assert_eq!(ema.count(), 0);
297 assert!(!ema.initialized());
298 }
299
300 #[rstest]
301 fn test_has_inputs_lifecycle() {
302 let mut ema = ExponentialMovingAverage::new(5, None);
303 assert!(!ema.has_inputs());
304
305 ema.update_raw(1.23);
306 assert!(ema.has_inputs());
307
308 ema.reset();
309 assert!(!ema.has_inputs());
310 }
311
312 #[rstest]
313 fn test_subnormal_inputs_do_not_underflow() {
314 let mut ema = ExponentialMovingAverage::new(2, None);
315 let tiny = f64::MIN_POSITIVE / 2.0;
316 ema.update_raw(tiny);
317 ema.update_raw(tiny);
318 assert!(
319 ema.value() > 0.0,
320 "Underflow: EMA value collapsed to zero for sub-normal inputs"
321 );
322 }
323}