Skip to main content

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