nautilus_indicators/momentum/
roc.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2025 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 arraydeque::{ArrayDeque, Wrapping};
19use nautilus_model::data::Bar;
20
21use crate::indicator::Indicator;
22
23const MAX_PERIOD: usize = 1_024;
24
25#[repr(C)]
26#[derive(Debug)]
27#[cfg_attr(
28    feature = "python",
29    pyo3::pyclass(module = "nautilus_trader.core.nautilus_pyo3.indicators")
30)]
31pub struct RateOfChange {
32    pub period: usize,
33    pub use_log: bool,
34    pub value: f64,
35    pub initialized: bool,
36    has_inputs: bool,
37    prices: ArrayDeque<f64, MAX_PERIOD, Wrapping>,
38}
39
40impl Display for RateOfChange {
41    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
42        write!(f, "{}({})", self.name(), self.period)
43    }
44}
45
46impl Indicator for RateOfChange {
47    fn name(&self) -> String {
48        stringify!(RateOfChange).to_string()
49    }
50
51    fn has_inputs(&self) -> bool {
52        self.has_inputs
53    }
54
55    fn initialized(&self) -> bool {
56        self.initialized
57    }
58
59    fn handle_bar(&mut self, bar: &Bar) {
60        self.update_raw((&bar.close).into());
61    }
62
63    fn reset(&mut self) {
64        self.prices.clear();
65        self.value = 0.0;
66        self.has_inputs = false;
67        self.initialized = false;
68    }
69}
70
71impl RateOfChange {
72    /// Creates a new [`RateOfChange`] instance.
73    ///
74    /// # Panics
75    ///
76    /// This function panics if:
77    /// - `period` is greater than `MAX_PERIOD`.
78    #[must_use]
79    pub fn new(period: usize, use_log: Option<bool>) -> Self {
80        assert!(
81            period <= MAX_PERIOD,
82            "RateOfChange: period {period} exceeds MAX_PERIOD ({MAX_PERIOD})"
83        );
84
85        Self {
86            period,
87            use_log: use_log.unwrap_or(false),
88            value: 0.0,
89            prices: ArrayDeque::new(),
90            has_inputs: false,
91            initialized: false,
92        }
93    }
94
95    pub fn update_raw(&mut self, price: f64) {
96        let _ = self.prices.push_back(price);
97
98        if !self.initialized {
99            self.has_inputs = true;
100            if self.prices.len() >= self.period {
101                self.initialized = true;
102            }
103        }
104
105        if let Some(first) = self.prices.front() {
106            if self.use_log {
107                self.value = (price / first).log10();
108            } else {
109                self.value = (price - first) / first;
110            }
111        }
112    }
113}
114
115#[cfg(test)]
116mod tests {
117    use rstest::rstest;
118
119    use super::*;
120    use crate::stubs::roc_10;
121
122    #[rstest]
123    fn test_name_returns_expected_string(roc_10: RateOfChange) {
124        assert_eq!(roc_10.name(), "RateOfChange");
125    }
126
127    #[rstest]
128    fn test_str_repr_returns_expected_string(roc_10: RateOfChange) {
129        assert_eq!(format!("{roc_10}"), "RateOfChange(10)");
130    }
131
132    #[rstest]
133    fn test_period_returns_expected_value(roc_10: RateOfChange) {
134        assert_eq!(roc_10.period, 10);
135        assert!(roc_10.use_log);
136    }
137
138    #[rstest]
139    fn test_initialized_without_inputs_returns_false(roc_10: RateOfChange) {
140        assert!(!roc_10.initialized());
141    }
142
143    #[rstest]
144    fn test_value_with_all_higher_inputs_returns_expected_value(mut roc_10: RateOfChange) {
145        let close_values = [
146            0.95, 1.95, 2.95, 3.95, 4.95, 5.95, 6.95, 7.95, 8.95, 9.95, 10.05, 10.15, 10.25, 11.05,
147            11.45,
148        ];
149
150        for close in &close_values {
151            roc_10.update_raw(*close);
152        }
153
154        assert!(roc_10.initialized());
155        assert_eq!(roc_10.value, 1.081_081_881_387_059);
156    }
157
158    #[rstest]
159    fn test_reset_successfully_returns_indicator_to_fresh_state(mut roc_10: RateOfChange) {
160        roc_10.update_raw(1.00020);
161        roc_10.update_raw(1.00030);
162        roc_10.update_raw(1.00070);
163
164        roc_10.reset();
165
166        assert!(!roc_10.initialized());
167        assert!(!roc_10.has_inputs);
168        assert_eq!(roc_10.value, 0.0);
169    }
170}