Skip to main content

nautilus_indicators/average/
rma.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_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)]
31#[cfg_attr(
32    feature = "python",
33    pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.indicators")
34)]
35pub struct WilderMovingAverage {
36    pub period: usize,
37    pub price_type: PriceType,
38    pub alpha: f64,
39    pub value: f64,
40    pub count: usize,
41    pub initialized: bool,
42    has_inputs: bool,
43}
44
45impl Display for WilderMovingAverage {
46    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
47        write!(f, "{}({})", self.name(), self.period)
48    }
49}
50
51impl Indicator for WilderMovingAverage {
52    fn name(&self) -> String {
53        stringify!(WilderMovingAverage).to_string()
54    }
55
56    fn has_inputs(&self) -> bool {
57        self.has_inputs
58    }
59    fn initialized(&self) -> bool {
60        self.initialized
61    }
62
63    fn handle_quote(&mut self, quote: &QuoteTick) {
64        self.update_raw(quote.extract_price(self.price_type).into());
65    }
66
67    fn handle_trade(&mut self, t: &TradeTick) {
68        self.update_raw((&t.price).into());
69    }
70
71    fn handle_bar(&mut self, b: &Bar) {
72        self.update_raw((&b.close).into());
73    }
74
75    fn reset(&mut self) {
76        self.value = 0.0;
77        self.count = 0;
78        self.has_inputs = false;
79        self.initialized = false;
80    }
81}
82
83impl WilderMovingAverage {
84    /// Creates a new [`WilderMovingAverage`] instance.
85    ///
86    /// # Panics
87    ///
88    /// Panics if `period` is not positive (> 0).
89    #[must_use]
90    pub fn new(period: usize, price_type: Option<PriceType>) -> Self {
91        // The Wilder Moving Average is The Wilder's Moving Average is simply
92        // an Exponential Moving Average (EMA) with a modified alpha.
93        // alpha = 1 / period
94        assert!(
95            period > 0,
96            "WilderMovingAverage: period must be > 0 (received {period})"
97        );
98        Self {
99            period,
100            price_type: price_type.unwrap_or(PriceType::Last),
101            alpha: 1.0 / period as f64,
102            value: 0.0,
103            count: 0,
104            initialized: false,
105            has_inputs: false,
106        }
107    }
108}
109
110impl MovingAverage for WilderMovingAverage {
111    fn value(&self) -> f64 {
112        self.value
113    }
114    fn count(&self) -> usize {
115        self.count
116    }
117
118    fn update_raw(&mut self, price: f64) {
119        if !self.has_inputs {
120            self.has_inputs = true;
121            self.value = price;
122            self.count = 1;
123            self.initialized = self.count >= self.period;
124            return;
125        }
126
127        self.value = self.alpha.mul_add(price, (1.0 - self.alpha) * self.value);
128        self.count += 1;
129        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::rma::WilderMovingAverage,
145        indicator::{Indicator, MovingAverage},
146        stubs::*,
147    };
148
149    #[rstest]
150    fn test_rma_initialized(indicator_rma_10: WilderMovingAverage) {
151        let rma = indicator_rma_10;
152        let display_str = format!("{rma}");
153        assert_eq!(display_str, "WilderMovingAverage(10)");
154        assert_eq!(rma.period, 10);
155        assert_eq!(rma.price_type, PriceType::Mid);
156        assert_eq!(rma.alpha, 0.1);
157        assert!(!rma.initialized);
158    }
159
160    #[rstest]
161    #[should_panic(expected = "WilderMovingAverage: period must be > 0")]
162    fn test_new_with_zero_period_panics() {
163        let _ = WilderMovingAverage::new(0, None);
164    }
165
166    #[rstest]
167    fn test_one_value_input(indicator_rma_10: WilderMovingAverage) {
168        let mut rma = indicator_rma_10;
169        rma.update_raw(1.0);
170        assert_eq!(rma.count, 1);
171        assert_eq!(rma.value, 1.0);
172    }
173
174    #[rstest]
175    fn test_rma_update_raw(indicator_rma_10: WilderMovingAverage) {
176        let mut rma = indicator_rma_10;
177        rma.update_raw(1.0);
178        rma.update_raw(2.0);
179        rma.update_raw(3.0);
180        rma.update_raw(4.0);
181        rma.update_raw(5.0);
182        rma.update_raw(6.0);
183        rma.update_raw(7.0);
184        rma.update_raw(8.0);
185        rma.update_raw(9.0);
186        rma.update_raw(10.0);
187
188        assert!(rma.has_inputs());
189        assert!(rma.initialized());
190        assert_eq!(rma.count, 10);
191        assert_eq!(rma.value, 4.486_784_401);
192    }
193
194    #[rstest]
195    fn test_reset(indicator_rma_10: WilderMovingAverage) {
196        let mut rma = indicator_rma_10;
197        rma.update_raw(1.0);
198        assert_eq!(rma.count, 1);
199        rma.reset();
200        assert_eq!(rma.count, 0);
201        assert_eq!(rma.value, 0.0);
202        assert!(!rma.initialized);
203    }
204
205    #[rstest]
206    fn test_handle_quote_tick_single(indicator_rma_10: WilderMovingAverage, stub_quote: QuoteTick) {
207        let mut rma = indicator_rma_10;
208        rma.handle_quote(&stub_quote);
209        assert!(rma.has_inputs());
210        assert_eq!(rma.value, 1501.0);
211    }
212
213    #[rstest]
214    fn test_handle_quote_tick_multi(mut indicator_rma_10: WilderMovingAverage) {
215        let tick1 = stub_quote("1500.0", "1502.0");
216        let tick2 = stub_quote("1502.0", "1504.0");
217
218        indicator_rma_10.handle_quote(&tick1);
219        indicator_rma_10.handle_quote(&tick2);
220        assert_eq!(indicator_rma_10.count, 2);
221        assert_eq!(indicator_rma_10.value, 1_501.2);
222    }
223
224    #[rstest]
225    fn test_handle_trade_tick(indicator_rma_10: WilderMovingAverage, stub_trade: TradeTick) {
226        let mut rma = indicator_rma_10;
227        rma.handle_trade(&stub_trade);
228        assert!(rma.has_inputs());
229        assert_eq!(rma.value, 1500.0);
230    }
231
232    #[rstest]
233    fn handle_handle_bar(
234        mut indicator_rma_10: WilderMovingAverage,
235        bar_ethusdt_binance_minute_bid: Bar,
236    ) {
237        indicator_rma_10.handle_bar(&bar_ethusdt_binance_minute_bid);
238        assert!(indicator_rma_10.has_inputs);
239        assert!(!indicator_rma_10.initialized);
240        assert_eq!(indicator_rma_10.value, 1522.0);
241    }
242
243    #[rstest]
244    #[should_panic(expected = "WilderMovingAverage: period must be > 0")]
245    fn invalid_period_panics() {
246        let _ = WilderMovingAverage::new(0, None);
247    }
248
249    #[rstest]
250    #[case(1.0)]
251    #[case(123.456)]
252    #[case(9_876.543_21)]
253    fn first_tick_seeding_parity(#[case] seed_price: f64) {
254        let mut rma = WilderMovingAverage::new(10, None);
255
256        rma.update_raw(seed_price);
257
258        assert_eq!(rma.count(), 1);
259        assert_eq!(rma.value(), seed_price);
260        assert!(!rma.initialized());
261    }
262
263    #[rstest]
264    fn numeric_parity_with_reference_series() {
265        let mut rma = WilderMovingAverage::new(10, None);
266
267        for price in 1_u32..=10 {
268            rma.update_raw(f64::from(price));
269        }
270
271        assert!(rma.initialized());
272        assert_eq!(rma.count(), 10);
273        let expected = 4.486_784_401_f64;
274        assert!((rma.value() - expected).abs() < 1e-12);
275    }
276
277    /// Period = 1 should act as a pure 1-tick MA (α = 1) and be initialized immediately.
278    #[rstest]
279    fn test_rma_period_one_behaviour() {
280        let mut rma = WilderMovingAverage::new(1, None);
281
282        // First tick seeds and immediately initializes
283        rma.update_raw(42.0);
284        assert!(rma.initialized());
285        assert_eq!(rma.count(), 1);
286        assert!((rma.value() - 42.0).abs() < 1e-12);
287
288        // With α = 1 the next tick fully replaces the previous value
289        rma.update_raw(100.0);
290        assert_eq!(rma.count(), 2);
291        assert!((rma.value() - 100.0).abs() < 1e-12);
292    }
293
294    /// Very large period: `initialized()` must remain `false` until enough samples arrive.
295    #[rstest]
296    fn test_rma_large_period_not_initialized() {
297        let mut rma = WilderMovingAverage::new(1_000, None);
298
299        for p in 1_u32..=999 {
300            rma.update_raw(f64::from(p));
301        }
302
303        assert_eq!(rma.count(), 999);
304        assert!(!rma.initialized());
305    }
306
307    #[rstest]
308    fn test_reset_reseeds_properly() {
309        let mut rma = WilderMovingAverage::new(10, None);
310
311        rma.update_raw(10.0);
312        assert!(rma.has_inputs());
313        assert_eq!(rma.count(), 1);
314
315        rma.reset();
316        assert_eq!(rma.count(), 0);
317        assert!(!rma.has_inputs());
318        assert!(!rma.initialized());
319
320        rma.update_raw(20.0);
321        assert_eq!(rma.count(), 1);
322        assert!((rma.value() - 20.0).abs() < 1e-12);
323    }
324
325    #[rstest]
326    fn test_default_price_type_is_last() {
327        let rma = WilderMovingAverage::new(5, None);
328        assert_eq!(rma.price_type, PriceType::Last);
329    }
330
331    #[rstest]
332    fn test_update_with_nan_propagates() {
333        let mut rma = WilderMovingAverage::new(10, None);
334        rma.update_raw(f64::NAN);
335
336        assert!(rma.value().is_nan());
337        assert!(rma.has_inputs());
338        assert_eq!(rma.count(), 1);
339    }
340}