nautilus_indicators/momentum/
bias.rs1use std::fmt::{Debug, Display};
17
18use nautilus_model::data::{Bar, QuoteTick, TradeTick};
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.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_quote(&mut self, _quote: &QuoteTick) -> anyhow::Result<()> {
67 Ok(())
68 }
69
70 fn handle_trade(&mut self, _trade: &TradeTick) {}
71
72 fn handle_bar(&mut self, bar: &Bar) {
73 self.update_raw((&bar.close).into());
74 }
75
76 fn reset(&mut self) {
77 self.ma.reset();
78 self.value = 0.0;
79 self.count = 0;
80 self.has_inputs = false;
81 self.initialized = false;
82 }
83}
84
85impl Bias {
86 #[must_use]
93 pub fn new(period: usize, ma_type: Option<MovingAverageType>) -> Self {
94 assert!(
95 period > 0,
96 "BollingerBands: period must be > 0 (received {period})"
97 );
98 assert!(
99 period <= MAX_PERIOD,
100 "Bias: period {period} exceeds MAX_PERIOD {MAX_PERIOD}"
101 );
102 Self {
103 period,
104 ma_type: ma_type.unwrap_or(MovingAverageType::Simple),
105 value: 0.0,
106 count: 0,
107 ma: MovingAverageFactory::create(ma_type.unwrap_or(MovingAverageType::Simple), period),
108 has_inputs: false,
109 initialized: false,
110 }
111 }
112
113 pub fn update_raw(&mut self, close: f64) {
114 self.count += 1;
115 self.ma.update_raw(close);
116 self.value = (close / self.ma.value()) - 1.0;
117 self.check_initialized();
118 }
119
120 pub fn check_initialized(&mut self) {
121 if !self.initialized {
122 self.has_inputs = true;
123
124 if self.ma.initialized() {
125 self.initialized = true;
126 }
127 }
128 }
129}
130
131#[cfg(test)]
132mod tests {
133 use rstest::{fixture, rstest};
134
135 use super::*;
136
137 #[fixture]
138 fn bias() -> Bias {
139 Bias::new(10, None)
140 }
141
142 #[rstest]
143 fn test_name_returns_expected_string(bias: Bias) {
144 assert_eq!(bias.name(), "Bias");
145 }
146
147 #[rstest]
148 fn test_str_repr_returns_expected_string(bias: Bias) {
149 assert_eq!(format!("{bias}"), "Bias(10,SIMPLE)");
150 }
151
152 #[rstest]
153 fn test_period_returns_expected_value(bias: Bias) {
154 assert_eq!(bias.period, 10);
155 }
156
157 #[rstest]
158 fn test_initialized_without_inputs_returns_false(bias: Bias) {
159 assert!(!bias.initialized());
160 }
161
162 #[rstest]
163 fn test_initialized_with_required_inputs_returns_true(mut bias: Bias) {
164 for i in 1..=10 {
165 bias.update_raw(f64::from(i));
166 }
167 assert!(bias.initialized());
168 }
169
170 #[rstest]
171 fn test_value_with_one_input_returns_expected_value(mut bias: Bias) {
172 bias.update_raw(1.0);
173 assert_eq!(bias.value, 0.0);
174 }
175
176 #[rstest]
177 fn test_value_with_all_higher_inputs_returns_expected_value(mut bias: Bias) {
178 const EPS: f64 = 1e-12;
179 const EXPECTED: f64 = 0.000_654_735_923_177_662_8;
180
181 fn abs_diff_lt(lhs: f64, rhs: f64) -> bool {
182 (lhs - rhs).abs() < EPS
183 }
184
185 let inputs = [
186 109.93, 110.0, 109.77, 109.96, 110.29, 110.53, 110.27, 110.21, 110.06, 110.19, 109.83,
187 109.9, 110.0, 110.03, 110.13, 109.95, 109.75, 110.15, 109.9, 110.04,
188 ];
189
190 for &price in &inputs {
191 bias.update_raw(price);
192 }
193
194 assert!(
195 abs_diff_lt(bias.value, EXPECTED),
196 "bias.value = {:.16} did not match expected value",
197 bias.value
198 );
199 }
200
201 #[rstest]
202 fn test_reset_successfully_returns_indicator_to_fresh_state(mut bias: Bias) {
203 bias.update_raw(1.00020);
204 bias.update_raw(1.00030);
205 bias.update_raw(1.00050);
206
207 bias.reset();
208
209 assert!(!bias.initialized());
210 assert_eq!(bias.value, 0.0);
211 }
212
213 #[rstest]
214 fn test_reset_resets_moving_average_state() {
215 let mut bias = Bias::new(3, None);
216 bias.update_raw(1.0);
217 bias.update_raw(2.0);
218 bias.update_raw(3.0);
219 assert!(bias.ma.initialized());
220 bias.reset();
221 assert!(!bias.ma.initialized());
222 assert_eq!(bias.value, 0.0);
223 }
224
225 #[rstest]
226 fn test_count_increments_and_resets(mut bias: Bias) {
227 assert_eq!(bias.count, 0);
228 bias.update_raw(1.0);
229 assert_eq!(bias.count, 1);
230 bias.update_raw(1.1);
231 assert_eq!(bias.count, 2);
232 bias.reset();
233 assert_eq!(bias.count, 0);
234 }
235}