nautilus_indicators/average/
hma.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2025 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, 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 = "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 weights: Vec<f64> = (1..=size).map(|x| x as f64).collect();
93    let divisor: f64 = weights.iter().sum();
94    weights = weights.iter().map(|x| x / divisor).collect();
95    weights
96}
97
98impl HullMovingAverage {
99    /// Creates a new [`HullMovingAverage`] instance.
100    #[must_use]
101    pub fn new(period: usize, price_type: Option<PriceType>) -> Self {
102        let period_halved = period / 2;
103        let period_sqrt = (period as f64).sqrt() as usize;
104
105        let w1 = _get_weights(period_halved);
106        let w2 = _get_weights(period);
107        let w3 = _get_weights(period_sqrt);
108
109        let ma1 = WeightedMovingAverage::new(period_halved, w1, price_type);
110        let ma2 = WeightedMovingAverage::new(period, w2, price_type);
111        let ma3 = WeightedMovingAverage::new(period_sqrt, w3, price_type);
112
113        Self {
114            period,
115            price_type: price_type.unwrap_or(PriceType::Last),
116            value: 0.0,
117            count: 0,
118            has_inputs: false,
119            initialized: false,
120            ma1,
121            ma2,
122            ma3,
123        }
124    }
125}
126
127impl MovingAverage for HullMovingAverage {
128    fn value(&self) -> f64 {
129        self.value
130    }
131
132    fn count(&self) -> usize {
133        self.count
134    }
135
136    fn update_raw(&mut self, value: f64) {
137        if !self.has_inputs {
138            self.has_inputs = true;
139            self.value = value;
140        }
141
142        self.ma1.update_raw(value);
143        self.ma2.update_raw(value);
144        self.ma3
145            .update_raw(2.0f64.mul_add(self.ma1.value, -self.ma2.value));
146
147        self.value = self.ma3.value;
148        self.count += 1;
149
150        if !self.initialized && self.count >= self.period {
151            self.initialized = true;
152        }
153    }
154}
155
156////////////////////////////////////////////////////////////////////////////////
157// Tests
158////////////////////////////////////////////////////////////////////////////////
159#[cfg(test)]
160mod tests {
161    use nautilus_model::data::{Bar, QuoteTick, TradeTick};
162    use rstest::rstest;
163
164    use crate::{
165        average::hma::HullMovingAverage,
166        indicator::{Indicator, MovingAverage},
167        stubs::*,
168    };
169
170    #[rstest]
171    fn test_hma_initialized(indicator_hma_10: HullMovingAverage) {
172        let display_str = format!("{indicator_hma_10}");
173        assert_eq!(display_str, "HullMovingAverage(10)");
174        assert_eq!(indicator_hma_10.period, 10);
175        assert!(!indicator_hma_10.initialized);
176        assert!(!indicator_hma_10.has_inputs);
177    }
178
179    #[rstest]
180    fn test_initialized_with_required_input(mut indicator_hma_10: HullMovingAverage) {
181        for i in 1..10 {
182            indicator_hma_10.update_raw(f64::from(i));
183        }
184        assert!(!indicator_hma_10.initialized);
185        indicator_hma_10.update_raw(10.0);
186        assert!(indicator_hma_10.initialized);
187    }
188
189    #[rstest]
190    fn test_value_with_one_input(mut indicator_hma_10: HullMovingAverage) {
191        indicator_hma_10.update_raw(1.0);
192        assert_eq!(indicator_hma_10.value, 1.0);
193    }
194
195    #[rstest]
196    fn test_value_with_three_inputs(mut indicator_hma_10: HullMovingAverage) {
197        indicator_hma_10.update_raw(1.0);
198        indicator_hma_10.update_raw(2.0);
199        indicator_hma_10.update_raw(3.0);
200        assert_eq!(indicator_hma_10.value, 1.824_561_403_508_772);
201    }
202
203    #[rstest]
204    fn test_value_with_ten_inputs(mut indicator_hma_10: HullMovingAverage) {
205        indicator_hma_10.update_raw(1.00000);
206        indicator_hma_10.update_raw(1.00010);
207        indicator_hma_10.update_raw(1.00020);
208        indicator_hma_10.update_raw(1.00030);
209        indicator_hma_10.update_raw(1.00040);
210        indicator_hma_10.update_raw(1.00050);
211        indicator_hma_10.update_raw(1.00040);
212        indicator_hma_10.update_raw(1.00030);
213        indicator_hma_10.update_raw(1.00020);
214        indicator_hma_10.update_raw(1.00010);
215        indicator_hma_10.update_raw(1.00000);
216        assert_eq!(indicator_hma_10.value, 1.000_140_392_817_059_8);
217    }
218
219    #[rstest]
220    fn test_handle_quote_tick(mut indicator_hma_10: HullMovingAverage, stub_quote: QuoteTick) {
221        indicator_hma_10.handle_quote(&stub_quote);
222        assert_eq!(indicator_hma_10.value, 1501.0);
223    }
224
225    #[rstest]
226    fn test_handle_trade_tick(mut indicator_hma_10: HullMovingAverage, stub_trade: TradeTick) {
227        indicator_hma_10.handle_trade(&stub_trade);
228        assert_eq!(indicator_hma_10.value, 1500.0);
229    }
230
231    #[rstest]
232    fn test_handle_bar(
233        mut indicator_hma_10: HullMovingAverage,
234        bar_ethusdt_binance_minute_bid: Bar,
235    ) {
236        indicator_hma_10.handle_bar(&bar_ethusdt_binance_minute_bid);
237        assert_eq!(indicator_hma_10.value, 1522.0);
238        assert!(indicator_hma_10.has_inputs);
239        assert!(!indicator_hma_10.initialized);
240    }
241
242    #[rstest]
243    fn test_reset(mut indicator_hma_10: HullMovingAverage) {
244        indicator_hma_10.update_raw(1.0);
245        assert_eq!(indicator_hma_10.count, 1);
246        assert_eq!(indicator_hma_10.value, 1.0);
247        assert_eq!(indicator_hma_10.ma1.value, 1.0);
248        assert_eq!(indicator_hma_10.ma2.value, 1.0);
249        assert_eq!(indicator_hma_10.ma3.value, 1.0);
250        indicator_hma_10.reset();
251        assert_eq!(indicator_hma_10.value, 0.0);
252        assert_eq!(indicator_hma_10.count, 0);
253        assert_eq!(indicator_hma_10.ma1.value, 0.0);
254        assert_eq!(indicator_hma_10.ma2.value, 0.0);
255        assert_eq!(indicator_hma_10.ma3.value, 0.0);
256        assert!(!indicator_hma_10.has_inputs);
257        assert!(!indicator_hma_10.initialized);
258    }
259}