Skip to main content

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