nautilus_indicators/average/
wma.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2025 Posei Systems Pty Ltd. All rights reserved.
3//  https://poseitrader.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 arraydeque::{ArrayDeque, Wrapping};
19use nautilus_core::correctness::{FAILED, check_predicate_true};
20use nautilus_model::{
21    data::{Bar, QuoteTick, TradeTick},
22    enums::PriceType,
23};
24
25use crate::indicator::{Indicator, MovingAverage};
26
27const MAX_PERIOD: usize = 8_192;
28
29/// An indicator which calculates a weighted moving average across a rolling window.
30#[repr(C)]
31#[derive(Debug)]
32#[cfg_attr(
33    feature = "python",
34    pyo3::pyclass(module = "posei_trader.core.nautilus_pyo3.indicators")
35)]
36pub struct WeightedMovingAverage {
37    /// The rolling window period for the indicator (> 0).
38    pub period: usize,
39    /// The weights for the moving average calculation
40    pub weights: Vec<f64>,
41    /// Price type
42    pub price_type: PriceType,
43    /// The last indicator value.
44    pub value: f64,
45    /// Whether the indicator is initialized.
46    pub initialized: bool,
47    /// Inputs
48    pub inputs: ArrayDeque<f64, MAX_PERIOD, Wrapping>,
49}
50
51impl Display for WeightedMovingAverage {
52    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
53        write!(f, "{}({},{:?})", self.name(), self.period, self.weights)
54    }
55}
56
57impl WeightedMovingAverage {
58    /// Creates a new [`WeightedMovingAverage`] instance.
59    ///
60    /// # Panics
61    ///
62    /// This function panics if:
63    /// - `period` is zero.
64    /// - `weights.len()` does not equal `period`.
65    /// - `weights` sum is effectively zero.
66    #[must_use]
67    pub fn new(period: usize, weights: Vec<f64>, price_type: Option<PriceType>) -> Self {
68        Self::new_checked(period, weights, price_type).expect(FAILED)
69    }
70
71    /// Creates a new [`WeightedMovingAverage`] instance with the given period and weights.
72    ///
73    /// # Errors
74    ///
75    /// Returns an error if **any** of the validation rules fails:
76    /// - `period` must be **positive**.
77    /// - `weights` must be **exactly** `period` elements long.
78    /// - `weights` must contain at least one non-zero value (∑wᵢ > ε).
79    pub fn new_checked(
80        period: usize,
81        weights: Vec<f64>,
82        price_type: Option<PriceType>,
83    ) -> anyhow::Result<Self> {
84        const EPS: f64 = f64::EPSILON;
85
86        check_predicate_true(period > 0, "`period` must be positive")?;
87
88        check_predicate_true(
89            period == weights.len(),
90            "`period` must equal `weights.len()`",
91        )?;
92
93        let weight_sum: f64 = weights.iter().copied().sum();
94        check_predicate_true(
95            weight_sum > EPS,
96            "`weights` sum must be positive and > f64::EPSILON",
97        )?;
98
99        Ok(Self {
100            period,
101            weights,
102            price_type: price_type.unwrap_or(PriceType::Last),
103            value: 0.0,
104            inputs: ArrayDeque::new(),
105            initialized: false,
106        })
107    }
108
109    fn weighted_average(&self) -> f64 {
110        let n = self.inputs.len();
111        let weights_slice = &self.weights[self.period - n..];
112
113        let mut sum = 0.0;
114        let mut weight_sum = 0.0;
115
116        for (input, weight) in self.inputs.iter().rev().zip(weights_slice.iter().rev()) {
117            sum += input * weight;
118            weight_sum += weight;
119        }
120        sum / weight_sum
121    }
122}
123
124impl Indicator for WeightedMovingAverage {
125    fn name(&self) -> String {
126        stringify!(WeightedMovingAverage).to_string()
127    }
128
129    fn has_inputs(&self) -> bool {
130        !self.inputs.is_empty()
131    }
132
133    fn initialized(&self) -> bool {
134        self.initialized
135    }
136
137    fn handle_quote(&mut self, quote: &QuoteTick) {
138        self.update_raw(quote.extract_price(self.price_type).into());
139    }
140
141    fn handle_trade(&mut self, trade: &TradeTick) {
142        self.update_raw((&trade.price).into());
143    }
144
145    fn handle_bar(&mut self, bar: &Bar) {
146        self.update_raw((&bar.close).into());
147    }
148
149    fn reset(&mut self) {
150        self.value = 0.0;
151        self.initialized = false;
152        self.inputs.clear();
153    }
154}
155
156impl MovingAverage for WeightedMovingAverage {
157    fn value(&self) -> f64 {
158        self.value
159    }
160
161    fn count(&self) -> usize {
162        self.inputs.len()
163    }
164
165    fn update_raw(&mut self, value: f64) {
166        if self.inputs.len() == self.period.min(MAX_PERIOD) {
167            self.inputs.pop_front();
168        }
169        let _ = self.inputs.push_back(value);
170
171        self.value = self.weighted_average();
172        self.initialized = self.count() >= self.period;
173    }
174}
175
176////////////////////////////////////////////////////////////////////////////////
177// Tests
178////////////////////////////////////////////////////////////////////////////////
179#[cfg(test)]
180mod tests {
181    use std::f64::{INFINITY, NAN};
182
183    use arraydeque::{ArrayDeque, Wrapping};
184    use rstest::rstest;
185
186    use crate::{
187        average::wma::WeightedMovingAverage,
188        indicator::{Indicator, MovingAverage},
189        stubs::*,
190    };
191
192    #[rstest]
193    fn test_wma_initialized(indicator_wma_10: WeightedMovingAverage) {
194        let display_str = format!("{indicator_wma_10}");
195        assert_eq!(
196            display_str,
197            "WeightedMovingAverage(10,[0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0])"
198        );
199        assert_eq!(indicator_wma_10.name(), "WeightedMovingAverage");
200        assert!(!indicator_wma_10.has_inputs());
201        assert!(!indicator_wma_10.initialized());
202    }
203
204    #[rstest]
205    #[should_panic]
206    fn test_different_weights_len_and_period_error() {
207        let _ = WeightedMovingAverage::new(10, vec![0.5, 0.5, 0.5], None);
208    }
209
210    #[rstest]
211    fn test_value_with_one_input(mut indicator_wma_10: WeightedMovingAverage) {
212        indicator_wma_10.update_raw(1.0);
213        assert_eq!(indicator_wma_10.value, 1.0);
214    }
215
216    #[rstest]
217    fn test_value_with_two_inputs_equal_weights() {
218        let mut wma = WeightedMovingAverage::new(2, vec![0.5, 0.5], None);
219        wma.update_raw(1.0);
220        wma.update_raw(2.0);
221        assert_eq!(wma.value, 1.5);
222    }
223
224    #[rstest]
225    fn test_value_with_four_inputs_equal_weights() {
226        let mut wma = WeightedMovingAverage::new(4, vec![0.25, 0.25, 0.25, 0.25], None);
227        wma.update_raw(1.0);
228        wma.update_raw(2.0);
229        wma.update_raw(3.0);
230        wma.update_raw(4.0);
231        assert_eq!(wma.value, 2.5);
232    }
233
234    #[rstest]
235    fn test_value_with_two_inputs(mut indicator_wma_10: WeightedMovingAverage) {
236        indicator_wma_10.update_raw(1.0);
237        indicator_wma_10.update_raw(2.0);
238        let result = 2.0f64.mul_add(1.0, 1.0 * 0.9) / 1.9;
239        assert_eq!(indicator_wma_10.value, result);
240    }
241
242    #[rstest]
243    fn test_value_with_three_inputs(mut indicator_wma_10: WeightedMovingAverage) {
244        indicator_wma_10.update_raw(1.0);
245        indicator_wma_10.update_raw(2.0);
246        indicator_wma_10.update_raw(3.0);
247        let result = 1.0f64.mul_add(0.8, 3.0f64.mul_add(1.0, 2.0 * 0.9)) / (1.0 + 0.9 + 0.8);
248        assert_eq!(indicator_wma_10.value, result);
249    }
250
251    #[rstest]
252    fn test_value_expected_with_exact_period(mut indicator_wma_10: WeightedMovingAverage) {
253        for i in 1..11 {
254            indicator_wma_10.update_raw(f64::from(i));
255        }
256        assert_eq!(indicator_wma_10.value, 7.0);
257    }
258
259    #[rstest]
260    fn test_value_expected_with_more_inputs(mut indicator_wma_10: WeightedMovingAverage) {
261        for i in 1..=11 {
262            indicator_wma_10.update_raw(f64::from(i));
263        }
264        assert_eq!(indicator_wma_10.value(), 8.000_000_000_000_002);
265    }
266
267    #[rstest]
268    fn test_reset(mut indicator_wma_10: WeightedMovingAverage) {
269        indicator_wma_10.update_raw(1.0);
270        indicator_wma_10.update_raw(2.0);
271        indicator_wma_10.reset();
272        assert_eq!(indicator_wma_10.value, 0.0);
273        assert_eq!(indicator_wma_10.count(), 0);
274        assert!(!indicator_wma_10.initialized);
275    }
276
277    #[rstest]
278    #[should_panic]
279    fn new_panics_on_zero_period() {
280        let _ = WeightedMovingAverage::new(0, vec![1.0], None);
281    }
282
283    #[rstest]
284    fn new_checked_err_on_zero_period() {
285        let res = WeightedMovingAverage::new_checked(0, vec![1.0], None);
286        assert!(res.is_err());
287    }
288
289    #[rstest]
290    #[should_panic]
291    fn new_panics_on_zero_weight_sum() {
292        let _ = WeightedMovingAverage::new(3, vec![0.0, 0.0, 0.0], None);
293    }
294
295    #[rstest]
296    fn new_checked_err_on_zero_weight_sum() {
297        let res = WeightedMovingAverage::new_checked(3, vec![0.0, 0.0, 0.0], None);
298        assert!(res.is_err());
299    }
300
301    #[rstest]
302    #[should_panic]
303    fn new_panics_when_weight_sum_below_epsilon() {
304        let tiny = f64::EPSILON / 10.0;
305        let _ = WeightedMovingAverage::new(3, vec![tiny; 3], None);
306    }
307
308    #[rstest]
309    fn initialized_flag_transitions() {
310        let period = 3;
311        let weights = vec![1.0, 2.0, 3.0];
312        let mut wma = WeightedMovingAverage::new(period, weights, None);
313
314        assert!(!wma.initialized());
315
316        for i in 0..period {
317            wma.update_raw(i as f64);
318            let expected = (i + 1) >= period;
319            assert_eq!(wma.initialized(), expected);
320        }
321        assert!(wma.initialized());
322    }
323
324    #[rstest]
325    fn count_matches_inputs_and_has_inputs() {
326        let mut wma = WeightedMovingAverage::new(4, vec![0.25; 4], None);
327
328        assert_eq!(wma.count(), 0);
329        assert!(!wma.has_inputs());
330
331        wma.update_raw(1.0);
332        wma.update_raw(2.0);
333        assert_eq!(wma.count(), 2);
334        assert!(wma.has_inputs());
335    }
336
337    #[rstest]
338    fn reset_restores_pristine_state() {
339        let mut wma = WeightedMovingAverage::new(2, vec![0.5, 0.5], None);
340        wma.update_raw(1.0);
341        wma.update_raw(2.0);
342        assert!(wma.initialized());
343
344        wma.reset();
345
346        assert_eq!(wma.count(), 0);
347        assert_eq!(wma.value(), 0.0);
348        assert!(!wma.initialized());
349        assert!(!wma.has_inputs());
350    }
351
352    #[rstest]
353    fn weighted_average_with_non_uniform_weights() {
354        let mut wma = WeightedMovingAverage::new(3, vec![1.0, 2.0, 3.0], None);
355        wma.update_raw(10.0);
356        wma.update_raw(20.0);
357        wma.update_raw(30.0);
358        let expected = 23.333_333_333_333_332;
359        let tol = f64::EPSILON.sqrt();
360        assert!(
361            (wma.value() - expected).abs() < tol,
362            "value = {}, expected ≈ {}",
363            wma.value(),
364            expected
365        );
366    }
367
368    #[rstest]
369    fn test_window_never_exceeds_period(mut indicator_wma_10: WeightedMovingAverage) {
370        for i in 0..100 {
371            indicator_wma_10.update_raw(f64::from(i));
372            assert!(indicator_wma_10.count() <= indicator_wma_10.period);
373        }
374    }
375
376    #[rstest]
377    fn test_negative_weights_positive_sum() {
378        let period = 3;
379        let weights = vec![-1.0, 2.0, 2.0];
380        let mut wma = WeightedMovingAverage::new(period, weights, None);
381        wma.update_raw(1.0);
382        wma.update_raw(2.0);
383        wma.update_raw(3.0);
384
385        let expected = 2.0f64.mul_add(3.0, 2.0f64.mul_add(2.0, -1.0)) / 3.0;
386        let tol = f64::EPSILON.sqrt();
387        assert!((wma.value() - expected).abs() < tol);
388    }
389
390    #[rstest]
391    fn test_nan_input_propagates() {
392        let mut wma = WeightedMovingAverage::new(2, vec![0.5, 0.5], None);
393        wma.update_raw(1.0);
394        wma.update_raw(NAN);
395
396        assert!(wma.value().is_nan());
397    }
398
399    #[rstest]
400    #[should_panic]
401    fn new_panics_when_weight_sum_equals_epsilon() {
402        let eps_third = f64::EPSILON / 3.0;
403        let _ = WeightedMovingAverage::new(3, vec![eps_third; 3], None);
404    }
405
406    #[rstest]
407    fn new_checked_err_when_weight_sum_equals_epsilon() {
408        let eps_third = f64::EPSILON / 3.0;
409        let res = WeightedMovingAverage::new_checked(3, vec![eps_third; 3], None);
410        assert!(res.is_err());
411    }
412
413    #[rstest]
414    fn new_checked_err_when_weight_sum_below_epsilon() {
415        let w = f64::EPSILON * 0.9;
416        let res = WeightedMovingAverage::new_checked(1, vec![w], None);
417        assert!(res.is_err());
418    }
419
420    #[rstest]
421    fn new_ok_when_weight_sum_above_epsilon() {
422        let w = f64::EPSILON * 1.1;
423        let res = WeightedMovingAverage::new_checked(1, vec![w], None);
424        assert!(res.is_ok());
425    }
426
427    #[rstest]
428    #[should_panic]
429    fn new_panics_on_cancelled_weights_sum() {
430        let _ = WeightedMovingAverage::new(3, vec![1.0, -1.0, 0.0], None);
431    }
432
433    #[rstest]
434    fn new_checked_err_on_cancelled_weights_sum() {
435        let res = WeightedMovingAverage::new_checked(3, vec![1.0, -1.0, 0.0], None);
436        assert!(res.is_err());
437    }
438
439    #[rstest]
440    fn single_period_returns_latest_input() {
441        let mut wma = WeightedMovingAverage::new(1, vec![1.0], None);
442        for i in 0..5 {
443            let v = f64::from(i);
444            wma.update_raw(v);
445            assert_eq!(wma.value(), v);
446        }
447    }
448
449    #[rstest]
450    fn value_with_sparse_weights() {
451        let mut wma = WeightedMovingAverage::new(3, vec![0.0, 1.0, 0.0], None);
452        wma.update_raw(10.0);
453        wma.update_raw(20.0);
454        wma.update_raw(30.0);
455        assert_eq!(wma.value(), 20.0);
456    }
457
458    #[rstest]
459    fn warm_up_len1() {
460        let mut wma = WeightedMovingAverage::new(4, vec![1.0, 2.0, 3.0, 4.0], None);
461        wma.update_raw(42.0);
462        assert_eq!(wma.value(), 42.0);
463    }
464
465    #[rstest]
466    fn warm_up_len2() {
467        let mut wma = WeightedMovingAverage::new(4, vec![1.0, 2.0, 3.0, 4.0], None);
468        wma.update_raw(10.0);
469        wma.update_raw(20.0);
470        let expected = 20.0f64.mul_add(4.0, 10.0 * 3.0) / (4.0 + 3.0);
471        assert_eq!(wma.value(), expected);
472    }
473
474    #[rstest]
475    fn warm_up_len3() {
476        let mut wma = WeightedMovingAverage::new(4, vec![1.0, 2.0, 3.0, 4.0], None);
477        wma.update_raw(1.0);
478        wma.update_raw(2.0);
479        wma.update_raw(3.0);
480        let expected = 1.0f64.mul_add(2.0, 3.0f64.mul_add(4.0, 2.0 * 3.0)) / (4.0 + 3.0 + 2.0);
481        assert_eq!(wma.value(), expected);
482    }
483
484    #[rstest]
485    fn input_window_contains_latest_period() {
486        let period = 3;
487        let mut wma = WeightedMovingAverage::new(period, vec![1.0; period], None);
488        let vals = [1.0, 2.0, 3.0, 4.0];
489        for v in vals {
490            wma.update_raw(v);
491        }
492        let expected: Vec<f64> = vals[vals.len() - period..].to_vec();
493        assert_eq!(wma.inputs.iter().copied().collect::<Vec<_>>(), expected);
494    }
495
496    #[rstest]
497    fn window_slides_correctly() {
498        let mut wma = WeightedMovingAverage::new(2, vec![1.0; 2], None);
499        wma.update_raw(1.0);
500        assert_eq!(wma.inputs.iter().copied().collect::<Vec<_>>(), vec![1.0]);
501        wma.update_raw(2.0);
502        assert_eq!(
503            wma.inputs.iter().copied().collect::<Vec<_>>(),
504            vec![1.0, 2.0]
505        );
506        wma.update_raw(3.0);
507        assert_eq!(
508            wma.inputs.iter().copied().collect::<Vec<_>>(),
509            vec![2.0, 3.0]
510        );
511    }
512
513    #[rstest]
514    fn window_len_constant_after_many_updates() {
515        let period = 5;
516        let mut wma = WeightedMovingAverage::new(period, vec![1.0; period], None);
517        for i in 0..100 {
518            wma.update_raw(i as f64);
519            assert_eq!(wma.inputs.len(), period.min(i + 1));
520        }
521    }
522
523    #[rstest]
524    fn arraydeque_wraps_when_full() {
525        const CAP: usize = 3;
526        let mut buf: ArrayDeque<usize, CAP, Wrapping> = ArrayDeque::new();
527        for i in 0..=CAP {
528            let _ = buf.push_back(i);
529        }
530        assert_eq!(buf.len(), CAP);
531        assert_eq!(buf.front().copied(), Some(1));
532        assert_eq!(buf.back().copied(), Some(3));
533    }
534
535    #[rstest]
536    fn arraydeque_sliding_window_with_pop() {
537        const CAP: usize = 3;
538        let mut buf: ArrayDeque<usize, CAP, Wrapping> = ArrayDeque::new();
539        for i in 0..10 {
540            if buf.len() == CAP {
541                buf.pop_front();
542            }
543            let _ = buf.push_back(i);
544            assert!(buf.len() <= CAP);
545        }
546        assert_eq!(buf.len(), CAP);
547    }
548
549    #[rstest]
550    fn new_ok_with_infinite_weight() {
551        let res = WeightedMovingAverage::new_checked(2, vec![INFINITY, 1.0], None);
552        assert!(res.is_ok());
553    }
554
555    #[rstest]
556    #[should_panic]
557    fn new_panics_on_nan_weight() {
558        let _ = WeightedMovingAverage::new(2, vec![NAN, 1.0], None);
559    }
560
561    #[rstest]
562    #[should_panic]
563    fn new_panics_on_empty_weights() {
564        let _ = WeightedMovingAverage::new(1, Vec::new(), None);
565    }
566
567    #[rstest]
568    fn inf_input_propagates() {
569        let mut wma = WeightedMovingAverage::new(2, vec![0.5, 0.5], None);
570        wma.update_raw(1.0);
571        wma.update_raw(INFINITY);
572        assert!(wma.value().is_infinite());
573    }
574
575    #[rstest]
576    fn warm_up_with_front_zero_weights() {
577        let mut wma = WeightedMovingAverage::new(4, vec![0.0, 0.0, 1.0, 1.0], None);
578        wma.update_raw(10.0);
579        wma.update_raw(20.0);
580        let expected = 20.0f64.mul_add(1.0, 10.0 * 1.0) / 2.0;
581        assert_eq!(wma.value(), expected);
582    }
583}