nautilus-indicators 0.63.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
// -------------------------------------------------------------------------------------------------
//  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 nautilus_core::correctness::{FAILED, check_predicate_true};
use nautilus_model::{
    data::{Bar, QuoteTick, TradeTick},
    enums::PriceType,
};

use crate::{
    indicator::{Indicator, MovingAverage},
    ratio::efficiency_ratio::EfficiencyRatio,
};

/// An indicator which calculates an adaptive moving average (AMA) across a
/// rolling window. Developed by Perry Kaufman, the AMA is a moving average
/// designed to account for market noise and volatility. The AMA will closely
/// follow prices when the price swings are relatively small and the noise is
/// low. The AMA will increase lag when the price swings increase.
#[repr(C)]
#[derive(Debug)]
#[cfg_attr(
    feature = "python",
    pyo3::pyclass(module = "nautilus_trader.indicators")
)]
#[cfg_attr(
    feature = "python",
    pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.indicators")
)]
pub struct AdaptiveMovingAverage {
    /// The period for the internal `EfficiencyRatio` indicator (>= 2).
    pub period_efficiency_ratio: usize,
    /// The period for the fast smoothing constant (> 0).
    pub period_fast: usize,
    /// The period for the slow smoothing constant (> `period_fast`).
    pub period_slow: usize,
    /// The price type used for calculations.
    pub price_type: PriceType,
    /// The last indicator value.
    pub value: f64,
    /// The input count for the indicator.
    pub count: usize,
    pub initialized: bool,
    has_inputs: bool,
    efficiency_ratio: EfficiencyRatio,
    prior_value: Option<f64>,
    alpha_fast: f64,
    alpha_slow: f64,
}

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

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

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

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

    fn handle_quote(&mut self, quote: &QuoteTick) -> anyhow::Result<()> {
        self.update_raw(quote.extract_price(self.price_type)?.into());
        Ok(())
    }

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

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

    fn reset(&mut self) {
        self.value = 0.0;
        self.prior_value = None;
        self.count = 0;
        self.has_inputs = false;
        self.initialized = false;
        self.efficiency_ratio.reset();
    }
}

impl AdaptiveMovingAverage {
    /// Creates a new [`AdaptiveMovingAverage`] instance.
    ///
    /// # Panics
    ///
    /// This function panics if:
    /// - `period_efficiency_ratio` is less than 2 or its rolling-window storage
    ///   cannot be reserved.
    /// - `period_fast` == 0.
    /// - `period_slow` == 0.
    /// - `period_slow` == `usize::MAX`.
    /// - `period_slow` ≤ `period_fast`.
    #[must_use]
    pub fn new(
        period_efficiency_ratio: usize,
        period_fast: usize,
        period_slow: usize,
        price_type: Option<PriceType>,
    ) -> Self {
        Self::new_checked(
            period_efficiency_ratio,
            period_fast,
            period_slow,
            price_type,
        )
        .expect(FAILED)
    }

    pub(crate) fn new_checked(
        period_efficiency_ratio: usize,
        period_fast: usize,
        period_slow: usize,
        price_type: Option<PriceType>,
    ) -> anyhow::Result<Self> {
        check_predicate_true(period_fast > 0, "`period_fast` must be positive")?;
        check_predicate_true(period_slow > 0, "`period_slow` must be positive")?;
        check_predicate_true(
            period_slow < usize::MAX,
            "`period_slow` must be less than `usize::MAX`",
        )?;
        check_predicate_true(
            period_slow > period_fast,
            "`period_slow` must be greater than `period_fast`",
        )?;

        let efficiency_ratio = EfficiencyRatio::new_checked(period_efficiency_ratio, price_type)?;

        Ok(Self {
            period_efficiency_ratio,
            period_fast,
            period_slow,
            price_type: price_type.unwrap_or(PriceType::Last),
            value: 0.0,
            count: 0,
            alpha_fast: 2.0 / (period_fast + 1) as f64,
            alpha_slow: 2.0 / (period_slow + 1) as f64,
            prior_value: None,
            has_inputs: false,
            initialized: false,
            efficiency_ratio,
        })
    }

