nautilus_indicators/momentum/
roc.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2025 Posei Systems Pty Ltd. All rights reserved.
3//  https://poseitrader.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 = "posei_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////////////////////////////////////////////////////////////////////////////////
116// Tests
117////////////////////////////////////////////////////////////////////////////////
118#[cfg(test)]
119mod tests {
120    use rstest::rstest;
121
122    use super::*;
123    use crate::stubs::roc_10;
124
125    #[rstest]
126    fn test_name_returns_expected_string(roc_10: RateOfChange) {
127        assert_eq!(roc_10.name(), "RateOfChange");
128    }
129
130    #[rstest]
131    fn test_str_repr_returns_expected_string(roc_10: RateOfChange) {
132        assert_eq!(format!("{roc_10}"), "RateOfChange(10)");
133    }
134
135    #[rstest]
136    fn test_period_returns_expected_value(roc_10: RateOfChange) {
137        assert_eq!(roc_10.period, 10);
138        assert!(roc_10.use_log);
139    }
140
141    #[rstest]
142    fn test_initialized_without_inputs_returns_false(roc_10: RateOfChange) {
143        assert!(!roc_10.initialized());
144    }
145
146    #[rstest]
147    fn test_value_with_all_higher_inputs_returns_expected_value(mut roc_10: RateOfChange) {
148        let close_values = [
149            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,
150            11.45,
151        ];
152
153        for close in &close_values {
154            roc_10.update_raw(*close);
155        }
156
157        assert!(roc_10.initialized());
158        assert_eq!(roc_10.value, 1.081_081_881_387_059);
159    }
160
161    #[rstest]
162    fn test_reset_successfully_returns_indicator_to_fresh_state(mut roc_10: RateOfChange) {
163        roc_10.update_raw(1.00020);
164        roc_10.update_raw(1.00030);
165        roc_10.update_raw(1.00070);
166
167        roc_10.reset();
168
169        assert!(!roc_10.initialized());
170        assert!(!roc_10.has_inputs);
171        assert_eq!(roc_10.value, 0.0);
172    }
173}