nautilus_indicators/momentum/
bias.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::{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 = "posei_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
115    #[fixture]
116    fn bias() -> Bias {
117        Bias::new(10, None)
118    }
119
120    #[rstest]
121    fn test_name_returns_expected_string(bias: Bias) {
122        assert_eq!(bias.name(), "Bias");
123    }
124
125    #[rstest]
126    fn test_str_repr_returns_expected_string(bias: Bias) {
127        assert_eq!(format!("{bias}"), "Bias(10,SIMPLE)");
128    }
129
130    #[rstest]
131    fn test_period_returns_expected_value(bias: Bias) {
132        assert_eq!(bias.period, 10);
133    }
134
135    #[rstest]
136    fn test_initialized_without_inputs_returns_false(bias: Bias) {
137        assert!(!bias.initialized());
138    }
139
140    #[rstest]
141    fn test_initialized_with_required_inputs_returns_true(mut bias: Bias) {
142        for i in 1..=10 {
143            bias.update_raw(f64::from(i));
144        }
145        assert!(bias.initialized());
146    }
147
148    #[rstest]
149    fn test_value_with_one_input_returns_expected_value(mut bias: Bias) {
150        bias.update_raw(1.0);
151        assert_eq!(bias.value, 0.0);
152    }
153
154    #[rstest]
155    fn test_value_with_all_higher_inputs_returns_expected_value(mut bias: Bias) {
156        let inputs = [
157            109.93, 110.0, 109.77, 109.96, 110.29, 110.53, 110.27, 110.21, 110.06, 110.19, 109.83,
158            109.9, 110.0, 110.03, 110.13, 109.95, 109.75, 110.15, 109.9, 110.04,
159        ];
160        const EPS: f64 = 1e-12;
161        const EXPECTED: f64 = 0.000_654_735_923_177_662_8;
162        fn abs_diff_lt(lhs: f64, rhs: f64) -> bool {
163            (lhs - rhs).abs() < EPS
164        }
165
166        for &price in &inputs {
167            bias.update_raw(price);
168        }
169
170        assert!(
171            abs_diff_lt(bias.value, EXPECTED),
172            "bias.value = {:.16} did not match expected value",
173            bias.value
174        );
175    }
176
177    #[rstest]
178    fn test_reset_successfully_returns_indicator_to_fresh_state(mut bias: Bias) {
179        bias.update_raw(1.00020);
180        bias.update_raw(1.00030);
181        bias.update_raw(1.00050);
182
183        bias.reset();
184
185        assert!(!bias.initialized());
186        assert_eq!(bias.value, 0.0);
187    }
188}