Skip to main content

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