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#[cfg(test)]
123mod tests {
124    use rstest::rstest;
125
126    use super::*;
127    use crate::stubs::vr_10;
128
129    #[rstest]
130    fn test_name_returns_expected_string(vr_10: VolatilityRatio) {
131        assert_eq!(vr_10.name(), "VolatilityRatio");
132    }
133
134    #[rstest]
135    fn test_str_repr_returns_expected_string(vr_10: VolatilityRatio) {
136        assert_eq!(format!("{vr_10}"), "VolatilityRatio(10,10,SIMPLE)");
137    }
138
139    #[rstest]
140    fn test_period_returns_expected_value(vr_10: VolatilityRatio) {
141        assert_eq!(vr_10.fast_period, 10);
142        assert_eq!(vr_10.slow_period, 10);
143        assert!(!vr_10.use_previous);
144        assert_eq!(vr_10.value_floor, 10.0);
145    }
146
147    #[rstest]
148    fn test_initialized_without_inputs_returns_false(vr_10: VolatilityRatio) {
149        assert!(!vr_10.initialized());
150    }
151
152    #[rstest]
153    fn test_value_with_all_higher_inputs_returns_expected_value(mut vr_10: VolatilityRatio) {
154        let high_values = [
155            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,
156        ];
157        let low_values = [
158            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,
159        ];
160        let close_values = [
161            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,
162        ];
163
164        for i in 0..15 {
165            vr_10.update_raw(high_values[i], low_values[i], close_values[i]);
166        }
167
168        assert!(vr_10.initialized());
169        assert_eq!(vr_10.value, 1.0);
170    }
171
172    #[rstest]
173    fn test_reset_successfully_returns_indicator_to_fresh_state(mut vr_10: VolatilityRatio) {
174        vr_10.update_raw(1.00020, 1.00050, 1.00030);
175        vr_10.update_raw(1.00030, 1.00060, 1.00030);
176        vr_10.update_raw(1.00070, 1.00080, 1.00030);
177
178        vr_10.reset();
179
180        assert!(!vr_10.initialized());
181        assert_eq!(vr_10.value, 0.0);
182        assert!(!vr_10.initialized);
183        assert!(!vr_10.has_inputs);
184        assert_eq!(vr_10.atr_fast.value, 0.0);
185        assert_eq!(vr_10.atr_slow.value, 0.0);
186    }
187}