nautilus-indicators 0.56.0

Technical indicators for the Nautilus trading engine
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
// -------------------------------------------------------------------------------------------------
//  Copyright (C) 2015-2026 Nautech Systems Pty Ltd. All rights reserved.
//  https://nautechsystems.io
//
//  Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
//  You may not use this file except in compliance with the License.
//  You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.
// -------------------------------------------------------------------------------------------------

use std::fmt::Display;

use arraydeque::{ArrayDeque, Wrapping};
use nautilus_model::{
    data::{Bar, QuoteTick, TradeTick},
    enums::PriceType,
};

use crate::indicator::{Indicator, MovingAverage};

const MAX_PERIOD: usize = 1_024;

#[repr(C)]
#[derive(Debug)]
#[cfg_attr(
    feature = "python",
    pyo3::pyclass(module = "nautilus_trader.core.nautilus_pyo3.indicators")
)]
#[cfg_attr(
    feature = "python",
    pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.indicators")
)]
pub struct SimpleMovingAverage {
    pub period: usize,
    pub price_type: PriceType,
    pub value: f64,
    sum: f64,
    pub count: usize,
    buf: ArrayDeque<f64, MAX_PERIOD, Wrapping>,
    pub initialized: bool,
}

impl Display for SimpleMovingAverage {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}({})", self.name(), self.period)
    }
}

impl Indicator for SimpleMovingAverage {
    fn name(&self) -> String {
        stringify!(SimpleMovingAverage).into()
    }

    fn has_inputs(&self) -> bool {
        self.count > 0
    }

    fn initialized(&self) -> bool {
        self.initialized
    }

    fn handle_quote(&mut self, quote: &QuoteTick) {
        self.process_raw(quote.extract_price(self.price_type).into());
    }

    fn handle_trade(&mut self, trade: &TradeTick) {
        self.process_raw(trade.price.into());
    }

    fn handle_bar(&mut self, bar: &Bar) {
        self.process_raw(bar.close.into());
    }

    fn reset(&mut self) {
        self.value = 0.0;
        self.sum = 0.0;
        self.count = 0;
        self.buf.clear();
        self.initialized = false;
    }
}

impl MovingAverage for SimpleMovingAverage {
    fn value(&self) -> f64 {
        self.value
    }

    fn count(&self) -> usize {
        self.count
    }

    fn update_raw(&mut self, value: f64) {
        self.process_raw(value);
    }
}

impl SimpleMovingAverage {
    /// Creates a new [`SimpleMovingAverage`] instance.
    ///
    /// # Panics
    ///
    /// Panics if `period` is not positive (> 0).
    #[must_use]
    pub fn new(period: usize, price_type: Option<PriceType>) -> Self {
        assert!(period > 0, "SimpleMovingAverage: period must be > 0");
        assert!(
            period <= MAX_PERIOD,
            "SimpleMovingAverage: period {period} exceeds MAX_PERIOD ({MAX_PERIOD})"
        );

        Self {
            period,
            price_type: price_type.unwrap_or(PriceType::Last),
            value: 0.0,
            sum: 0.0,
            count: 0,
            buf: ArrayDeque::new(),
            initialized: false,
        }
    }

    fn process_raw(&mut self, price: f64) {
        if self.count == self.period {
            if let Some(oldest) = self.buf.pop_front() {
                self.sum -= oldest;
            }
        } else {
            self.count += 1;
        }

        let _ = self.buf.push_back(price);
        self.sum += price;

        self.value = self.sum / self.count as f64;
        self.initialized = self.count >= self.period;
    }
}

#[cfg(test)]
mod tests {
    use arraydeque::{ArrayDeque, Wrapping};
    use nautilus_model::{
        data::{QuoteTick, TradeTick},
        enums::PriceType,
    };
    use rstest::rstest;

    use super::MAX_PERIOD;
    use crate::{
        average::sma::SimpleMovingAverage,
        indicator::{Indicator, MovingAverage},
        stubs::*,
    };

    #[rstest]
    fn sma_initialized_state(indicator_sma_10: SimpleMovingAverage) {
        let display_str = format!("{indicator_sma_10}");
        assert_eq!(display_str, "SimpleMovingAverage(10)");
        assert_eq!(indicator_sma_10.period, 10);
        assert_eq!(indicator_sma_10.price_type, PriceType::Mid);
        assert_eq!(indicator_sma_10.value, 0.0);
        assert_eq!(indicator_sma_10.count, 0);
        assert!(!indicator_sma_10.initialized());
        assert!(!indicator_sma_10.has_inputs());
    }

