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 = "nautilus_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)]
136mod tests {
137 use nautilus_model::{
138 data::{Bar, QuoteTick, TradeTick},
139 enums::PriceType,
140 };
141 use rstest::rstest;
142
143 use crate::{
144 average::ema::ExponentialMovingAverage,
145 indicator::{Indicator, MovingAverage},
146 stubs::*,
147 };
148
149 #[rstest]
150 fn test_ema_initialized(indicator_ema_10: ExponentialMovingAverage) {
151 let ema = indicator_ema_10;
152 let display_str = format!("{ema}");
153 assert_eq!(display_str, "ExponentialMovingAverage(10)");
154 assert_eq!(ema.period, 10);
155 assert_eq!(ema.price_type, PriceType::Mid);
156 assert_eq!(ema.alpha, 0.181_818_181_818_181_82);
157 assert!(!ema.initialized);
158 }
159
160 #[rstest]
161 fn test_one_value_input(indicator_ema_10: ExponentialMovingAverage) {
162 let mut ema = indicator_ema_10;
163 ema.update_raw(1.0);
164 assert_eq!(ema.count, 1);
165 assert_eq!(ema.value, 1.0);
166 }
167
168 #[rstest]
169 fn test_ema_update_raw(indicator_ema_10: ExponentialMovingAverage) {
170 let mut ema = indicator_ema_10;
171 ema.update_raw(1.0);
172 ema.update_raw(2.0);
173 ema.update_raw(3.0);
174 ema.update_raw(4.0);
175 ema.update_raw(5.0);
176 ema.update_raw(6.0);
177 ema.update_raw(7.0);
178 ema.update_raw(8.0);
179 ema.update_raw(9.0);
180 ema.update_raw(10.0);
181
182 assert!(ema.has_inputs());
183 assert!(ema.initialized());
184 assert_eq!(ema.count, 10);
185 assert_eq!(ema.value, 6.239_368_480_121_215_5);
186 }
187
188 #[rstest]
189 fn test_reset(indicator_ema_10: ExponentialMovingAverage) {
190 let mut ema = indicator_ema_10;
191 ema.update_raw(1.0);
192 assert_eq!(ema.count, 1);
193 ema.reset();
194 assert_eq!(ema.count, 0);
195 assert_eq!(ema.value, 0.0);
196 assert!(!ema.initialized);
197 }
198
199 #[rstest]
200 fn test_handle_quote_tick_single(
201 indicator_ema_10: ExponentialMovingAverage,
202 stub_quote: QuoteTick,
203 ) {
204 let mut ema = indicator_ema_10;
205 ema.handle_quote(&stub_quote);
206 assert!(ema.has_inputs());
207 assert_eq!(ema.value, 1501.0);
208 }
209
210 #[rstest]
211 fn test_handle_quote_tick_multi(mut indicator_ema_10: ExponentialMovingAverage) {
212 let tick1 = stub_quote("1500.0", "1502.0");
213 let tick2 = stub_quote("1502.0", "1504.0");
214
215 indicator_ema_10.handle_quote(&tick1);
216 indicator_ema_10.handle_quote(&tick2);
217 assert_eq!(indicator_ema_10.count, 2);
218 assert_eq!(indicator_ema_10.value, 1_501.363_636_363_636_3);
219 }
220
221 #[rstest]
222 fn test_handle_trade_tick(indicator_ema_10: ExponentialMovingAverage, stub_trade: TradeTick) {
223 let mut ema = indicator_ema_10;
224 ema.handle_trade(&stub_trade);
225 assert!(ema.has_inputs());
226 assert_eq!(ema.value, 1500.0);
227 }
228
229 #[rstest]
230 fn handle_handle_bar(
231 mut indicator_ema_10: ExponentialMovingAverage,
232 bar_ethusdt_binance_minute_bid: Bar,
233 ) {
234 indicator_ema_10.handle_bar(&bar_ethusdt_binance_minute_bid);
235 assert!(indicator_ema_10.has_inputs);
236 assert!(!indicator_ema_10.initialized);
237 assert_eq!(indicator_ema_10.value, 1522.0);
238 }
239
240 #[rstest]
241 fn test_period_one_behaviour() {
242 let mut ema = ExponentialMovingAverage::new(1, None);
243 assert_eq!(ema.alpha, 1.0, "α must be 1 when period = 1");
244
245 ema.update_raw(10.0);
246 assert!(ema.initialized());
247 assert_eq!(ema.value(), 10.0);
248
249 ema.update_raw(42.0);
250 assert_eq!(
251 ema.value(),
252 42.0,
253 "With α = 1, the EMA must track the latest sample exactly"
254 );
255 }
256
257 #[rstest]
258 fn test_default_price_type_is_last() {
259 let ema = ExponentialMovingAverage::new(3, None);
260 assert_eq!(
261 ema.price_type,
262 PriceType::Last,
263 "`price_type` default mismatch"
264 );
265 }
266
267 #[rstest]
268 fn test_nan_poisoning_and_reset_recovery() {
269 let mut ema = ExponentialMovingAverage::new(4, None);
270 for x in 0..3 {
271 ema.update_raw(f64::from(x));
272 assert!(ema.value().is_finite());
273 }
274
275 ema.update_raw(f64::NAN);
276 assert!(ema.value().is_nan());
277
278 ema.update_raw(123.456);
279 assert!(ema.value().is_nan());
280
281 ema.reset();
282 assert!(!ema.has_inputs());
283 ema.update_raw(7.0);
284 assert_eq!(ema.value(), 7.0);
285 assert!(ema.value().is_finite());
286 }
287
288 #[rstest]
289 fn test_reset_without_inputs_is_safe() {
290 let mut ema = ExponentialMovingAverage::new(8, None);
291 ema.reset();
292 assert!(!ema.has_inputs());
293 assert_eq!(ema.count(), 0);
294 assert!(!ema.initialized());
295 }
296
297 #[rstest]
298 fn test_has_inputs_lifecycle() {
299 let mut ema = ExponentialMovingAverage::new(5, None);
300 assert!(!ema.has_inputs());
301
302 ema.update_raw(1.23);
303 assert!(ema.has_inputs());
304
305 ema.reset();
306 assert!(!ema.has_inputs());
307 }
308
309 #[rstest]
310 fn test_subnormal_inputs_do_not_underflow() {
311 let mut ema = ExponentialMovingAverage::new(2, None);
312 let tiny = f64::MIN_POSITIVE / 2.0;
313 ema.update_raw(tiny);
314 ema.update_raw(tiny);
315 assert!(
316 ema.value() > 0.0,
317 "Underflow: EMA value collapsed to zero for sub-normal inputs"
318 );
319 }
320}