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 = "nautilus_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)]
147mod tests {
148 use nautilus_model::data::{Bar, QuoteTick, TradeTick};
149 use rstest::rstest;
150
151 use crate::{
152 average::{sma::SimpleMovingAverage, vidya::VariableIndexDynamicAverage},
153 indicator::{Indicator, MovingAverage},
154 stubs::*,
155 };
156
157 #[rstest]
158 fn test_vidya_initialized(indicator_vidya_10: VariableIndexDynamicAverage) {
159 let display_st = format!("{indicator_vidya_10}");
160 assert_eq!(display_st, "VariableIndexDynamicAverage(10)");
161 assert_eq!(indicator_vidya_10.period, 10);
162 assert!(!indicator_vidya_10.initialized());
163 assert!(!indicator_vidya_10.has_inputs());
164 }
165
166 #[rstest]
167 #[should_panic(expected = "period must be > 0")]
168 fn sma_new_with_zero_period_panics() {
169 let _ = VariableIndexDynamicAverage::new(0, None, None);
170 }
171
172 #[rstest]
173 fn test_initialized_with_required_input(mut indicator_vidya_10: VariableIndexDynamicAverage) {
174 for i in 1..10 {
175 indicator_vidya_10.update_raw(f64::from(i));
176 }
177 assert!(!indicator_vidya_10.initialized);
178 indicator_vidya_10.update_raw(10.0);
179 assert!(indicator_vidya_10.initialized);
180 }
181
182 #[rstest]
183 fn test_value_with_one_input(mut indicator_vidya_10: VariableIndexDynamicAverage) {
184 indicator_vidya_10.update_raw(1.0);
185 assert_eq!(indicator_vidya_10.value, 0.0);
186 }
187
188 #[rstest]
189 fn test_value_with_three_inputs(mut indicator_vidya_10: VariableIndexDynamicAverage) {
190 indicator_vidya_10.update_raw(1.0);
191 indicator_vidya_10.update_raw(2.0);
192 indicator_vidya_10.update_raw(3.0);
193 assert_eq!(indicator_vidya_10.value, 0.0);
194 }
195
196 #[rstest]
197 fn test_value_with_ten_inputs(mut indicator_vidya_10: VariableIndexDynamicAverage) {
198 indicator_vidya_10.update_raw(1.00000);
199 indicator_vidya_10.update_raw(1.00010);
200 indicator_vidya_10.update_raw(1.00020);
201 indicator_vidya_10.update_raw(1.00030);
202 indicator_vidya_10.update_raw(1.00040);
203 indicator_vidya_10.update_raw(1.00050);
204 indicator_vidya_10.update_raw(1.00040);
205 indicator_vidya_10.update_raw(1.00030);
206 indicator_vidya_10.update_raw(1.00020);
207 indicator_vidya_10.update_raw(1.00010);
208 indicator_vidya_10.update_raw(1.00000);
209 assert_eq!(indicator_vidya_10.value, 0.046_813_474_863_949_87);
210 }
211
212 #[rstest]
213 fn test_handle_quote_tick(
214 mut indicator_vidya_10: VariableIndexDynamicAverage,
215 stub_quote: QuoteTick,
216 ) {
217 indicator_vidya_10.handle_quote(&stub_quote);
218 assert_eq!(indicator_vidya_10.value, 0.0);
219 }
220
221 #[rstest]
222 fn test_handle_trade_tick(
223 mut indicator_vidya_10: VariableIndexDynamicAverage,
224 stub_trade: TradeTick,
225 ) {
226 indicator_vidya_10.handle_trade(&stub_trade);
227 assert_eq!(indicator_vidya_10.value, 0.0);
228 }
229
230 #[rstest]
231 fn test_handle_bar(
232 mut indicator_vidya_10: VariableIndexDynamicAverage,
233 bar_ethusdt_binance_minute_bid: Bar,
234 ) {
235 indicator_vidya_10.handle_bar(&bar_ethusdt_binance_minute_bid);
236 assert_eq!(indicator_vidya_10.value, 0.0);
237 assert!(!indicator_vidya_10.initialized);
238 }
239
240 #[rstest]
241 fn test_reset(mut indicator_vidya_10: VariableIndexDynamicAverage) {
242 indicator_vidya_10.update_raw(1.0);
243 assert_eq!(indicator_vidya_10.count, 1);
244 assert_eq!(indicator_vidya_10.value, 0.0);
245 indicator_vidya_10.reset();
246 assert_eq!(indicator_vidya_10.value, 0.0);
247 assert_eq!(indicator_vidya_10.count, 0);
248 assert!(!indicator_vidya_10.has_inputs);
249 assert!(!indicator_vidya_10.initialized);
250 }
251
252 fn reference_ma(prices: &[f64], period: usize) -> Vec<f64> {
253 let mut buf = Vec::with_capacity(period);
254 prices
255 .iter()
256 .map(|&p| {
257 buf.push(p);
258 if buf.len() > period {
259 buf.remove(0);
260 }
261 buf.iter().copied().sum::<f64>() / buf.len() as f64
262 })
263 .collect()
264 }
265
266 #[rstest]
267 #[case(3, vec![1.0, 2.0, 3.0, 4.0, 5.0])]
268 #[case(4, vec![10.0, 20.0, 30.0, 40.0, 50.0, 60.0])]
269 #[case(2, vec![0.1, 0.2, 0.3, 0.4])]
270 fn test_sma_exact_rolling_mean(#[case] period: usize, #[case] prices: Vec<f64>) {
271 let mut sma = SimpleMovingAverage::new(period, None);
272 let expected = reference_ma(&prices, period);
273
274 for (ix, (&price, &exp)) in prices.iter().zip(expected.iter()).enumerate() {
275 sma.update_raw(price);
276 assert_eq!(sma.count(), std::cmp::min(ix + 1, period));
277
278 let got = sma.value();
279 assert!(
280 (got - exp).abs() < 1e-12,
281 "tick {ix}: expected {exp}, was {got}"
282 );
283 }
284 }
285
286 #[rstest]
287 fn test_sma_matches_reference_series() {
288 const PERIOD: usize = 5;
289
290 let prices: Vec<f64> = (1u32..=15)
291 .map(|n| f64::from(n * (n + 1) / 2) * 0.37)
292 .collect();
293
294 let reference = reference_ma(&prices, PERIOD);
295
296 let mut sma = SimpleMovingAverage::new(PERIOD, None);
297
298 for (ix, (&price, &exp)) in prices.iter().zip(reference.iter()).enumerate() {
299 sma.update_raw(price);
300
301 let got = sma.value();
302 assert!(
303 (got - exp).abs() < 1e-12,
304 "tick {ix}: expected {exp}, was {got}"
305 );
306 }
307 }
308
309 #[rstest]
310 fn test_vidya_alpha_bounds() {
311 let vidya_min = VariableIndexDynamicAverage::new(1, None, None);
312 assert_eq!(vidya_min.alpha, 1.0);
313
314 let vidya_large = VariableIndexDynamicAverage::new(1_000, None, None);
315 assert!(vidya_large.alpha > 0.0 && vidya_large.alpha < 0.01);
316 }
317
318 #[rstest]
319 fn test_vidya_value_constant_when_cmo_zero() {
320 let mut vidya = VariableIndexDynamicAverage::new(3, None, None);
321
322 for _ in 0..10 {
323 vidya.update_raw(100.0);
324 }
325
326 let baseline = vidya.value;
327 for _ in 0..5 {
328 vidya.update_raw(100.0);
329 assert!((vidya.value - baseline).abs() < 1e-12);
330 }
331 }
332
333 #[rstest]
334 fn test_vidya_handles_negative_prices() {
335 let mut vidya = VariableIndexDynamicAverage::new(5, None, None);
336 let negative_prices = [-1.0, -1.2, -0.8, -1.5, -1.3, -1.1];
337
338 for p in negative_prices {
339 vidya.update_raw(p);
340 assert!(vidya.value.is_finite());
341 assert!((0.0..=1.0).contains(&vidya.cmo_pct));
342 }
343
344 assert!(vidya.value < 0.0);
345 }
346}