Skip to main content

nautilus_indicators/momentum/
roc.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2026 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)]
31#[cfg_attr(
32    feature = "python",
33    pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.indicators")
34)]
35pub struct RateOfChange {
36    pub period: usize,
37    pub use_log: bool,
38    pub value: f64,
39    pub initialized: bool,
40    has_inputs: bool,
41    prices: ArrayDeque<f64, MAX_PERIOD, Wrapping>,
42}
43
44impl Display for RateOfChange {
45    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
46        write!(f, "{}({})", self.name(), self.period)
47    }
48}
49
50impl Indicator for RateOfChange {
51    fn name(&self) -> String {
52        stringify!(RateOfChange).to_string()
53    }
54
55    fn has_inputs(&self) -> bool {
56        self.has_inputs
57    }
58
59    fn initialized(&self) -> bool {
60        self.initialized
61    }
62
63    fn handle_bar(&mut self, bar: &Bar) {
64        self.update_raw((&bar.close).into());
65    }
66
67    fn reset(&mut self) {
68        self.prices.clear();
69        self.value = 0.0;
70        self.has_inputs = false;
71        self.initialized = false;
72    }
73}
74
75impl RateOfChange {
76    /// Creates a new [`RateOfChange`] instance.
77    ///
78    /// # Panics
79    ///
80    /// This function panics if:
81    /// - `period` is greater than `MAX_PERIOD`.
82    #[must_use]
83    pub fn new(period: usize, use_log: Option<bool>) -> Self {
84        assert!(
85            period <= MAX_PERIOD,
86            "RateOfChange: period {period} exceeds MAX_PERIOD ({MAX_PERIOD})"
87        );
88
89        Self {
90            period,
91            use_log: use_log.unwrap_or(false),
92            value: 0.0,
93            prices: ArrayDeque::new(),
94            has_inputs: false,
95            initialized: false,
96        }
97    }
98
99    pub fn update_raw(&mut self, price: f64) {
100        if self.prices.len() == self.period {
101            let _ = self.prices.pop_front();
102        }
103        let _ = self.prices.push_back(price);
104
105        if !self.initialized {
106            self.has_inputs = true;
107
108            if self.prices.len() >= self.period {
109                self.initialized = true;
110            }
111        }
112
113        if let Some(first) = self.prices.front() {
114            if self.use_log {
115                self.value = (price / first).ln();
116            } else {
117                self.value = (price - first) / first;
118            }
119        }
120    }
121}
122
123#[cfg(test)]
124mod tests {
125    use rstest::rstest;
126
127    use super::*;
128    use crate::stubs::roc_10;
129
130    #[rstest]
131    fn test_name_returns_expected_string(roc_10: RateOfChange) {
132        assert_eq!(roc_10.name(), "RateOfChange");
133    }
134
135    #[rstest]
136    fn test_str_repr_returns_expected_string(roc_10: RateOfChange) {
137        assert_eq!(format!("{roc_10}"), "RateOfChange(10)");
138    }
139
140    #[rstest]
141    fn test_period_returns_expected_value(roc_10: RateOfChange) {
142        assert_eq!(roc_10.period, 10);
143        assert!(roc_10.use_log);
144    }
145
146    #[rstest]
147    fn test_initialized_without_inputs_returns_false(roc_10: RateOfChange) {
148        assert!(!roc_10.initialized());
149    }
150
151    #[rstest]
152    fn test_value_with_all_higher_inputs_returns_expected_value(mut roc_10: RateOfChange) {
153        let close_values = [
154            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,
155            11.45,
156        ];
157
158        for close in &close_values {
159            roc_10.update_raw(*close);
160        }
161
162        assert!(roc_10.initialized());
163        assert_eq!(roc_10.value, 0.6545985104427102);
164    }
165
166    #[rstest]
167    fn test_reset_successfully_returns_indicator_to_fresh_state(mut roc_10: RateOfChange) {
168        roc_10.update_raw(1.00020);
169        roc_10.update_raw(1.00030);
170        roc_10.update_raw(1.00070);
171
172        roc_10.reset();
173
174        assert!(!roc_10.initialized());
175        assert!(!roc_10.has_inputs);
176        assert_eq!(roc_10.value, 0.0);
177    }
178
179    #[rstest]
180    fn test_value_respects_period_window() {
181        let mut roc = RateOfChange::new(3, Some(false));
182
183        roc.update_raw(100.0);
184        roc.update_raw(1.0);
185        roc.update_raw(2.0);
186        roc.update_raw(3.0);
187        roc.update_raw(4.0);
188
189        assert_eq!(roc.value, 1.0);
190    }
191}