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, QuoteTick, TradeTick};
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.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_quote(&mut self, _quote: &QuoteTick) -> anyhow::Result<()> {
64        Ok(())
65    }
66
67    fn handle_trade(&mut self, _trade: &TradeTick) {}
68
69    fn handle_bar(&mut self, bar: &Bar) {
70        self.update_raw((&bar.close).into());
71    }
72
73    fn reset(&mut self) {
74        self.prices.clear();
75        self.value = 0.0;
76        self.has_inputs = false;
77        self.initialized = false;
78    }
79}
80
81impl RateOfChange {
82    /// Creates a new [`RateOfChange`] instance.
83    ///
84    /// # Panics
85    ///
86    /// This function panics if:
87    /// - `period` is greater than `MAX_PERIOD`.
88    #[must_use]
89    pub fn new(period: usize, use_log: Option<bool>) -> Self {
90        assert!(
91            period <= MAX_PERIOD,
92            "RateOfChange: period {period} exceeds MAX_PERIOD ({MAX_PERIOD})"
93        );
94
95        Self {
96            period,
97            use_log: use_log.unwrap_or(false),
98            value: 0.0,
99            prices: ArrayDeque::new(),
100            has_inputs: false,
101            initialized: false,
102        }
103    }
104
105    pub fn update_raw(&mut self, price: f64) {
106        if self.prices.len() == self.period {
107            let _ = self.prices.pop_front();
108        }
109        let _ = self.prices.push_back(price);
110
111        if !self.initialized {
112            self.has_inputs = true;
113
114            if self.prices.len() >= self.period {
115                self.initialized = true;
116            }
117        }
118
119        if let Some(first) = self.prices.front() {
120            if self.use_log {
121                self.value = (price / first).ln();
122            } else {
123                self.value = (price - first) / first;
124            }
125        }
126    }
127}
128
129#[cfg(test)]
130mod tests {
131    use rstest::rstest;
132
133    use super::*;
134    use crate::{stubs::roc_10, testing::assert_approx_equal};
135
136    #[rstest]
137    fn test_name_returns_expected_string(roc_10: RateOfChange) {
138        assert_eq!(roc_10.name(), "RateOfChange");
139    }
140
141    #[rstest]
142    fn test_str_repr_returns_expected_string(roc_10: RateOfChange) {
143        assert_eq!(format!("{roc_10}"), "RateOfChange(10)");
144    }
145
146    #[rstest]
147    fn test_period_returns_expected_value(roc_10: RateOfChange) {
148        assert_eq!(roc_10.period, 10);
149        assert!(roc_10.use_log);
150    }
151
152    #[rstest]
153    fn test_initialized_without_inputs_returns_false(roc_10: RateOfChange) {
154        assert!(!roc_10.initialized());
155    }
156
157    #[rstest]
158    fn test_value_with_all_higher_inputs_returns_expected_value(mut roc_10: RateOfChange) {
159        let close_values = [
160            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,
161            11.45,
162        ];
163
164        for close in &close_values {
165            roc_10.update_raw(*close);
166        }
167
168        assert!(roc_10.initialized());
169        assert_approx_equal(roc_10.value, 0.654598510443);
170    }
171
172    #[rstest]
173    fn test_reset_successfully_returns_indicator_to_fresh_state(mut roc_10: RateOfChange) {
174        roc_10.update_raw(1.00020);
175        roc_10.update_raw(1.00030);
176        roc_10.update_raw(1.00070);
177
178        roc_10.reset();
179
180        assert!(!roc_10.initialized());
181        assert!(!roc_10.has_inputs);
182        assert_eq!(roc_10.value, 0.0);
183    }
184
185    #[rstest]
186    fn test_value_respects_period_window() {
187        let mut roc = RateOfChange::new(3, Some(false));
188
189        roc.update_raw(100.0);
190        roc.update_raw(1.0);
191        roc.update_raw(2.0);
192        roc.update_raw(3.0);
193        roc.update_raw(4.0);
194
195        assert_eq!(roc.value, 1.0);
196    }
197}