Skip to main content

nautilus_indicators/average/
ema.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2026 Nautech Systems Pty Ltd. All rights reserved.
3//  https://nautechsystems.io
4//
5//  Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
6//  You may not use this file except in compliance with the License.
7//  You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
8//
9//  Unless required by applicable law or agreed to in writing, software
10//  distributed under the License is distributed on an "AS IS" BASIS,
11//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12//  See the License for the specific language governing permissions and
13//  limitations under the License.
14// -------------------------------------------------------------------------------------------------
15
16use std::fmt::Display;
17
18use nautilus_core::correctness::{FAILED, check_predicate_true};
19use nautilus_model::{
20    data::{Bar, QuoteTick, TradeTick},
21    enums::PriceType,
22};
23
24use crate::{
25    indicator::{Indicator, MovingAverage},
26    support::MAX_PERIOD,
27};
28
29/// Exponential moving average.
30#[repr(C)]
31#[derive(Debug)]
32#[cfg_attr(
33    feature = "python",
34    pyo3::pyclass(module = "nautilus_trader.indicators")
35)]
36#[cfg_attr(
37    feature = "python",
38    pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.indicators")
39)]
40pub struct ExponentialMovingAverage {
41    pub period: usize,
42    pub price_type: PriceType,
43    pub alpha: f64,
44    pub value: f64,
45    pub count: usize,
46    pub initialized: bool,
47    has_inputs: bool,
48    seed_sum: f64,
49}
50
51impl Display for ExponentialMovingAverage {
52    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
53        write!(f, "{}({})", self.name(), self.period)
54    }
55}
56
57impl Indicator for ExponentialMovingAverage {
58    fn name(&self) -> String {
59        stringify!(ExponentialMovingAverage).to_string()
60    }
61
62    fn has_inputs(&self) -> bool {
63        self.has_inputs
64    }
65
66    fn initialized(&self) -> bool {
67        self.initialized
68    }
69
70    fn handle_quote(&mut self, quote: &QuoteTick) -> anyhow::Result<()> {
71        self.update_raw(quote.extract_price(self.price_type)?.into());
72        Ok(())
73    }
74
75    fn handle_trade(&mut self, trade: &TradeTick) {
76        self.update_raw((&trade.price).into());
77    }
78
79    fn handle_bar(&mut self, bar: &Bar) {
80        self.update_raw((&bar.close).into());
81    }
82
83    fn reset(&mut self) {
84        self.value = 0.0;
85        self.count = 0;
86        self.has_inputs = false;
87        self.initialized = false;
88        self.seed_sum = 0.0;
89    }
90}
91
92impl ExponentialMovingAverage {
93    /// Creates a new [`ExponentialMovingAverage`] instance.
94    ///
95    /// # Panics
96    ///
97    /// Panics if `period` is zero or exceeds 16,777,216.
98    #[must_use]
99    pub fn new(period: usize, price_type: Option<PriceType>) -> Self {
100        Self::new_checked(period, price_type).expect(FAILED)
101    }
102
103    /// Creates an exponential moving average with a validated period.
104    ///
105    /// # Errors
106    ///
107    /// Returns an error if `period` is zero or exceeds 16,777,216.
108    pub fn new_checked(period: usize, price_type: Option<PriceType>) -> anyhow::Result<Self> {
109        check_predicate_true(
110            period > 0,
111            &format!("ExponentialMovingAverage: period must be > 0 (received {period})"),
112        )?;
113        check_predicate_true(
114            period <= MAX_PERIOD,
115            &format!("period cannot exceed {MAX_PERIOD}"),
116        )?;
117        Ok(Self {
118            period,
119            price_type: price_type.unwrap_or(PriceType::Last),
120            alpha: 2.0 / (period as f64 + 1.0),
121            value: 0.0,
122            count: 0,
123            has_inputs: false,
124            initialized: false,
125            seed_sum: 0.0,
126        })
127    }
128}
129
130impl MovingAverage for ExponentialMovingAverage {
131    fn value(&self) -> f64 {
132        self.value
133    }
134
135    fn count(&self) -> usize {
136        self.count
137    }
138
139    fn update_raw(&mut self, value: f64) {
140        if !value.is_finite() {
141            return;
142        }
143
144        self.has_inputs = true;
145        self.count += 1;
146        if self.count < self.period {
147            self.seed_sum += value;
148            return;
149        }
150
151        if self.count == self.period {
152            self.seed_sum += value;
153            self.value = self.seed_sum / self.period as f64;
154            self.initialized = true;
155            return;
156        }
157
158        self.value = self.alpha.mul_add(value, (1.0 - self.alpha) * self.value);
159    }
160}
161
162#[cfg(test)]
163mod tests {
164    use nautilus_model::{
165        data::{Bar, QuoteTick, TradeTick},
166        enums::PriceType,
167    };
168    use rstest::rstest;
169
170    use super::MAX_PERIOD;
171    use crate::{
172        average::ema::ExponentialMovingAverage,
173        indicator::{Indicator, MovingAverage},
174        stubs::*,
175        testing::assert_approx_equal,
176    };
177
178    #[rstest]
179    #[case(0)]
180    #[case(MAX_PERIOD + 1)]
181    #[case(usize::MAX)]
182    fn test_checked_constructor_rejects_invalid_period(#[case] period: usize) {
183        assert!(ExponentialMovingAverage::new_checked(period, None).is_err());
184    }
185
186    #[rstest]
187    fn test_ema_initialized(indicator_ema_10: ExponentialMovingAverage) {
188        let ema = indicator_ema_10;
189        let display_str = format!("{ema}");
190        assert_eq!(display_str, "ExponentialMovingAverage(10)");
191        assert_eq!(ema.period, 10);
192        assert_eq!(ema.price_type, PriceType::Mid);
193        assert_approx_equal(ema.alpha, 0.181818181818);
194        assert!(!ema.initialized);
195    }
196
197    #[rstest]
198    fn test_one_value_input(indicator_ema_10: ExponentialMovingAverage) {
199        let mut ema = indicator_ema_10;
200        ema.update_raw(1.0);
201        assert_eq!(ema.count, 1);
202        assert_eq!(ema.value, 0.0);
203        assert!(!ema.initialized());
204    }
205
206    #[rstest]
207    fn test_ema_update_raw(indicator_ema_10: ExponentialMovingAverage) {
208        let mut ema = indicator_ema_10;
209        for value in 1..=10 {
210            ema.update_raw(f64::from(value));
211        }
212
213        assert!(ema.has_inputs());
214        assert!(ema.initialized());
215        assert_eq!(ema.count, 10);
216        assert_eq!(ema.value, 5.5);
217    }
218
219    #[rstest]
220    fn test_reset(indicator_ema_10: ExponentialMovingAverage) {
221        let mut ema = indicator_ema_10;
222        ema.update_raw(1.0);
223        assert_eq!(ema.count, 1);
224        ema.reset();
225        assert_eq!(ema.count, 0);
226        assert_eq!(ema.value, 0.0);
227        assert!(!ema.initialized);
228    }
229
230    #[rstest]
231    fn test_handle_quote_tick_single(
232        indicator_ema_10: ExponentialMovingAverage,
233        stub_quote: QuoteTick,
234    ) {
235        let mut ema = indicator_ema_10;
236        ema.handle_quote(&stub_quote).unwrap();
237
238        assert!(ema.has_inputs());
239        assert_eq!(ema.count, 1);
240        assert_eq!(ema.value, 0.0);
241        assert!(!ema.initialized());
242    }
243
244    #[rstest]
245    fn test_handle_quote_tick_multi(mut indicator_ema_10: ExponentialMovingAverage) {
246        let tick1 = stub_quote("1500.0", "1502.0");
247        let tick2 = stub_quote("1502.0", "1504.0");
248        indicator_ema_10.handle_quote(&tick1).unwrap();
249        indicator_ema_10.handle_quote(&tick2).unwrap();
250
251        assert_eq!(indicator_ema_10.count, 2);
252        assert_eq!(indicator_ema_10.value, 0.0);
253        assert!(!indicator_ema_10.initialized());
254    }
255
256    #[rstest]
257    fn test_handle_trade_tick(indicator_ema_10: ExponentialMovingAverage, stub_trade: TradeTick) {
258        let mut ema = indicator_ema_10;
259        ema.handle_trade(&stub_trade);
260
261        assert!(ema.has_inputs());
262        assert_eq!(ema.count, 1);
263        assert_eq!(ema.value, 0.0);
264        assert!(!ema.initialized());
265    }
266
267    #[rstest]
268    fn handle_handle_bar(
269        mut indicator_ema_10: ExponentialMovingAverage,
270        bar_ethusdt_binance_minute_bid: Bar,
271    ) {
272        indicator_ema_10.handle_bar(&bar_ethusdt_binance_minute_bid);
273
274        assert!(indicator_ema_10.has_inputs);
275        assert_eq!(indicator_ema_10.count, 1);
276        assert_eq!(indicator_ema_10.value, 0.0);
277        assert!(!indicator_ema_10.initialized);
278    }
279
280    #[rstest]
281    fn test_period_one_behavior() {
282        let mut ema = ExponentialMovingAverage::new(1, None);
283        assert_eq!(ema.alpha, 1.0, "α must be 1 when period = 1");
284
285        ema.update_raw(10.0);
286        assert!(ema.initialized());
287        assert_eq!(ema.value(), 10.0);
288
289        ema.update_raw(42.0);
290        assert_eq!(
291            ema.value(),
292            42.0,
293            "With α = 1, the EMA must track the latest sample exactly"
294        );
295    }
296
297    #[rstest]
298    fn test_default_price_type_is_last() {
299        let ema = ExponentialMovingAverage::new(3, None);
300        assert_eq!(
301            ema.price_type,
302            PriceType::Last,
303            "`price_type` default mismatch"
304        );
305    }
306
307    #[rstest]
308    fn test_nan_poisoning_and_reset_recovery() {
309        let mut ema = ExponentialMovingAverage::new(4, None);
310        for value in [1.0, 2.0, 3.0, 4.0] {
311            ema.update_raw(value);
312        }
313        let before = (ema.value(), ema.count());
314
315        ema.update_raw(f64::NAN);
316        ema.update_raw(f64::INFINITY);
317
318        assert_eq!((ema.value(), ema.count()), before);
319        ema.update_raw(5.0);
320        assert!(ema.value().is_finite());
321        ema.reset();
322        assert!(!ema.has_inputs());
323        assert_eq!(ema.value(), 0.0);
324    }
325
326    #[rstest]
327    fn test_reset_without_inputs_is_safe() {
328        let mut ema = ExponentialMovingAverage::new(8, None);
329        ema.reset();
330        assert!(!ema.has_inputs());
331        assert_eq!(ema.count(), 0);
332        assert!(!ema.initialized());
333    }
334
335    #[rstest]
336    fn test_has_inputs_lifecycle() {
337        let mut ema = ExponentialMovingAverage::new(5, None);
338        assert!(!ema.has_inputs());
339
340        ema.update_raw(1.23);
341        assert!(ema.has_inputs());
342
343        ema.reset();
344        assert!(!ema.has_inputs());
345    }
346
347    #[rstest]
348    fn test_subnormal_inputs_do_not_underflow() {
349        let mut ema = ExponentialMovingAverage::new(2, None);
350        let tiny = f64::MIN_POSITIVE / 2.0;
351        ema.update_raw(tiny);
352        ema.update_raw(tiny);
353        assert!(
354            ema.value() > 0.0,
355            "Underflow: EMA value collapsed to zero for sub-normal inputs"
356        );
357    }
358}