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::{collections::VecDeque, 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::indicator::{Indicator, MovingAverage};
25
26/// An indicator which calculates a weighted moving average across a rolling window.
27#[repr(C)]
28#[derive(Debug)]
29#[cfg_attr(
30    feature = "python",
31    pyo3::pyclass(module = "posei_trader.core.nautilus_pyo3.indicators")
32)]
33pub struct WeightedMovingAverage {
34    /// The rolling window period for the indicator (> 0).
35    pub period: usize,
36    /// The weights for the moving average calculation
37    pub weights: Vec<f64>,
38    /// Price type
39    pub price_type: PriceType,
40    /// The last indicator value.
41    pub value: f64,
42    /// Whether the indicator is initialized.
43    pub initialized: bool,
44    /// Inputs
45    pub inputs: VecDeque<f64>,
46}
47
48impl Display for WeightedMovingAverage {
49    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
50        write!(f, "{}({},{:?})", self.name(), self.period, self.weights)
51    }
52}
53
54impl WeightedMovingAverage {
55    /// Creates a new [`WeightedMovingAverage`] instance.
56    ///
57    /// # Panics
58    ///
59    /// This function panics if:
60    /// - `period` is zero.
61    /// - `weights.len()` does not equal `period`.
62    /// - `weights` sum is effectively zero.
63    #[must_use]
64    pub fn new(period: usize, weights: Vec<f64>, price_type: Option<PriceType>) -> Self {
65        Self::new_checked(period, weights, price_type).expect(FAILED)
66    }
67
68    /// Creates a new [`WeightedMovingAverage`] instance with the given period and weights.
69    ///
70    /// # Errors
71    ///
72    /// Returns an erro if **any** of the validation rules fails:
73    /// - `period` must be **positive**.
74    /// - `weights` must be **exactly** `period` elements long.
75    /// - `weights` must contain at least one non-zero value (∑wᵢ > ε).
76    pub fn new_checked(
77        period: usize,
78        weights: Vec<f64>,
79        price_type: Option<PriceType>,
80    ) -> anyhow::Result<Self> {
81        const EPS: f64 = f64::EPSILON; // ≈ 2.22 e-16
82
83        check_predicate_true(period > 0, "`period` must be positive")?;
84
85        check_predicate_true(
86            period == weights.len(),
87            "`period` must equal `weights.len()`",
88        )?;
89
90        let weight_sum: f64 = weights.iter().copied().sum();
91        check_predicate_true(
92            weight_sum > EPS,
93            "`weights` sum must be positive and > f64::EPSILON",
94        )?;
95
96        Ok(Self {
97            period,
98            weights,
99            price_type: price_type.unwrap_or(PriceType::Last),
100            value: 0.0,
101            inputs: VecDeque::with_capacity(period),
102            initialized: false,
103        })
104    }
105
106    fn weighted_average(&self) -> f64 {
107        let n = self.inputs.len();
108        let weights_slice = &self.weights[self.period - n..];
109
110        let mut sum = 0.0;
111        let mut weight_sum = 0.0;
112
113        for (input, weight) in self.inputs.iter().rev().zip(weights_slice.iter().rev()) {
114            sum += input * weight;
115            weight_sum += weight;
116        }
117        sum / weight_sum
118    }
119}
120
121impl Indicator for WeightedMovingAverage {
122    fn name(&self) -> String {
123        stringify!(WeightedMovingAverage).to_string()
124    }
125
126    fn has_inputs(&self) -> bool {
127        !self.inputs.is_empty()
128    }
129
130    fn initialized(&self) -> bool {
131        self.initialized
132    }
133
134    fn handle_quote(&mut self, quote: &QuoteTick) {
135        self.update_raw(quote.extract_price(self.price_type).into());
136    }
137
138    fn handle_trade(&mut self, trade: &TradeTick) {
139        self.update_raw((&trade.price).into());
140    }
141
142    fn handle_bar(&mut self, bar: &Bar) {
143        self.update_raw((&bar.close).into());
144    }
145
146    fn reset(&mut self) {
147        self.value = 0.0;
148        self.initialized = false;
149        self.inputs.clear();
150    }
151}
152
153impl MovingAverage for WeightedMovingAverage {
154    fn value(&self) -> f64 {
155        self.value
156    }
157
158    fn count(&self) -> usize {
159        self.inputs.len()
160    }
161
162    fn update_raw(&mut self, value: f64) {
163        if self.inputs.len() == self.period {
164            self.inputs.pop_front();
165        }
166        self.inputs.push_back(value);
167
168        self.value = self.weighted_average();
169
170        self.initialized = self.count() >= self.period;
171    }
172}
173
174////////////////////////////////////////////////////////////////////////////////
175// Tests
176////////////////////////////////////////////////////////////////////////////////
177#[cfg(test)]
178mod tests {
179    use std::{
180        collections::VecDeque,
181        f64::{INFINITY, NAN},
182    };
183
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        use std::f64::NAN;
393
394        let mut wma = WeightedMovingAverage::new(2, vec![0.5, 0.5], None);
395        wma.update_raw(1.0);
396        wma.update_raw(NAN);
397
398        assert!(wma.value().is_nan());
399    }
400
401    #[rstest]
402    #[should_panic]
403    fn new_panics_when_weight_sum_equals_epsilon() {
404        let eps_third = f64::EPSILON / 3.0;
405        let _ = WeightedMovingAverage::new(3, vec![eps_third; 3], None);
406    }
407
408    #[rstest]
409    fn new_checked_err_when_weight_sum_equals_epsilon() {
410        let eps_third = f64::EPSILON / 3.0;
411        let res = WeightedMovingAverage::new_checked(3, vec![eps_third; 3], None);
412        assert!(res.is_err());
413    }
414
415    #[rstest]
416    fn new_checked_err_when_weight_sum_below_epsilon() {
417        let w = f64::EPSILON * 0.9;
418        let res = WeightedMovingAverage::new_checked(1, vec![w], None);
419        assert!(res.is_err());
420    }
421
422    #[rstest]
423    fn new_ok_when_weight_sum_above_epsilon() {
424        let w = f64::EPSILON * 1.1;
425        let res = WeightedMovingAverage::new_checked(1, vec![w], None);
426        assert!(res.is_ok());
427    }
428
429    #[rstest]
430    #[should_panic]
431    fn new_panics_on_cancelled_weights_sum() {
432        let _ = WeightedMovingAverage::new(3, vec![1.0, -1.0, 0.0], None);
433    }
434
435    #[rstest]
436    fn new_checked_err_on_cancelled_weights_sum() {
437        let res = WeightedMovingAverage::new_checked(3, vec![1.0, -1.0, 0.0], None);
438        assert!(res.is_err());
439    }
440
441    #[rstest]
442    fn single_period_returns_latest_input() {
443        let mut wma = WeightedMovingAverage::new(1, vec![1.0], None);
444        for i in 0..5 {
445            let v = f64::from(i);
446            wma.update_raw(v);
447            assert_eq!(wma.value(), v);
448        }
449    }
450
451    #[rstest]
452    fn value_with_sparse_weights() {
453        let mut wma = WeightedMovingAverage::new(3, vec![0.0, 1.0, 0.0], None);
454        wma.update_raw(10.0);
455        wma.update_raw(20.0);
456        wma.update_raw(30.0);
457        assert_eq!(wma.value(), 20.0);
458    }
459
460    #[rstest]
461    fn warm_up_len1() {
462        let mut wma = WeightedMovingAverage::new(4, vec![1.0, 2.0, 3.0, 4.0], None);
463        wma.update_raw(42.0);
464        assert_eq!(wma.value(), 42.0);
465    }
466
467    #[rstest]
468    fn warm_up_len2() {
469        let mut wma = WeightedMovingAverage::new(4, vec![1.0, 2.0, 3.0, 4.0], None);
470        wma.update_raw(10.0);
471        wma.update_raw(20.0);
472        let expected = 20.0f64.mul_add(4.0, 10.0 * 3.0) / (4.0 + 3.0);
473        assert_eq!(wma.value(), expected);
474    }
475
476    #[rstest]
477    fn warm_up_len3() {
478        let mut wma = WeightedMovingAverage::new(4, vec![1.0, 2.0, 3.0, 4.0], None);
479        wma.update_raw(1.0);
480        wma.update_raw(2.0);
481        wma.update_raw(3.0);
482        let expected = 1.0f64.mul_add(2.0, 3.0f64.mul_add(4.0, 2.0 * 3.0)) / (4.0 + 3.0 + 2.0);
483        assert_eq!(wma.value(), expected);
484    }
485
486    #[rstest]
487    fn input_window_contains_latest_period() {
488        let period = 3;
489        let mut wma = WeightedMovingAverage::new(period, vec![1.0; period], None);
490        let vals = [1.0, 2.0, 3.0, 4.0];
491        for v in vals {
492            wma.update_raw(v);
493        }
494        let expected: Vec<f64> = vals[vals.len() - period..].to_vec();
495        assert_eq!(wma.inputs.iter().copied().collect::<Vec<_>>(), expected);
496    }
497
498    #[rstest]
499    fn window_slides_correctly() {
500        let mut wma = WeightedMovingAverage::new(2, vec![1.0; 2], None);
501        wma.update_raw(1.0);
502        assert_eq!(wma.inputs.iter().copied().collect::<Vec<_>>(), vec![1.0]);
503        wma.update_raw(2.0);
504        assert_eq!(
505            wma.inputs.iter().copied().collect::<Vec<_>>(),
506            vec![1.0, 2.0]
507        );
508        wma.update_raw(3.0);
509        assert_eq!(
510            wma.inputs.iter().copied().collect::<Vec<_>>(),
511            vec![2.0, 3.0]
512        );
513    }
514
515    #[rstest]
516    fn window_len_constant_after_many_updates() {
517        let period = 5;
518        let mut wma = WeightedMovingAverage::new(period, vec![1.0; period], None);
519        for i in 0..100 {
520            wma.update_raw(i as f64);
521            assert_eq!(wma.inputs.len(), period.min(i + 1));
522        }
523    }
524
525    #[rstest]
526    #[should_panic]
527    fn new_panics_on_nan_weight() {
528        let _ = WeightedMovingAverage::new(2, vec![NAN, 1.0], None);
529    }
530
531    #[rstest]
532    fn new_ok_with_infinite_weight() {
533        let res = WeightedMovingAverage::new_checked(2, vec![INFINITY, 1.0], None);
534        assert!(res.is_ok());
535    }
536
537    #[rstest]
538    #[should_panic]
539    fn new_panics_on_empty_weights() {
540        let _ = WeightedMovingAverage::new(1, Vec::new(), None);
541    }
542
543    #[rstest]
544    fn inf_input_propagates() {
545        let mut wma = WeightedMovingAverage::new(2, vec![0.5, 0.5], None);
546        wma.update_raw(1.0);
547        wma.update_raw(INFINITY);
548        assert!(wma.value().is_infinite());
549    }
550
551    #[rstest]
552    fn warm_up_with_front_zero_weights() {
553        let mut wma = WeightedMovingAverage::new(4, vec![0.0, 0.0, 1.0, 1.0], None);
554        wma.update_raw(10.0);
555        wma.update_raw(20.0);
556        let expected = 20.0f64.mul_add(1.0, 10.0 * 1.0) / 2.0;
557        assert_eq!(wma.value(), expected);
558    }
559
560    #[rstest]
561    fn vecdeque_grows_without_pop() {
562        let period = 3;
563        let mut buf: VecDeque<usize> = VecDeque::with_capacity(period);
564        for i in 0..=period {
565            buf.push_back(i);
566        }
567        assert_eq!(buf.len(), period + 1);
568    }
569
570    #[rstest]
571    fn vecdeque_sliding_window_with_pop() {
572        let period = 3;
573        let mut buf: VecDeque<usize> = VecDeque::with_capacity(period);
574        for i in 0..10 {
575            if buf.len() == period {
576                buf.pop_front();
577            }
578            buf.push_back(i);
579            assert!(buf.len() <= period);
580        }
581        assert_eq!(buf.len(), period);
582    }
583}