nautilus_indicators/volatility/
vr.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::{Debug, Display};
17
18use nautilus_model::data::Bar;
19
20use crate::{average::MovingAverageType, indicator::Indicator, volatility::atr::AverageTrueRange};
21
22#[repr(C)]
23#[derive(Debug)]
24#[cfg_attr(
25    feature = "python",
26    pyo3::pyclass(module = "nautilus_trader.core.nautilus_pyo3.indicators", unsendable)
27)]
28pub struct VolatilityRatio {
29    pub fast_period: usize,
30    pub slow_period: usize,
31    pub ma_type: MovingAverageType,
32    pub use_previous: bool,
33    pub value_floor: f64,
34    pub value: f64,
35    pub initialized: bool,
36    has_inputs: bool,
37    atr_fast: AverageTrueRange,
38    atr_slow: AverageTrueRange,
39}
40
41impl Display for VolatilityRatio {
42    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
43        write!(
44            f,
45            "{}({},{},{})",
46            self.name(),
47            self.fast_period,
48            self.slow_period,
49            self.ma_type,
50        )
51    }
52}
53
54impl Indicator for VolatilityRatio {
55    fn name(&self) -> String {
56        stringify!(VolatilityRatio).to_string()
57    }
58
59    fn has_inputs(&self) -> bool {
60        self.has_inputs
61    }
62
63    fn initialized(&self) -> bool {
64        self.initialized
65    }
66
67    fn handle_bar(&mut self, bar: &Bar) {
68        self.update_raw((&bar.high).into(), (&bar.low).into(), (&bar.close).into());
69    }
70
71    fn reset(&mut self) {
72        self.atr_fast.reset();
73        self.atr_slow.reset();
74        self.value = 0.0;
75        self.initialized = false;
76        self.has_inputs = false;
77    }
78}
79
80impl VolatilityRatio {
81    /// Creates a new [`VolatilityRatio`] instance.
82    #[must_use]
83    pub fn new(
84        fast_period: usize,
85        slow_period: usize,
86        ma_type: Option<MovingAverageType>,
87        use_previous: Option<bool>,
88        value_floor: Option<f64>,
89    ) -> Self {
90        Self {
91            fast_period,
92            slow_period,
93            ma_type: ma_type.unwrap_or(MovingAverageType::Simple),
94            use_previous: use_previous.unwrap_or(false),
95            value_floor: value_floor.unwrap_or(0.0),
96            value: 0.0,
97            has_inputs: false,
98            initialized: false,
99            atr_fast: AverageTrueRange::new(fast_period, ma_type, use_previous, value_floor),
100            atr_slow: AverageTrueRange::new(slow_period, ma_type, use_previous, value_floor),
101        }
102    }
103
104    pub fn update_raw(&mut self, high: f64, low: f64, close: f64) {
105        self.atr_fast.update_raw(high, low, close);
106        self.atr_slow.update_raw(high, low, close);
107
108        if self.atr_fast.value > 0.0 {
109            self.value = self.atr_slow.value / self.atr_fast.value;
110        }
111
112        if !self.initialized {
113            self.has_inputs = true;
114
115            if self.atr_fast.initialized && self.atr_slow.initialized {
116                self.initialized = true;
117            }
118        }
119    }
120}
121
122////////////////////////////////////////////////////////////////////////////////
123// Tests
124////////////////////////////////////////////////////////////////////////////////
125#[cfg(test)]
126mod tests {
127    use rstest::rstest;
128
129    use super::*;
130    use crate::stubs::vr_10;
131
132    #[rstest]
133    fn test_name_returns_expected_string(vr_10: VolatilityRatio) {
134        assert_eq!(vr_10.name(), "VolatilityRatio");
135    }
136
137    #[rstest]
138    fn test_str_repr_returns_expected_string(vr_10: VolatilityRatio) {
139        assert_eq!(format!("{vr_10}"), "VolatilityRatio(10,10,SIMPLE)");
140    }
141
142    #[rstest]
143    fn test_period_returns_expected_value(vr_10: VolatilityRatio) {
144        assert_eq!(vr_10.fast_period, 10);
145        assert_eq!(vr_10.slow_period, 10);
146        assert!(!vr_10.use_previous);
147        assert_eq!(vr_10.value_floor, 10.0);
148    }
149
150    #[rstest]
151    fn test_initialized_without_inputs_returns_false(vr_10: VolatilityRatio) {
152        assert!(!vr_10.initialized());
153    }
154
155    #[rstest]
156    fn test_value_with_all_higher_inputs_returns_expected_value(mut vr_10: VolatilityRatio) {
157        let high_values = [
158            1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0,
159        ];
160        let low_values = [
161            0.9, 1.9, 2.9, 3.9, 4.9, 5.9, 6.9, 7.9, 8.9, 9.9, 10.1, 10.2, 10.3, 11.1, 11.4,
162        ];
163        let close_values = [
164            1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0,
165        ];
166
167        for i in 0..15 {
168            vr_10.update_raw(high_values[i], low_values[i], close_values[i]);
169        }
170
171        assert!(vr_10.initialized());
172        assert_eq!(vr_10.value, 1.0);
173    }
174
175    #[rstest]
176    fn test_reset_successfully_returns_indicator_to_fresh_state(mut vr_10: VolatilityRatio) {
177        vr_10.update_raw(1.00020, 1.00050, 1.00030);
178        vr_10.update_raw(1.00030, 1.00060, 1.00030);
179        vr_10.update_raw(1.00070, 1.00080, 1.00030);
180
181        vr_10.reset();
182
183        assert!(!vr_10.initialized());
184        assert_eq!(vr_10.value, 0.0);
185        assert!(!vr_10.initialized);
186        assert!(!vr_10.has_inputs);
187        assert_eq!(vr_10.atr_fast.value, 0.0);
188        assert_eq!(vr_10.atr_slow.value, 0.0);
189    }
190}