nautilus_indicators/momentum/
bias.rs1use 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 #[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 let inputs = [
168 109.93, 110.0, 109.77, 109.96, 110.29, 110.53, 110.27, 110.21, 110.06, 110.19, 109.83,
169 109.9, 110.0, 110.03, 110.13, 109.95, 109.75, 110.15, 109.9, 110.04,
170 ];
171 const EPS: f64 = 1e-12;
172 const EXPECTED: f64 = 0.000_654_735_923_177_662_8;
173 fn abs_diff_lt(lhs: f64, rhs: f64) -> bool {
174 (lhs - rhs).abs() < EPS
175 }
176
177 for &price in &inputs {
178 bias.update_raw(price);
179 }
180
181 assert!(
182 abs_diff_lt(bias.value, EXPECTED),
183 "bias.value = {:.16} did not match expected value",
184 bias.value
185 );
186 }
187
188 #[rstest]
189 fn test_reset_successfully_returns_indicator_to_fresh_state(mut bias: Bias) {
190 bias.update_raw(1.00020);
191 bias.update_raw(1.00030);
192 bias.update_raw(1.00050);
193
194 bias.reset();
195
196 assert!(!bias.initialized());
197 assert_eq!(bias.value, 0.0);
198 }
199
200 #[rstest]
201 fn test_reset_resets_moving_average_state() {
202 let mut bias = Bias::new(3, None);
203 bias.update_raw(1.0);
204 bias.update_raw(2.0);
205 bias.update_raw(3.0);
206 assert!(bias.ma.initialized());
207 bias.reset();
208 assert!(!bias.ma.initialized());
209 assert_eq!(bias.value, 0.0);
210 }
211
212 #[rstest]
213 fn test_count_increments_and_resets(mut bias: Bias) {
214 assert_eq!(bias.count, 0);
215 bias.update_raw(1.0);
216 assert_eq!(bias.count, 1);
217 bias.update_raw(1.1);
218 assert_eq!(bias.count, 2);
219 bias.reset();
220 assert_eq!(bias.count, 0);
221 }
222}