nautilus_indicators/momentum/
bias.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::{Debug, Display};
17
18use nautilus_model::data::Bar;
19
20use crate::{
21    average::{MovingAverageFactory, MovingAverageType},
22    indicator::{Indicator, MovingAverage},
23};
24
25const MAX_PERIOD: usize = 1024;
26
27#[repr(C)]
28#[derive(Debug)]
29#[cfg_attr(
30    feature = "python",
31    pyo3::pyclass(module = "nautilus_trader.core.nautilus_pyo3.indicators", unsendable)
32)]
33pub struct Bias {
34    pub period: usize,
35    pub ma_type: MovingAverageType,
36    pub value: f64,
37    pub count: usize,
38    pub initialized: bool,
39    ma: Box<dyn MovingAverage + Send + 'static>,
40    has_inputs: bool,
41}
42
43impl Display for Bias {
44    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
45        write!(f, "{}({},{})", self.name(), self.period, self.ma_type,)
46    }
47}
48
49impl Indicator for Bias {
50    fn name(&self) -> String {
51        stringify!(Bias).to_string()
52    }
53
54    fn has_inputs(&self) -> bool {
55        self.has_inputs
56    }
57
58    fn initialized(&self) -> bool {
59        self.initialized
60    }
61
62    fn handle_bar(&mut self, bar: &Bar) {
63        self.update_raw((&bar.close).into());
64    }
65
66    fn reset(&mut self) {
67        self.ma.reset();
68        self.value = 0.0;
69        self.count = 0;
70        self.has_inputs = false;
71        self.initialized = false;
72    }
73}
74
75impl Bias {
76    /// Creates a new [`Bias`] instance.
77    ///
78    /// # Panics
79    ///
80    /// - If `period` is less than or equal to 0.
81    /// - If `period` exceeds `MAX_PERIOD`.
82    #[must_use]
83    pub fn new(period: usize, ma_type: Option<MovingAverageType>) -> Self {
84        assert!(
85            period > 0,
86            "BollingerBands: period must be > 0 (received {period})"
87        );
88        assert!(
89            period <= MAX_PERIOD,
90            "Bias: period {period} exceeds MAX_PERIOD {MAX_PERIOD}"
91        );
92        Self {
93            period,
94            ma_type: ma_type.unwrap_or(MovingAverageType::Simple),
95            value: 0.0,
96            count: 0,
97            ma: MovingAverageFactory::create(ma_type.unwrap_or(MovingAverageType::Simple), period),
98            has_inputs: false,
99            initialized: false,
100        }
101    }
102
103    pub fn update_raw(&mut self, close: f64) {
104        self.count += 1;
105        self.ma.update_raw(close);
106        self.value = (close / self.ma.value()) - 1.0;
107        self._check_initialized();
108    }
109
110    pub fn _check_initialized(&mut self) {
111        if !self.initialized {
112            self.has_inputs = true;
113            if self.ma.initialized() {
114                self.initialized = true;
115            }
116        }
117    }
118}
119
120#[cfg(test)]
121mod tests {
122    use rstest::{fixture, rstest};
123
124    use super::*;
125
126    #[fixture]
127    fn bias() -> Bias {
128        Bias::new(10, None)
129    }
130
131    #[rstest]
132    fn test_name_returns_expected_string(bias: Bias) {
133        assert_eq!(bias.name(), "Bias");
134    }
135
136    #[rstest]
137    fn test_str_repr_returns_expected_string(bias: Bias) {
138        assert_eq!(format!("{bias}"), "Bias(10,SIMPLE)");
139    }
140
141    #[rstest]
142    fn test_period_returns_expected_value(bias: Bias) {
143        assert_eq!(bias.period, 10);
144    }
145
146    #[rstest]
147    fn test_initialized_without_inputs_returns_false(bias: Bias) {
148        assert!(!bias.initialized());
149    }
150
151    #[rstest]
152    fn test_initialized_with_required_inputs_returns_true(mut bias: Bias) {
153        for i in 1..=10 {
154            bias.update_raw(f64::from(i));
155        }
156        assert!(bias.initialized());
157    }
158
159    #[rstest]
160    fn test_value_with_one_input_returns_expected_value(mut bias: Bias) {
161        bias.update_raw(1.0);
162        assert_eq!(bias.value, 0.0);
163    }
164
165    #[rstest]
166    fn test_value_with_all_higher_inputs_returns_expected_value(mut bias: Bias) {
167        const EPS: f64 = 1e-12;
168        const EXPECTED: f64 = 0.000_654_735_923_177_662_8;
169
170        fn abs_diff_lt(lhs: f64, rhs: f64) -> bool {
171            (lhs - rhs).abs() < EPS
172        }
173
174        let inputs = [
175            109.93, 110.0, 109.77, 109.96, 110.29, 110.53, 110.27, 110.21, 110.06, 110.19, 109.83,
176            109.9, 110.0, 110.03, 110.13, 109.95, 109.75, 110.15, 109.9, 110.04,
177        ];
178
179        for &price in &inputs {
180            bias.update_raw(price);
181        }
182
183        assert!(
184            abs_diff_lt(bias.value, EXPECTED),
185            "bias.value = {:.16} did not match expected value",
186            bias.value
187        );
188    }
189
190    #[rstest]
191    fn test_reset_successfully_returns_indicator_to_fresh_state(mut bias: Bias) {
192        bias.update_raw(1.00020);
193        bias.update_raw(1.00030);
194        bias.update_raw(1.00050);
195
196        bias.reset();
197
198        assert!(!bias.initialized());
199        assert_eq!(bias.value, 0.0);
200    }
201
202    #[rstest]
203    fn test_reset_resets_moving_average_state() {
204        let mut bias = Bias::new(3, None);
205        bias.update_raw(1.0);
206        bias.update_raw(2.0);
207        bias.update_raw(3.0);
208        assert!(bias.ma.initialized());
209        bias.reset();
210        assert!(!bias.ma.initialized());
211        assert_eq!(bias.value, 0.0);
212    }
213
214    #[rstest]
215    fn test_count_increments_and_resets(mut bias: Bias) {
216        assert_eq!(bias.count, 0);
217        bias.update_raw(1.0);
218        assert_eq!(bias.count, 1);
219        bias.update_raw(1.1);
220        assert_eq!(bias.count, 2);
221        bias.reset();
222        assert_eq!(bias.count, 0);
223    }
224}