    #[must_use]
    pub fn alpha_diff(&self) -> f64 {
        self.alpha_fast - self.alpha_slow
    }

    #[must_use]
    pub const fn alpha_fast(&self) -> f64 {
        self.alpha_fast
    }

    #[must_use]
    pub const fn alpha_slow(&self) -> f64 {
        self.alpha_slow
    }

    pub fn reset(&mut self) {
        Indicator::reset(self);
    }
}

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

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

    fn update_raw(&mut self, value: f64) {
        self.count += 1;

        if !self.has_inputs {
            self.prior_value = Some(value);
            self.efficiency_ratio.update_raw(value);
            self.value = value;
            self.has_inputs = true;
            return;
        }

        self.efficiency_ratio.update_raw(value);
        self.prior_value = Some(self.value);

        // Calculate the smoothing constant
        let smoothing_constant = self
            .efficiency_ratio
            .value
            .mul_add(self.alpha_diff(), self.alpha_slow)
            .powi(2);

        // Calculate the AMA
        // TODO: Remove unwraps
        self.value = smoothing_constant
            .mul_add(value - self.prior_value.unwrap(), self.prior_value.unwrap());

        if self.efficiency_ratio.initialized() {
            self.initialized = true;
        }
    }
}

#[cfg(test)]
mod tests {
    use nautilus_model::data::{Bar, QuoteTick, TradeTick};
    use rstest::rstest;

    use crate::{
        average::ama::AdaptiveMovingAverage,
        indicator::{Indicator, MovingAverage},
        stubs::*,
        testing::assert_approx_equal,
    };

    #[rstest]
    fn test_ama_initialized(indicator_ama_10: AdaptiveMovingAverage) {
        let display_str = format!("{indicator_ama_10}");
        assert_eq!(display_str, "AdaptiveMovingAverage(10,2,30)");
        assert_eq!(indicator_ama_10.name(), "AdaptiveMovingAverage");
        assert!(!indicator_ama_10.has_inputs());
        assert!(!indicator_ama_10.initialized());
    }

    #[rstest]
    fn test_value_with_one_input(mut indicator_ama_10: AdaptiveMovingAverage) {
        indicator_ama_10.update_raw(1.0);
        assert_eq!(indicator_ama_10.value, 1.0);
    }

    #[rstest]
    fn test_value_with_two_inputs(mut indicator_ama_10: AdaptiveMovingAverage) {
        indicator_ama_10.update_raw(1.0);
        indicator_ama_10.update_raw(2.0);
        assert_approx_equal(indicator_ama_10.value, 1.44444444444);
    }

    #[rstest]
    fn test_value_with_three_inputs(mut indicator_ama_10: AdaptiveMovingAverage) {
        indicator_ama_10.update_raw(1.0);
        indicator_ama_10.update_raw(2.0);
        indicator_ama_10.update_raw(3.0);
        assert_approx_equal(indicator_ama_10.value, 2.13580246914);
    }

    #[rstest]
    #[case::inherent(AdaptiveMovingAverage::reset)]
    #[case::indicator(<AdaptiveMovingAverage as Indicator>::reset)]
    fn test_reset(
        #[case] reset: fn(&mut AdaptiveMovingAverage),
        mut indicator_ama_10: AdaptiveMovingAverage,
    ) {
        for value in 1..=10 {
            indicator_ama_10.update_raw(f64::from(value));
        }
        assert!(indicator_ama_10.initialized);

        reset(&mut indicator_ama_10);

        assert!(!indicator_ama_10.initialized);
        assert!(!indicator_ama_10.has_inputs);
        assert_eq!(indicator_ama_10.value, 0.0);
        assert_eq!(indicator_ama_10.prior_value, None);
        assert_eq!(indicator_ama_10.count, 0);
        assert!(!indicator_ama_10.efficiency_ratio.has_inputs());
        assert!(!indicator_ama_10.efficiency_ratio.initialized());
        assert_eq!(indicator_ama_10.efficiency_ratio.value, 0.0);
    }

