nautilus_indicators/average/
hma.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2025 Posei Systems Pty Ltd. All rights reserved.
3//  https://poseitrader.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, 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/// 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 = "posei_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    /// Creates a new [`HullMovingAverage`] instance.
102    ///
103    /// # Panics
104    ///
105    /// Panics if `period` is not a positive integer (> 0).
106    #[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////////////////////////////////////////////////////////////////////////////////
166// Tests
167////////////////////////////////////////////////////////////////////////////////
168#[cfg(test)]
169mod tests {
170    use nautilus_model::{
171        data::{Bar, QuoteTick, TradeTick},
172        enums::PriceType,
173    };
174    use rstest::rstest;
175
176    use crate::{
177        average::hma::HullMovingAverage,
178        indicator::{Indicator, MovingAverage},
179        stubs::*,
180    };
181
182    #[rstest]
183    fn test_hma_initialized(indicator_hma_10: HullMovingAverage) {
184        let display_str = format!("{indicator_hma_10}");
185        assert_eq!(display_str, "HullMovingAverage(10)");
186        assert_eq!(indicator_hma_10.period, 10);
187        assert!(!indicator_hma_10.initialized);
188        assert!(!indicator_hma_10.has_inputs);
189    }
190
191    #[rstest]
192    fn test_initialized_with_required_input(mut indicator_hma_10: HullMovingAverage) {
193        for i in 1..10 {
194            indicator_hma_10.update_raw(f64::from(i));
195        }
196        assert!(!indicator_hma_10.initialized);
197        indicator_hma_10.update_raw(10.0);
198        assert!(indicator_hma_10.initialized);
199    }
200
201    #[rstest]
202    fn test_value_with_one_input(mut indicator_hma_10: HullMovingAverage) {
203        indicator_hma_10.update_raw(1.0);
204        assert_eq!(indicator_hma_10.value, 1.0);
205    }
206
207    #[rstest]
208    fn test_value_with_three_inputs(mut indicator_hma_10: HullMovingAverage) {
209        indicator_hma_10.update_raw(1.0);
210        indicator_hma_10.update_raw(2.0);
211        indicator_hma_10.update_raw(3.0);
212        assert_eq!(indicator_hma_10.value, 1.824_561_403_508_772);
213    }
214
215    #[rstest]
216    fn test_value_with_ten_inputs(mut indicator_hma_10: HullMovingAverage) {
217        indicator_hma_10.update_raw(1.00000);
218        indicator_hma_10.update_raw(1.00010);
219        indicator_hma_10.update_raw(1.00020);
220        indicator_hma_10.update_raw(1.00030);
221        indicator_hma_10.update_raw(1.00040);
222        indicator_hma_10.update_raw(1.00050);
223        indicator_hma_10.update_raw(1.00040);
224        indicator_hma_10.update_raw(1.00030);
225        indicator_hma_10.update_raw(1.00020);
226        indicator_hma_10.update_raw(1.00010);
227        indicator_hma_10.update_raw(1.00000);
228        assert_eq!(indicator_hma_10.value, 1.000_140_392_817_059_8);
229    }
230
231    #[rstest]
232    fn test_handle_quote_tick(mut indicator_hma_10: HullMovingAverage, stub_quote: QuoteTick) {
233        indicator_hma_10.handle_quote(&stub_quote);
234        assert_eq!(indicator_hma_10.value, 1501.0);
235    }
236
237    #[rstest]
238    fn test_handle_trade_tick(mut indicator_hma_10: HullMovingAverage, stub_trade: TradeTick) {
239        indicator_hma_10.handle_trade(&stub_trade);
240        assert_eq!(indicator_hma_10.value, 1500.0);
241    }
242
243    #[rstest]
244    fn test_handle_bar(
245        mut indicator_hma_10: HullMovingAverage,
246        bar_ethusdt_binance_minute_bid: Bar,
247    ) {
248        indicator_hma_10.handle_bar(&bar_ethusdt_binance_minute_bid);
249        assert_eq!(indicator_hma_10.value, 1522.0);
250        assert!(indicator_hma_10.has_inputs);
251        assert!(!indicator_hma_10.initialized);
252    }
253
254    #[rstest]
255    fn test_reset(mut indicator_hma_10: HullMovingAverage) {
256        indicator_hma_10.update_raw(1.0);
257        assert_eq!(indicator_hma_10.count, 1);
258        assert_eq!(indicator_hma_10.value, 1.0);
259        assert_eq!(indicator_hma_10.ma1.value, 1.0);
260        assert_eq!(indicator_hma_10.ma2.value, 1.0);
261        assert_eq!(indicator_hma_10.ma3.value, 1.0);
262        indicator_hma_10.reset();
263        assert_eq!(indicator_hma_10.value, 0.0);
264        assert_eq!(indicator_hma_10.count, 0);
265        assert_eq!(indicator_hma_10.ma1.value, 0.0);
266        assert_eq!(indicator_hma_10.ma2.value, 0.0);
267        assert_eq!(indicator_hma_10.ma3.value, 0.0);
268        assert!(!indicator_hma_10.has_inputs);
269        assert!(!indicator_hma_10.initialized);
270    }
271
272    #[rstest]
273    #[should_panic(expected = "HullMovingAverage: period must be > 0")]
274    fn test_new_with_zero_period_panics() {
275        let _ = HullMovingAverage::new(0, None);
276    }
277
278    #[rstest]
279    #[case(1)]
280    #[case(5)]
281    #[case(128)]
282    #[case(10_000)]
283    fn test_new_with_positive_period_constructs(#[case] period: usize) {
284        let hma = HullMovingAverage::new(period, None);
285        assert_eq!(hma.period, period);
286        assert_eq!(hma.count(), 0);
287        assert!(!hma.initialized());
288    }
289
290    #[rstest]
291    #[case(PriceType::Bid)]
292    #[case(PriceType::Ask)]
293    #[case(PriceType::Last)]
294    fn test_price_type_propagates_to_inner_wmas(#[case] pt: PriceType) {
295        let hma = HullMovingAverage::new(10, Some(pt));
296        assert_eq!(hma.price_type, pt);
297        assert_eq!(hma.ma1.price_type, pt);
298        assert_eq!(hma.ma2.price_type, pt);
299        assert_eq!(hma.ma3.price_type, pt);
300    }
301
302    #[rstest]
303    fn test_price_type_defaults_to_last() {
304        let hma = HullMovingAverage::new(10, None);
305        assert_eq!(hma.price_type, PriceType::Last);
306        assert_eq!(hma.ma1.price_type, PriceType::Last);
307        assert_eq!(hma.ma2.price_type, PriceType::Last);
308        assert_eq!(hma.ma3.price_type, PriceType::Last);
309    }
310
311    #[rstest]
312    #[case(10.0)]
313    #[case(-5.5)]
314    #[case(42.42)]
315    #[case(0.0)]
316    fn period_one_degenerates_to_price(#[case] price: f64) {
317        let mut hma = HullMovingAverage::new(1, None);
318
319        for _ in 0..5 {
320            hma.update_raw(price);
321            assert!(
322                (hma.value() - price).abs() < f64::EPSILON,
323                "HMA(1) should equal last price {price}, got {}",
324                hma.value()
325            );
326            assert!(hma.initialized(), "HMA(1) must initialise immediately");
327        }
328    }
329
330    #[rstest]
331    #[case(3, 123.456_f64)]
332    #[case(13, 0.001_f64)]
333    fn constant_series_yields_constant_value(#[case] period: usize, #[case] constant: f64) {
334        let mut hma = HullMovingAverage::new(period, None);
335
336        for _ in 0..(period * 4) {
337            hma.update_raw(constant);
338            assert!(
339                (hma.value() - constant).abs() < 1e-12,
340                "Expected {constant}, got {}",
341                hma.value()
342            );
343        }
344        assert!(hma.initialized());
345    }
346
347    #[rstest]
348    fn alternating_extremes_bounded() {
349        let mut hma = HullMovingAverage::new(50, None);
350        let lows_highs = [0.0_f64, 1_000.0_f64];
351
352        for i in 0..200 {
353            let price = lows_highs[i & 1];
354            hma.update_raw(price);
355
356            let v = hma.value();
357            assert!((0.0..=1_000.0).contains(&v), "HMA out of bounds: {v}");
358        }
359    }
360
361    #[rstest]
362    #[case(2)]
363    #[case(17)]
364    #[case(128)]
365    fn initialized_boundary(#[case] period: usize) {
366        let mut hma = HullMovingAverage::new(period, None);
367
368        for i in 0..(period - 1) {
369            hma.update_raw(i as f64);
370            assert!(!hma.initialized(), "HMA wrongly initialised at count {i}");
371        }
372
373        hma.update_raw(0.0);
374        assert!(
375            hma.initialized(),
376            "HMA should initialise at exactly {period} ticks"
377        );
378    }
379
380    #[rstest]
381    #[case(2)]
382    #[case(3)]
383    fn small_periods_do_not_panic(#[case] period: usize) {
384        let mut hma = HullMovingAverage::new(period, None);
385        for i in 0..(period * 5) {
386            hma.update_raw(i as f64);
387        }
388        assert!(hma.initialized());
389    }
390
391    #[rstest]
392    fn negative_prices_supported() {
393        let mut hma = HullMovingAverage::new(10, None);
394        let prices = [-5.0, -4.0, -3.0, -2.5, -2.0, -1.5, -1.0, -0.5, 0.0, 0.5];
395
396        for &p in &prices {
397            hma.update_raw(p);
398            let v = hma.value();
399            assert!(
400                v.is_finite(),
401                "HMA produced a non-finite value {v} from negative prices"
402            );
403        }
404    }
405}