    #[rstest]
    fn sma_update_raw_exact_period(indicator_sma_10: SimpleMovingAverage) {
        let mut sma = indicator_sma_10;
        for i in 1..=10 {
            sma.update_raw(f64::from(i));
        }
        assert!(sma.has_inputs());
        assert!(sma.initialized());
        assert_eq!(sma.count, 10);
        assert_eq!(sma.value, 5.5);
    }

    #[rstest]
    fn sma_reset_smoke(indicator_sma_10: SimpleMovingAverage) {
        let mut sma = indicator_sma_10;
        sma.update_raw(1.0);
        assert_eq!(sma.count, 1);
        sma.reset();
        assert_eq!(sma.count, 0);
        assert_eq!(sma.value, 0.0);
        assert!(!sma.initialized());
    }

    #[rstest]
    fn sma_handle_single_quote(indicator_sma_10: SimpleMovingAverage, stub_quote: QuoteTick) {
        let mut sma = indicator_sma_10;
        sma.handle_quote(&stub_quote);
        assert_eq!(sma.count, 1);
        assert_eq!(sma.value, 1501.0);
    }

    #[rstest]
    fn sma_handle_multiple_quotes(indicator_sma_10: SimpleMovingAverage) {
        let mut sma = indicator_sma_10;
        let q1 = stub_quote("1500.0", "1502.0");
        let q2 = stub_quote("1502.0", "1504.0");

        sma.handle_quote(&q1);
        sma.handle_quote(&q2);
        assert_eq!(sma.count, 2);
        assert_eq!(sma.value, 1502.0);
    }

    #[rstest]
    fn sma_handle_trade(indicator_sma_10: SimpleMovingAverage, stub_trade: TradeTick) {
        let mut sma = indicator_sma_10;
        sma.handle_trade(&stub_trade);
        assert_eq!(sma.count, 1);
        assert_eq!(sma.value, 1500.0);
    }

    #[rstest]
    #[case(1)]
    #[case(3)]
    #[case(5)]
    #[case(16)]
    fn count_progression_respects_period(#[case] period: usize) {
        let mut sma = SimpleMovingAverage::new(period, None);

        for i in 0..(period * 3) {
            sma.update_raw(i as f64);

            assert!(
                sma.count() <= period,
                "period={period}, step={i}, count={}",
                sma.count()
            );

            let expected = usize::min(i + 1, period);
            assert_eq!(
                sma.count(),
                expected,
                "period={period}, step={i}, expected={expected}, was={}",
                sma.count()
            );
        }
    }

    #[rstest]
    #[case(1)]
    #[case(4)]
    #[case(10)]
    fn count_after_reset_is_zero(#[case] period: usize) {
        let mut sma = SimpleMovingAverage::new(period, None);

        for i in 0..(period + 2) {
            sma.update_raw(i as f64);
        }
        assert_eq!(sma.count(), period, "pre-reset saturation failed");

        sma.reset();
        assert_eq!(sma.count(), 0, "count not reset to zero");
        assert_eq!(sma.value(), 0.0, "value not reset to zero");
        assert!(!sma.initialized(), "initialized flag not cleared");
    }

    #[rstest]
    fn count_edge_case_period_one() {
        let mut sma = SimpleMovingAverage::new(1, None);

        sma.update_raw(10.0);
        assert_eq!(sma.count(), 1);
        assert_eq!(sma.value(), 10.0);

        sma.update_raw(20.0);
        assert_eq!(sma.count(), 1, "count exceeded 1 with period==1");
        assert_eq!(sma.value(), 20.0, "value not equal to latest price");
    }

    #[rstest]
    fn sliding_window_correctness() {
        let mut sma = SimpleMovingAverage::new(3, None);

        let prices = [1.0, 2.0, 3.0, 4.0, 5.0];
        let expect_avg = [1.0, 1.5, 2.0, 3.0, 4.0];

        for (i, &p) in prices.iter().enumerate() {
            sma.update_raw(p);
            assert!(
                (sma.value() - expect_avg[i]).abs() < 1e-9,
                "step {i}: expected {}, was {}",
                expect_avg[i],
                sma.value()
            );
        }
    }

    #[rstest]
    #[case(2)]
    #[case(6)]
    fn initialized_transitions_with_count(#[case] period: usize) {
        let mut sma = SimpleMovingAverage::new(period, None);

        for i in 0..(period - 1) {
            sma.update_raw(i as f64);
            assert!(
                !sma.initialized(),
                "initialized early at i={i} (period={period})"
            );
        }

        sma.update_raw(42.0);
        assert_eq!(sma.count(), period);
        assert!(sma.initialized(), "initialized flag not set at period");
    }