    #[rstest]
    fn test_initialized_after_correct_number_of_input(indicator_ama_10: AdaptiveMovingAverage) {
        let mut ama = indicator_ama_10;
        for _ in 0..9 {
            ama.update_raw(1.0);
        }
        assert!(!ama.initialized);
        ama.update_raw(1.0);
        assert!(ama.initialized);
    }

    #[rstest]
    fn test_count_increments(mut indicator_ama_10: AdaptiveMovingAverage) {
        assert_eq!(indicator_ama_10.count(), 0);
        indicator_ama_10.update_raw(1.0);
        assert_eq!(indicator_ama_10.count(), 1);
        indicator_ama_10.update_raw(2.0);
        indicator_ama_10.update_raw(3.0);
        assert_eq!(indicator_ama_10.count(), 3);
    }

    #[rstest]
    fn test_handle_quote_tick(mut indicator_ama_10: AdaptiveMovingAverage, stub_quote: QuoteTick) {
        indicator_ama_10.handle_quote(&stub_quote).unwrap();
        assert!(indicator_ama_10.has_inputs);
        assert!(!indicator_ama_10.initialized);
        assert_eq!(indicator_ama_10.value, 1501.0);
        assert_eq!(indicator_ama_10.count(), 1);
    }

    #[rstest]
    fn test_handle_trade_tick_update(
        mut indicator_ama_10: AdaptiveMovingAverage,
        stub_trade: TradeTick,
    ) {
        indicator_ama_10.handle_trade(&stub_trade);
        assert!(indicator_ama_10.has_inputs);
        assert!(!indicator_ama_10.initialized);
        assert_eq!(indicator_ama_10.value, 1500.0);
        assert_eq!(indicator_ama_10.count(), 1);
    }

    #[rstest]
    fn handle_handle_bar(
        mut indicator_ama_10: AdaptiveMovingAverage,
        bar_ethusdt_binance_minute_bid: Bar,
    ) {
        indicator_ama_10.handle_bar(&bar_ethusdt_binance_minute_bid);
        assert!(indicator_ama_10.has_inputs);
        assert!(!indicator_ama_10.initialized);
        assert_eq!(indicator_ama_10.value, 1522.0);
        assert_eq!(indicator_ama_10.count(), 1);
    }

    #[rstest]
    fn new_panics_when_slow_not_greater_than_fast() {
        let result = std::panic::catch_unwind(|| {
            let _ = AdaptiveMovingAverage::new(10, 20, 20, None);
        });
        assert!(result.is_err());
    }

    #[rstest]
    #[case(0)]
    #[case(1)]
    #[should_panic(expected = "`period` must be at least 2")]
    fn new_panics_when_er_period_is_below_two(#[case] period: usize) {
        let _ = AdaptiveMovingAverage::new(period, 2, 30, None);
    }

    #[rstest]
    fn new_panics_when_fast_is_zero() {
        let result = std::panic::catch_unwind(|| {
            let _ = AdaptiveMovingAverage::new(10, 0, 30, None);
        });
        assert!(result.is_err());
    }

    #[rstest]
    fn new_panics_when_slow_is_zero() {
        let result = std::panic::catch_unwind(|| {
            let _ = AdaptiveMovingAverage::new(10, 2, 0, None);
        });
        assert!(result.is_err());
    }

    #[rstest]
    fn new_panics_when_slow_less_than_fast() {
        let result = std::panic::catch_unwind(|| {
            let _ = AdaptiveMovingAverage::new(10, 20, 5, None);
        });
        assert!(result.is_err());
    }

    #[rstest]
    fn new_checked_rejects_slow_period_max() {
        let error =
            AdaptiveMovingAverage::new_checked(10, usize::MAX - 1, usize::MAX, None).unwrap_err();

        assert_eq!(
            error.to_string(),
            "`period_slow` must be less than `usize::MAX`",
        );
    }
}