nautilus_indicators/average/
hma.rs1use std::fmt::{Display, Formatter};
17
18use nautilus_model::{
19 data::{Bar, QuoteTick, TradeTick},
20 enums::PriceType,
21};
22
23use crate::{
24 average::wma::WeightedMovingAverage,
25 indicator::{Indicator, MovingAverage},
26};
27
28#[repr(C)]
32#[derive(Debug)]
33#[cfg_attr(
34 feature = "python",
35 pyo3::pyclass(module = "nautilus_trader.core.nautilus_pyo3.indicators")
36)]
37pub struct HullMovingAverage {
38 pub period: usize,
39 pub price_type: PriceType,
40 pub value: f64,
41 pub count: usize,
42 pub initialized: bool,
43 has_inputs: bool,
44 ma1: WeightedMovingAverage,
45 ma2: WeightedMovingAverage,
46 ma3: WeightedMovingAverage,
47}
48
49impl Display for HullMovingAverage {
50 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
51 write!(f, "{}({})", self.name(), self.period)
52 }
53}
54
55impl Indicator for HullMovingAverage {
56 fn name(&self) -> String {
57 stringify!(HullMovingAverage).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) {
69 self.update_raw(quote.extract_price(self.price_type).into());
70 }
71
72 fn handle_trade(&mut self, trade: &TradeTick) {
73 self.update_raw((&trade.price).into());
74 }
75
76 fn handle_bar(&mut self, bar: &Bar) {
77 self.update_raw((&bar.close).into());
78 }
79
80 fn reset(&mut self) {
81 self.value = 0.0;
82 self.ma1.reset();
83 self.ma2.reset();
84 self.ma3.reset();
85 self.count = 0;
86 self.has_inputs = false;
87 self.initialized = false;
88 }
89}
90
91fn get_weights(size: usize) -> Vec<f64> {
92 let mut w: Vec<f64> = (1..=size).map(|x| x as f64).collect();
93 let divisor: f64 = w.iter().sum();
94 for v in &mut w {
95 *v /= divisor;
96 }
97 w
98}
99
100impl HullMovingAverage {
101 #[must_use]
107 pub fn new(period: usize, price_type: Option<PriceType>) -> Self {
108 assert!(
109 period > 0,
110 "HullMovingAverage: period must be > 0 (received {period})"
111 );
112
113 let half = usize::max(1, period / 2);
114 let root = usize::max(1, (period as f64).sqrt() as usize);
115
116 let pt = price_type.unwrap_or(PriceType::Last);
117
118 let ma1 = WeightedMovingAverage::new(half, get_weights(half), Some(pt));
119 let ma2 = WeightedMovingAverage::new(period, get_weights(period), Some(pt));
120 let ma3 = WeightedMovingAverage::new(root, get_weights(root), Some(pt));
121
122 Self {
123 period,
124 price_type: pt,
125 value: 0.0,
126 count: 0,
127 has_inputs: false,
128 initialized: false,
129 ma1,
130 ma2,
131 ma3,
132 }
133 }
134}
135
136impl MovingAverage for HullMovingAverage {
137 fn value(&self) -> f64 {
138 self.value
139 }
140
141 fn count(&self) -> usize {
142 self.count
143 }
144
145 fn update_raw(&mut self, value: f64) {
146 if !self.has_inputs {
147 self.has_inputs = true;
148 self.value = value;
149 }
150
151 self.ma1.update_raw(value);
152 self.ma2.update_raw(value);
153 self.ma3
154 .update_raw(2.0f64.mul_add(self.ma1.value, -self.ma2.value));
155
156 self.value = self.ma3.value;
157 self.count += 1;
158
159 if !self.initialized && self.count >= self.period {
160 self.initialized = true;
161 }
162 }
163}
164
165#[cfg(test)]
166mod tests {
167 use nautilus_model::{
168 data::{Bar, QuoteTick, TradeTick},
169 enums::PriceType,
170 };
171 use rstest::rstest;
172
173 use crate::{
174 average::hma::HullMovingAverage,
175 indicator::{Indicator, MovingAverage},
176 stubs::*,
177 };
178
179 #[rstest]
180 fn test_hma_initialized(indicator_hma_10: HullMovingAverage) {
181 let display_str = format!("{indicator_hma_10}");
182 assert_eq!(display_str, "HullMovingAverage(10)");
183 assert_eq!(indicator_hma_10.period, 10);
184 assert!(!indicator_hma_10.initialized);
185 assert!(!indicator_hma_10.has_inputs);
186 }
187
188 #[rstest]
189 fn test_initialized_with_required_input(mut indicator_hma_10: HullMovingAverage) {
190 for i in 1..10 {
191 indicator_hma_10.update_raw(f64::from(i));
192 }
193 assert!(!indicator_hma_10.initialized);
194 indicator_hma_10.update_raw(10.0);
195 assert!(indicator_hma_10.initialized);
196 }
197
198 #[rstest]
199 fn test_value_with_one_input(mut indicator_hma_10: HullMovingAverage) {
200 indicator_hma_10.update_raw(1.0);
201 assert_eq!(indicator_hma_10.value, 1.0);
202 }
203
204 #[rstest]
205 fn test_value_with_three_inputs(mut indicator_hma_10: HullMovingAverage) {
206 indicator_hma_10.update_raw(1.0);
207 indicator_hma_10.update_raw(2.0);
208 indicator_hma_10.update_raw(3.0);
209 assert_eq!(indicator_hma_10.value, 1.824_561_403_508_772);
210 }
211
212 #[rstest]
213 fn test_value_with_ten_inputs(mut indicator_hma_10: HullMovingAverage) {
214 indicator_hma_10.update_raw(1.00000);
215 indicator_hma_10.update_raw(1.00010);
216 indicator_hma_10.update_raw(1.00020);
217 indicator_hma_10.update_raw(1.00030);
218 indicator_hma_10.update_raw(1.00040);
219 indicator_hma_10.update_raw(1.00050);
220 indicator_hma_10.update_raw(1.00040);
221 indicator_hma_10.update_raw(1.00030);
222 indicator_hma_10.update_raw(1.00020);
223 indicator_hma_10.update_raw(1.00010);
224 indicator_hma_10.update_raw(1.00000);
225 assert_eq!(indicator_hma_10.value, 1.000_140_392_817_059_8);
226 }
227
228 #[rstest]
229 fn test_handle_quote_tick(mut indicator_hma_10: HullMovingAverage, stub_quote: QuoteTick) {
230 indicator_hma_10.handle_quote(&stub_quote);
231 assert_eq!(indicator_hma_10.value, 1501.0);
232 }
233
234 #[rstest]
235 fn test_handle_trade_tick(mut indicator_hma_10: HullMovingAverage, stub_trade: TradeTick) {
236 indicator_hma_10.handle_trade(&stub_trade);
237 assert_eq!(indicator_hma_10.value, 1500.0);
238 }
239
240 #[rstest]
241 fn test_handle_bar(
242 mut indicator_hma_10: HullMovingAverage,
243 bar_ethusdt_binance_minute_bid: Bar,
244 ) {
245 indicator_hma_10.handle_bar(&bar_ethusdt_binance_minute_bid);
246 assert_eq!(indicator_hma_10.value, 1522.0);
247 assert!(indicator_hma_10.has_inputs);
248 assert!(!indicator_hma_10.initialized);
249 }
250
251 #[rstest]
252 fn test_reset(mut indicator_hma_10: HullMovingAverage) {
253 indicator_hma_10.update_raw(1.0);
254 assert_eq!(indicator_hma_10.count, 1);
255 assert_eq!(indicator_hma_10.value, 1.0);
256 assert_eq!(indicator_hma_10.ma1.value, 1.0);
257 assert_eq!(indicator_hma_10.ma2.value, 1.0);
258 assert_eq!(indicator_hma_10.ma3.value, 1.0);
259 indicator_hma_10.reset();
260 assert_eq!(indicator_hma_10.value, 0.0);
261 assert_eq!(indicator_hma_10.count, 0);
262 assert_eq!(indicator_hma_10.ma1.value, 0.0);
263 assert_eq!(indicator_hma_10.ma2.value, 0.0);
264 assert_eq!(indicator_hma_10.ma3.value, 0.0);
265 assert!(!indicator_hma_10.has_inputs);
266 assert!(!indicator_hma_10.initialized);
267 }
268
269 #[rstest]
270 #[should_panic(expected = "HullMovingAverage: period must be > 0")]
271 fn test_new_with_zero_period_panics() {
272 let _ = HullMovingAverage::new(0, None);
273 }
274
275 #[rstest]
276 #[case(1)]
277 #[case(5)]
278 #[case(128)]
279 #[case(10_000)]
280 fn test_new_with_positive_period_constructs(#[case] period: usize) {
281 let hma = HullMovingAverage::new(period, None);
282 assert_eq!(hma.period, period);
283 assert_eq!(hma.count(), 0);
284 assert!(!hma.initialized());
285 }
286
287 #[rstest]
288 #[case(PriceType::Bid)]
289 #[case(PriceType::Ask)]
290 #[case(PriceType::Last)]
291 fn test_price_type_propagates_to_inner_wmas(#[case] pt: PriceType) {
292 let hma = HullMovingAverage::new(10, Some(pt));
293 assert_eq!(hma.price_type, pt);
294 assert_eq!(hma.ma1.price_type, pt);
295 assert_eq!(hma.ma2.price_type, pt);
296 assert_eq!(hma.ma3.price_type, pt);
297 }
298
299 #[rstest]
300 fn test_price_type_defaults_to_last() {
301 let hma = HullMovingAverage::new(10, None);
302 assert_eq!(hma.price_type, PriceType::Last);
303 assert_eq!(hma.ma1.price_type, PriceType::Last);
304 assert_eq!(hma.ma2.price_type, PriceType::Last);
305 assert_eq!(hma.ma3.price_type, PriceType::Last);
306 }
307
308 #[rstest]
309 #[case(10.0)]
310 #[case(-5.5)]
311 #[case(42.42)]
312 #[case(0.0)]
313 fn period_one_degenerates_to_price(#[case] price: f64) {
314 let mut hma = HullMovingAverage::new(1, None);
315
316 for _ in 0..5 {
317 hma.update_raw(price);
318 assert!(
319 (hma.value() - price).abs() < f64::EPSILON,
320 "HMA(1) should equal last price {price}, was {}",
321 hma.value()
322 );
323 assert!(hma.initialized(), "HMA(1) must initialise immediately");
324 }
325 }
326
327 #[rstest]
328 #[case(3, 123.456_f64)]
329 #[case(13, 0.001_f64)]
330 fn constant_series_yields_constant_value(#[case] period: usize, #[case] constant: f64) {
331 let mut hma = HullMovingAverage::new(period, None);
332
333 for _ in 0..(period * 4) {
334 hma.update_raw(constant);
335 assert!(
336 (hma.value() - constant).abs() < 1e-12,
337 "Expected {constant}, was {}",
338 hma.value()
339 );
340 }
341 assert!(hma.initialized());
342 }
343
344 #[rstest]
345 fn alternating_extremes_bounded() {
346 let mut hma = HullMovingAverage::new(50, None);
347 let lows_highs = [0.0_f64, 1_000.0_f64];
348
349 for i in 0..200 {
350 let price = lows_highs[i & 1];
351 hma.update_raw(price);
352
353 let v = hma.value();
354 assert!((0.0..=1_000.0).contains(&v), "HMA out of bounds: {v}");
355 }
356 }
357
358 #[rstest]
359 #[case(2)]
360 #[case(17)]
361 #[case(128)]
362 fn initialized_boundary(#[case] period: usize) {
363 let mut hma = HullMovingAverage::new(period, None);
364
365 for i in 0..(period - 1) {
366 hma.update_raw(i as f64);
367 assert!(!hma.initialized(), "HMA wrongly initialised at count {i}");
368 }
369
370 hma.update_raw(0.0);
371 assert!(
372 hma.initialized(),
373 "HMA should initialise at exactly {period} ticks"
374 );
375 }
376
377 #[rstest]
378 #[case(2)]
379 #[case(3)]
380 fn small_periods_do_not_panic(#[case] period: usize) {
381 let mut hma = HullMovingAverage::new(period, None);
382 for i in 0..(period * 5) {
383 hma.update_raw(i as f64);
384 }
385 assert!(hma.initialized());
386 }
387
388 #[rstest]
389 fn negative_prices_supported() {
390 let mut hma = HullMovingAverage::new(10, None);
391 let prices = [-5.0, -4.0, -3.0, -2.5, -2.0, -1.5, -1.0, -0.5, 0.0, 0.5];
392
393 for &p in &prices {
394 hma.update_raw(p);
395 let v = hma.value();
396 assert!(
397 v.is_finite(),
398 "HMA produced a non-finite value {v} from negative prices"
399 );
400 }
401 }
402}