    #[rstest]
    #[should_panic(expected = "period must be > 0")]
    fn sma_new_with_zero_period_panics() {
        let _ = SimpleMovingAverage::new(0, None);
    }

    #[rstest]
    fn sma_rolling_mean_exact_values() {
        let mut sma = SimpleMovingAverage::new(3, None);
        let inputs = [1.0, 2.0, 3.0, 4.0, 5.0];
        let expected = [1.0, 1.5, 2.0, 3.0, 4.0];

        for (&price, &exp_mean) in inputs.iter().zip(expected.iter()) {
            sma.update_raw(price);
            assert!(
                (sma.value() - exp_mean).abs() < 1e-12,
                "input={price}, expected={exp_mean}, was={}",
                sma.value()
            );
        }
    }

    #[rstest]
    fn sma_matches_reference_implementation() {
        const PERIOD: usize = 5;
        let mut sma = SimpleMovingAverage::new(PERIOD, None);
        let mut window: ArrayDeque<f64, PERIOD, Wrapping> = ArrayDeque::new();

        for step in 0..20 {
            let price = f64::from(step) * 10.0;
            sma.update_raw(price);

            if window.len() == PERIOD {
                window.pop_front();
            }
            let _ = window.push_back(price);

            let ref_mean: f64 = window.iter().sum::<f64>() / window.len() as f64;
            assert!(
                (sma.value() - ref_mean).abs() < 1e-12,
                "step={step}, expected={ref_mean}, was={}",
                sma.value()
            );
        }
    }

    #[rstest]
    #[case(f64::NAN)]
    #[case(f64::INFINITY)]
    #[case(f64::NEG_INFINITY)]
    fn sma_handles_bad_floats(#[case] bad: f64) {
        let mut sma = SimpleMovingAverage::new(3, None);
        sma.update_raw(1.0);
        sma.update_raw(bad);
        sma.update_raw(3.0);
        assert!(
            sma.value().is_nan() || !sma.value().is_finite(),
            "bad float not propagated"
        );
    }

    #[rstest]
    fn deque_and_count_always_match() {
        const PERIOD: usize = 8;
        let mut sma = SimpleMovingAverage::new(PERIOD, None);
        for i in 0..50 {
            sma.update_raw(f64::from(i));
            assert!(
                sma.buf.len() == sma.count,
                "buf.len() != count at step {i}: {} != {}",
                sma.buf.len(),
                sma.count
            );
        }
    }

    #[rstest]
    fn sma_multiple_resets() {
        let mut sma = SimpleMovingAverage::new(4, None);

        for cycle in 0..5 {
            for x in 0..4 {
                sma.update_raw(f64::from(x));
            }
            assert!(sma.initialized(), "cycle {cycle}: not initialized");
            sma.reset();
            assert_eq!(sma.count(), 0);
            assert_eq!(sma.value(), 0.0);
            assert!(!sma.initialized());
        }
    }

    #[rstest]
    fn sma_buffer_never_exceeds_capacity() {
        const PERIOD: usize = MAX_PERIOD;
        let mut sma = super::SimpleMovingAverage::new(PERIOD, None);

        for i in 0..(PERIOD * 2) {
            sma.update_raw(i as f64);

            assert!(
                sma.buf.len() <= PERIOD,
                "step {i}: buf.len()={}, exceeds PERIOD={PERIOD}",
                sma.buf.len(),
            );
        }
        assert!(
            sma.buf.is_full(),
            "buffer not reported as full after saturation"
        );
        assert_eq!(
            sma.count(),
            PERIOD,
            "count diverged from logical window length"
        );
    }

    #[rstest]
    fn sma_deque_eviction_order() {
        let mut sma = super::SimpleMovingAverage::new(3, None);

        sma.update_raw(1.0);
        sma.update_raw(2.0);
        sma.update_raw(3.0);
        sma.update_raw(4.0);

        assert_eq!(sma.buf.front().copied(), Some(2.0), "oldest element wrong");
        assert_eq!(sma.buf.back().copied(), Some(4.0), "newest element wrong");

        assert!(
            (sma.value() - 3.0).abs() < 1e-12,
            "unexpected mean after eviction: {}",
            sma.value()
        );
    }

    #[rstest]
    fn sma_sum_consistent_with_buffer() {
        const PERIOD: usize = 7;
        let mut sma = super::SimpleMovingAverage::new(PERIOD, None);

        for i in 0..40 {
            sma.update_raw(f64::from(i));

            let deque_sum: f64 = sma.buf.iter().copied().sum();
            assert!(
                (sma.sum - deque_sum).abs() < 1e-12,
                "step {i}: internal sum={} differs from buf sum={}",
                sma.sum,
                deque_sum
            );
        }
    }
}