nautilus_indicators/momentum/
bias.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::{Debug, Display};
17
18use nautilus_model::data::Bar;
19
20use crate::{
21    average::{MovingAverageFactory, MovingAverageType},
22    indicator::{Indicator, MovingAverage},
23};
24
25#[repr(C)]
26#[derive(Debug)]
27#[cfg_attr(
28    feature = "python",
29    pyo3::pyclass(module = "nautilus_trader.core.nautilus_pyo3.indicators", unsendable)
30)]
31pub struct Bias {
32    pub period: usize,
33    pub ma_type: MovingAverageType,
34    pub value: f64,
35    pub count: usize,
36    pub initialized: bool,
37    ma: Box<dyn MovingAverage + Send + 'static>,
38    has_inputs: bool,
39    previous_close: f64,
40}
41
42impl Display for Bias {
43    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
44        write!(f, "{}({},{})", self.name(), self.period, self.ma_type,)
45    }
46}
47
48impl Indicator for Bias {
49    fn name(&self) -> String {
50        stringify!(Bias).to_string()
51    }
52
53    fn has_inputs(&self) -> bool {
54        self.has_inputs
55    }
56
57    fn initialized(&self) -> bool {
58        self.initialized
59    }
60
61    fn handle_bar(&mut self, bar: &Bar) {
62        self.update_raw((&bar.close).into());
63    }
64
65    fn reset(&mut self) {
66        self.previous_close = 0.0;
67        self.value = 0.0;
68        self.count = 0;
69        self.has_inputs = false;
70        self.initialized = false;
71    }
72}
73
74impl Bias {
75    /// Creates a new [`Bias`] instance.
76    #[must_use]
77    pub fn new(period: usize, ma_type: Option<MovingAverageType>) -> Self {
78        Self {
79            period,
80            ma_type: ma_type.unwrap_or(MovingAverageType::Simple),
81            value: 0.0,
82            count: 0,
83            previous_close: 0.0,
84            ma: MovingAverageFactory::create(ma_type.unwrap_or(MovingAverageType::Simple), period),
85            has_inputs: false,
86            initialized: false,
87        }
88    }
89
90    pub fn update_raw(&mut self, close: f64) {
91        self.ma.update_raw(close);
92        self.value = (close / self.ma.value()) - 1.0;
93        self._check_initialized();
94    }
95
96    pub fn _check_initialized(&mut self) {
97        if !self.initialized {
98            self.has_inputs = true;
99            if self.ma.initialized() {
100                self.initialized = true;
101            }
102        }
103    }
104}
105
106////////////////////////////////////////////////////////////////////////////////
107// Tests
108////////////////////////////////////////////////////////////////////////////////
109#[cfg(test)]
110mod tests {
111    use rstest::{fixture, rstest};
112
113    use super::*;
114    use crate::testing::approx_equal;
115
116    #[fixture]
117    fn bias() -> Bias {
118        Bias::new(10, None)
119    }
120
121    #[rstest]
122    fn test_name_returns_expected_string(bias: Bias) {
123        assert_eq!(bias.name(), "Bias");
124    }
125
126    #[rstest]
127    fn test_str_repr_returns_expected_string(bias: Bias) {
128        assert_eq!(format!("{bias}"), "Bias(10,SIMPLE)");
129    }
130
131    #[rstest]
132    fn test_period_returns_expected_value(bias: Bias) {
133        assert_eq!(bias.period, 10);
134    }
135
136    #[rstest]
137    fn test_initialized_without_inputs_returns_false(bias: Bias) {
138        assert!(!bias.initialized());
139    }
140
141    #[rstest]
142    fn test_initialized_with_required_inputs_returns_true(mut bias: Bias) {
143        for i in 1..=10 {
144            bias.update_raw(f64::from(i));
145        }
146        assert!(bias.initialized());
147    }
148
149    #[rstest]
150    fn test_value_with_one_input_returns_expected_value(mut bias: Bias) {
151        bias.update_raw(1.0);
152        assert_eq!(bias.value, 0.0);
153    }
154
155    #[rstest]
156    fn test_value_with_all_higher_inputs_returns_expected_value(mut bias: Bias) {
157        let inputs = [
158            109.93, 110.0, 109.77, 109.96, 110.29, 110.53, 110.27, 110.21, 110.06, 110.19, 109.83,
159            109.9, 110.0, 110.03, 110.13, 109.95, 109.75, 110.15, 109.9, 110.04,
160        ];
161        for input in &inputs {
162            bias.update_raw(*input);
163        }
164        assert!(approx_equal(bias.value, 0.000_654_735_923_177_662_8));
165    }
166
167    #[rstest]
168    fn test_reset_successfully_returns_indicator_to_fresh_state(mut bias: Bias) {
169        bias.update_raw(1.00020);
170        bias.update_raw(1.00030);
171        bias.update_raw(1.00050);
172
173        bias.reset();
174
175        assert!(!bias.initialized());
176        assert_eq!(bias.value, 0.0);
177    }
178}