nautilus_indicators/momentum/
vhf.rs1use std::{collections::VecDeque, fmt::Display};
17
18use nautilus_core::correctness::FAILED;
19use nautilus_model::data::{Bar, QuoteTick, TradeTick};
20
21use crate::{
22 average::{MovingAverageFactory, MovingAverageType},
23 indicator::{Indicator, MovingAverage},
24 support::MAX_PERIOD,
25};
26
27#[repr(C)]
29#[derive(Debug)]
30#[cfg_attr(
31 feature = "python",
32 pyo3::pyclass(module = "nautilus_trader.indicators", unsendable)
33)]
34#[cfg_attr(
35 feature = "python",
36 pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.indicators")
37)]
38pub struct VerticalHorizontalFilter {
39 pub period: usize,
40 pub ma_type: MovingAverageType,
41 pub value: f64,
42 pub initialized: bool,
43 ma: Box<dyn MovingAverage + Send + 'static>,
44 has_inputs: bool,
45 previous_close: f64,
46 prices: VecDeque<f64>,
47}
48
49impl Display for VerticalHorizontalFilter {
50 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
51 write!(f, "{}({},{})", self.name(), self.period, self.ma_type)
52 }
53}
54
55impl Indicator for VerticalHorizontalFilter {
56 fn name(&self) -> String {
57 stringify!(VerticalHorizontalFilter).to_string()
58 }
59
60 fn has_inputs(&self) -> bool {
61 self.has_inputs
62 }
63
64 fn initialized(&self) -> bool {
65 self.initialized
66 }
67
68 fn handle_quote(&mut self, _quote: &QuoteTick) -> anyhow::Result<()> {
69 Ok(())
70 }
71
72 fn handle_trade(&mut self, _trade: &TradeTick) {}
73
74 fn handle_bar(&mut self, bar: &Bar) {
75 self.update_raw((&bar.close).into());
76 }
77
78 fn reset(&mut self) {
79 self.prices.clear();
80 self.ma.reset();
81 self.previous_close = 0.0;
82 self.value = 0.0;
83 self.has_inputs = false;
84 self.initialized = false;
85 }
86}
87
88impl VerticalHorizontalFilter {
89 #[must_use]
97 pub fn new(period: usize, ma_type: Option<MovingAverageType>) -> Self {
98 Self::new_checked(period, ma_type).expect(FAILED)
99 }
100
101 pub(crate) fn new_checked(
102 period: usize,
103 ma_type: Option<MovingAverageType>,
104 ) -> anyhow::Result<Self> {
105 anyhow::ensure!(
106 period > 0 && period <= MAX_PERIOD,
107 "VerticalHorizontalFilter: period {period} exceeds MAX_PERIOD ({MAX_PERIOD})"
108 );
109
110 let ma_kind = ma_type.unwrap_or(MovingAverageType::Simple);
111
112 Ok(Self {
113 period,
114 ma_type: ma_kind,
115 value: 0.0,
116 previous_close: 0.0,
117 ma: MovingAverageFactory::create(ma_kind, period),
118 has_inputs: false,
119 initialized: false,
120 prices: VecDeque::with_capacity(period),
121 })
122 }
123
124 pub fn update_raw(&mut self, close: f64) {
125 if !close.is_finite() {
126 return;
127 }
128
129 if !self.has_inputs {
130 self.has_inputs = true;
133 self.previous_close = close;
134 self.prices.push_back(close);
135 return;
136 }
137
138 if self.prices.len() == self.period {
139 let _ = self.prices.pop_front();
140 }
141
142 self.prices.push_back(close);
143
144 let max_price = self
145 .prices
146 .iter()
147 .copied()
148 .fold(f64::NEG_INFINITY, f64::max);
149
150 let min_price = self.prices.iter().copied().fold(f64::INFINITY, f64::min);
151
152 self.ma.update_raw(f64::abs(close - self.previous_close));
153
154 if self.ma.initialized() {
155 if self.ma.value() == 0.0 {
158 self.value = 0.0;
159 } else {
160 self.value = f64::abs(max_price - min_price) / self.period as f64 / self.ma.value();
161 }
162 }
163
164 self.previous_close = close;
165 self.check_initialized();
166 }
167
168 pub fn check_initialized(&mut self) {
169 if !self.initialized {
170 self.has_inputs = true;
171
172 if self.ma.initialized() {
173 self.initialized = true;
174 }
175 }
176 }
177}
178
179#[cfg(test)]
180mod tests {
181 use nautilus_model::data::Bar;
182 use rstest::rstest;
183
184 use crate::{indicator::Indicator, momentum::vhf::VerticalHorizontalFilter, stubs::*};
185
186 #[rstest]
187 fn test_dema_initialized(vhf_10: VerticalHorizontalFilter) {
188 let display_str = format!("{vhf_10}");
189 assert_eq!(display_str, "VerticalHorizontalFilter(10,SIMPLE)");
190 assert_eq!(vhf_10.period, 10);
191 assert!(!vhf_10.initialized);
192 assert!(!vhf_10.has_inputs);
193 }
194
195 #[rstest]
196 fn test_value_with_one_input(mut vhf_10: VerticalHorizontalFilter) {
197 vhf_10.update_raw(1.0);
198 assert_eq!(vhf_10.value, 0.0);
199 }
200
201 #[rstest]
202 fn test_value_with_three_inputs(mut vhf_10: VerticalHorizontalFilter) {
203 vhf_10.update_raw(1.0);
204 vhf_10.update_raw(2.0);
205 vhf_10.update_raw(3.0);
206 assert_eq!(vhf_10.value, 0.0);
207 }
208
209 #[rstest]
210 fn test_value_with_ten_inputs(mut vhf_10: VerticalHorizontalFilter) {
211 vhf_10.update_raw(1.00000);
212 vhf_10.update_raw(1.00010);
213 vhf_10.update_raw(1.00020);
214 vhf_10.update_raw(1.00030);
215 vhf_10.update_raw(1.00040);
216 vhf_10.update_raw(1.00050);
217 vhf_10.update_raw(1.00040);
218 vhf_10.update_raw(1.00030);
219 vhf_10.update_raw(1.00020);
220 vhf_10.update_raw(1.00010);
221 vhf_10.update_raw(1.00000);
222 assert_eq!(vhf_10.value, 0.5);
223 }
224
225 #[rstest]
226 fn test_initialized_with_required_input(mut vhf_10: VerticalHorizontalFilter) {
227 for i in 1..=10 {
230 vhf_10.update_raw(f64::from(i));
231 assert!(!vhf_10.initialized);
232 }
233 vhf_10.update_raw(11.0);
234 assert!(vhf_10.initialized);
235 }
236
237 #[rstest]
238 fn test_handle_bar(mut vhf_10: VerticalHorizontalFilter, bar_ethusdt_binance_minute_bid: Bar) {
239 vhf_10.handle_bar(&bar_ethusdt_binance_minute_bid);
240 assert_eq!(vhf_10.value, 0.0);
241 assert!(vhf_10.has_inputs);
242 assert!(!vhf_10.initialized);
243 }
244
245 #[rstest]
246 fn test_reset(mut vhf_10: VerticalHorizontalFilter) {
247 vhf_10.update_raw(1.0);
248 assert_eq!(vhf_10.prices.len(), 1);
249 vhf_10.reset();
250 assert_eq!(vhf_10.value, 0.0);
251 assert_eq!(vhf_10.prices.len(), 0);
252 assert!(!vhf_10.has_inputs);
253 assert!(!vhf_10.initialized);
254 }
255
256 #[rstest]
257 fn test_value_respects_period_window() {
258 let mut vhf = VerticalHorizontalFilter::new(3, None);
259
260 vhf.update_raw(100.0); vhf.update_raw(1.0);
262 vhf.update_raw(2.0);
263 vhf.update_raw(3.0);
264 vhf.update_raw(4.0);
265
266 assert_eq!(vhf.value, 2.0 / 3.0);
269 }
270
271 #[rstest]
272 fn test_value_is_zero_for_flat_prices(mut vhf_10: VerticalHorizontalFilter) {
273 for _ in 0..20 {
274 vhf_10.update_raw(100.0);
275 }
276
277 assert!(vhf_10.initialized);
278 assert_eq!(vhf_10.value, 0.0);
279 }
280}