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
25const MAX_PERIOD: usize = 1024;
26
27#[repr(C)]
28#[derive(Debug)]
29#[cfg_attr(
30    feature = "python",
31    pyo3::pyclass(module = "posei_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////////////////////////////////////////////////////////////////////////////////
121// Tests
122////////////////////////////////////////////////////////////////////////////////
123#[cfg(test)]
124mod tests {
125    use rstest::{fixture, rstest};
126
127    use super::*;
128
129    #[fixture]
130    fn bias() -> Bias {
131        Bias::new(10, None)
132    }
133
134    #[rstest]
135    fn test_name_returns_expected_string(bias: Bias) {
136        assert_eq!(bias.name(), "Bias");
137    }
138
139    #[rstest]
140    fn test_str_repr_returns_expected_string(bias: Bias) {
141        assert_eq!(format!("{bias}"), "Bias(10,SIMPLE)");
142    }
143
144    #[rstest]
145    fn test_period_returns_expected_value(bias: Bias) {
146        assert_eq!(bias.period, 10);
147    }
148
149    #[rstest]
150    fn test_initialized_without_inputs_returns_false(bias: Bias) {
151        assert!(!bias.initialized());
152    }
153
154    #[rstest]
155    fn test_initialized_with_required_inputs_returns_true(mut bias: Bias) {
156        for i in 1..=10 {
157            bias.update_raw(f64::from(i));
158        }
159        assert!(bias.initialized());
160    }
161
162    #[rstest]
163    fn test_value_with_one_input_returns_expected_value(mut bias: Bias) {
164        bias.update_raw(1.0);
165        assert_eq!(bias.value, 0.0);
166    }
167
168    #[rstest]
169    fn test_value_with_all_higher_inputs_returns_expected_value(mut bias: Bias) {
170        let inputs = [
171            109.93, 110.0, 109.77, 109.96, 110.29, 110.53, 110.27, 110.21, 110.06, 110.19, 109.83,
172            109.9, 110.0, 110.03, 110.13, 109.95, 109.75, 110.15, 109.9, 110.04,
173        ];
174        const EPS: f64 = 1e-12;
175        const EXPECTED: f64 = 0.000_654_735_923_177_662_8;
176        fn abs_diff_lt(lhs: f64, rhs: f64) -> bool {
177            (lhs - rhs).abs() < EPS
178        }
179
180        for &price in &inputs {
181            bias.update_raw(price);
182        }
183
184        assert!(
185            abs_diff_lt(bias.value, EXPECTED),
186            "bias.value = {:.16} did not match expected value",
187            bias.value
188        );
189    }
190
191    #[rstest]
192    fn test_reset_successfully_returns_indicator_to_fresh_state(mut bias: Bias) {
193        bias.update_raw(1.00020);
194        bias.update_raw(1.00030);
195        bias.update_raw(1.00050);
196
197        bias.reset();
198
199        assert!(!bias.initialized());
200        assert_eq!(bias.value, 0.0);
201    }
202
203    #[rstest]
204    fn test_reset_resets_moving_average_state() {
205        let mut bias = Bias::new(3, None);
206        bias.update_raw(1.0);
207        bias.update_raw(2.0);
208        bias.update_raw(3.0);
209        assert!(bias.ma.initialized());
210        bias.reset();
211        assert!(!bias.ma.initialized());
212        assert_eq!(bias.value, 0.0);
213    }
214
215    #[rstest]
216    fn test_count_increments_and_resets(mut bias: Bias) {
217        assert_eq!(bias.count, 0);
218        bias.update_raw(1.0);
219        assert_eq!(bias.count, 1);
220        bias.update_raw(1.1);
221        assert_eq!(bias.count, 2);
222        bias.reset();
223        assert_eq!(bias.count, 0);
224    }
225}