nautilus_indicators/average/
vidya.rs1use std::fmt::{Display, Formatter};
17
18use nautilus_model::{
19 data::{Bar, QuoteTick, TradeTick},
20 enums::PriceType,
21};
22
23use crate::{
24 average::MovingAverageType,
25 indicator::{Indicator, MovingAverage},
26 momentum::cmo::ChandeMomentumOscillator,
27};
28
29#[repr(C)]
30#[derive(Debug)]
31#[cfg_attr(
32 feature = "python",
33 pyo3::pyclass(module = "posei_trader.core.nautilus_pyo3.indicators", unsendable)
34)]
35pub struct VariableIndexDynamicAverage {
36 pub period: usize,
37 pub alpha: f64,
38 pub price_type: PriceType,
39 pub value: f64,
40 pub count: usize,
41 pub initialized: bool,
42 pub cmo: ChandeMomentumOscillator,
43 pub cmo_pct: f64,
44 has_inputs: bool,
45}
46
47impl Display for VariableIndexDynamicAverage {
48 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
49 write!(f, "{}({})", self.name(), self.period)
50 }
51}
52
53impl Indicator for VariableIndexDynamicAverage {
54 fn name(&self) -> String {
55 stringify!(VariableIndexDynamicAverage).into()
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) {
67 self.update_raw(quote.extract_price(self.price_type).into());
68 }
69
70 fn handle_trade(&mut self, trade: &TradeTick) {
71 self.update_raw((&trade.price).into());
72 }
73
74 fn handle_bar(&mut self, bar: &Bar) {
75 self.update_raw((&bar.close).into());
76 }
77
78 fn reset(&mut self) {
79 self.value = 0.0;
80 self.count = 0;
81 self.cmo_pct = 0.0;
82 self.alpha = 2.0 / (self.period as f64 + 1.0);
83 self.has_inputs = false;
84 self.initialized = false;
85 self.cmo.reset();
86 }
87}
88
89impl VariableIndexDynamicAverage {
90 #[must_use]
96 pub fn new(
97 period: usize,
98 price_type: Option<PriceType>,
99 cmo_ma_type: Option<MovingAverageType>,
100 ) -> Self {
101 assert!(
102 period > 0,
103 "VariableIndexDynamicAverage: period must be > 0 (received {period})"
104 );
105
106 Self {
107 period,
108 price_type: price_type.unwrap_or(PriceType::Last),
109 value: 0.0,
110 count: 0,
111 has_inputs: false,
112 initialized: false,
113 alpha: 2.0 / (period as f64 + 1.0),
114 cmo: ChandeMomentumOscillator::new(period, cmo_ma_type),
115 cmo_pct: 0.0,
116 }
117 }
118}
119
120impl MovingAverage for VariableIndexDynamicAverage {
121 fn value(&self) -> f64 {
122 self.value
123 }
124
125 fn count(&self) -> usize {
126 self.count
127 }
128
129 fn update_raw(&mut self, price: f64) {
130 self.cmo.update_raw(price);
131 self.cmo_pct = (self.cmo.value / 100.0).abs();
132
133 if self.initialized {
134 self.value = (self.alpha * self.cmo_pct)
135 .mul_add(price, self.alpha.mul_add(-self.cmo_pct, 1.0) * self.value);
136 }
137
138 if !self.initialized && self.cmo.initialized {
139 self.initialized = true;
140 }
141 self.has_inputs = true;
142 self.count += 1;
143 }
144}
145
146#[cfg(test)]
150mod tests {
151 use nautilus_model::data::{Bar, QuoteTick, TradeTick};
152 use rstest::rstest;
153
154 use crate::{
155 average::{sma::SimpleMovingAverage, vidya::VariableIndexDynamicAverage},
156 indicator::{Indicator, MovingAverage},
157 stubs::*,
158 };
159
160 #[rstest]
161 fn test_vidya_initialized(indicator_vidya_10: VariableIndexDynamicAverage) {
162 let display_st = format!("{indicator_vidya_10}");
163 assert_eq!(display_st, "VariableIndexDynamicAverage(10)");
164 assert_eq!(indicator_vidya_10.period, 10);
165 assert!(!indicator_vidya_10.initialized());
166 assert!(!indicator_vidya_10.has_inputs());
167 }
168
169 #[rstest]
170 #[should_panic(expected = "period must be > 0")]
171 fn sma_new_with_zero_period_panics() {
172 let _ = VariableIndexDynamicAverage::new(0, None, None);
173 }
174
175 #[rstest]
176 fn test_initialized_with_required_input(mut indicator_vidya_10: VariableIndexDynamicAverage) {
177 for i in 1..10 {
178 indicator_vidya_10.update_raw(f64::from(i));
179 }
180 assert!(!indicator_vidya_10.initialized);
181 indicator_vidya_10.update_raw(10.0);
182 assert!(indicator_vidya_10.initialized);
183 }
184
185 #[rstest]
186 fn test_value_with_one_input(mut indicator_vidya_10: VariableIndexDynamicAverage) {
187 indicator_vidya_10.update_raw(1.0);
188 assert_eq!(indicator_vidya_10.value, 0.0);
189 }
190
191 #[rstest]
192 fn test_value_with_three_inputs(mut indicator_vidya_10: VariableIndexDynamicAverage) {
193 indicator_vidya_10.update_raw(1.0);
194 indicator_vidya_10.update_raw(2.0);
195 indicator_vidya_10.update_raw(3.0);
196 assert_eq!(indicator_vidya_10.value, 0.0);
197 }
198
199 #[rstest]
200 fn test_value_with_ten_inputs(mut indicator_vidya_10: VariableIndexDynamicAverage) {
201 indicator_vidya_10.update_raw(1.00000);
202 indicator_vidya_10.update_raw(1.00010);
203 indicator_vidya_10.update_raw(1.00020);
204 indicator_vidya_10.update_raw(1.00030);
205 indicator_vidya_10.update_raw(1.00040);
206 indicator_vidya_10.update_raw(1.00050);
207 indicator_vidya_10.update_raw(1.00040);
208 indicator_vidya_10.update_raw(1.00030);
209 indicator_vidya_10.update_raw(1.00020);
210 indicator_vidya_10.update_raw(1.00010);
211 indicator_vidya_10.update_raw(1.00000);
212 assert_eq!(indicator_vidya_10.value, 0.046_813_474_863_949_87);
213 }
214
215 #[rstest]
216 fn test_handle_quote_tick(
217 mut indicator_vidya_10: VariableIndexDynamicAverage,
218 stub_quote: QuoteTick,
219 ) {
220 indicator_vidya_10.handle_quote(&stub_quote);
221 assert_eq!(indicator_vidya_10.value, 0.0);
222 }
223
224 #[rstest]
225 fn test_handle_trade_tick(
226 mut indicator_vidya_10: VariableIndexDynamicAverage,
227 stub_trade: TradeTick,
228 ) {
229 indicator_vidya_10.handle_trade(&stub_trade);
230 assert_eq!(indicator_vidya_10.value, 0.0);
231 }
232
233 #[rstest]
234 fn test_handle_bar(
235 mut indicator_vidya_10: VariableIndexDynamicAverage,
236 bar_ethusdt_binance_minute_bid: Bar,
237 ) {
238 indicator_vidya_10.handle_bar(&bar_ethusdt_binance_minute_bid);
239 assert_eq!(indicator_vidya_10.value, 0.0);
240 assert!(!indicator_vidya_10.initialized);
241 }
242
243 #[rstest]
244 fn test_reset(mut indicator_vidya_10: VariableIndexDynamicAverage) {
245 indicator_vidya_10.update_raw(1.0);
246 assert_eq!(indicator_vidya_10.count, 1);
247 assert_eq!(indicator_vidya_10.value, 0.0);
248 indicator_vidya_10.reset();
249 assert_eq!(indicator_vidya_10.value, 0.0);
250 assert_eq!(indicator_vidya_10.count, 0);
251 assert!(!indicator_vidya_10.has_inputs);
252 assert!(!indicator_vidya_10.initialized);
253 }
254
255 fn reference_ma(prices: &[f64], period: usize) -> Vec<f64> {
256 let mut buf = Vec::with_capacity(period);
257 prices
258 .iter()
259 .map(|&p| {
260 buf.push(p);
261 if buf.len() > period {
262 buf.remove(0);
263 }
264 buf.iter().copied().sum::<f64>() / buf.len() as f64
265 })
266 .collect()
267 }
268
269 #[rstest]
270 #[case(3, vec![1.0, 2.0, 3.0, 4.0, 5.0])]
271 #[case(4, vec![10.0, 20.0, 30.0, 40.0, 50.0, 60.0])]
272 #[case(2, vec![0.1, 0.2, 0.3, 0.4])]
273 fn test_sma_exact_rolling_mean(#[case] period: usize, #[case] prices: Vec<f64>) {
274 let mut sma = SimpleMovingAverage::new(period, None);
275 let expected = reference_ma(&prices, period);
276
277 for (ix, (&price, &exp)) in prices.iter().zip(expected.iter()).enumerate() {
278 sma.update_raw(price);
279 assert_eq!(sma.count(), std::cmp::min(ix + 1, period));
280
281 let got = sma.value();
282 assert!(
283 (got - exp).abs() < 1e-12,
284 "tick {ix}: expected {exp}, got {got}"
285 );
286 }
287 }
288
289 #[rstest]
290 fn test_sma_matches_reference_series() {
291 const PERIOD: usize = 5;
292
293 let prices: Vec<f64> = (1u32..=15)
294 .map(|n| f64::from(n * (n + 1) / 2) * 0.37)
295 .collect();
296
297 let reference = reference_ma(&prices, PERIOD);
298
299 let mut sma = SimpleMovingAverage::new(PERIOD, None);
300
301 for (ix, (&price, &exp)) in prices.iter().zip(reference.iter()).enumerate() {
302 sma.update_raw(price);
303
304 let got = sma.value();
305 assert!(
306 (got - exp).abs() < 1e-12,
307 "tick {ix}: expected {exp}, got {got}"
308 );
309 }
310 }
311
312 #[rstest]
313 fn test_vidya_alpha_bounds() {
314 let vidya_min = VariableIndexDynamicAverage::new(1, None, None);
315 assert_eq!(vidya_min.alpha, 1.0);
316
317 let vidya_large = VariableIndexDynamicAverage::new(1_000, None, None);
318 assert!(vidya_large.alpha > 0.0 && vidya_large.alpha < 0.01);
319 }
320
321 #[rstest]
322 fn test_vidya_value_constant_when_cmo_zero() {
323 let mut vidya = VariableIndexDynamicAverage::new(3, None, None);
324
325 for _ in 0..10 {
326 vidya.update_raw(100.0);
327 }
328
329 let baseline = vidya.value;
330 for _ in 0..5 {
331 vidya.update_raw(100.0);
332 assert!((vidya.value - baseline).abs() < 1e-12);
333 }
334 }
335
336 #[rstest]
337 fn test_vidya_handles_negative_prices() {
338 let mut vidya = VariableIndexDynamicAverage::new(5, None, None);
339 let negative_prices = [-1.0, -1.2, -0.8, -1.5, -1.3, -1.1];
340
341 for p in negative_prices {
342 vidya.update_raw(p);
343 assert!(vidya.value.is_finite());
344 assert!((0.0..=1.0).contains(&vidya.cmo_pct));
345 }
346
347 assert!(vidya.value < 0.0);
348 }
349}