wickra_core/indicators/
coefficient_of_variation.rs1use std::collections::VecDeque;
4
5use crate::error::{Error, Result};
6use crate::traits::Indicator;
7
8#[derive(Debug, Clone)]
39pub struct CoefficientOfVariation {
40 period: usize,
41 window: VecDeque<f64>,
42 sum: f64,
43 sum_sq: f64,
44}
45
46impl CoefficientOfVariation {
47 pub fn new(period: usize) -> Result<Self> {
52 if period == 0 {
53 return Err(Error::PeriodZero);
54 }
55 Ok(Self {
56 period,
57 window: VecDeque::with_capacity(period),
58 sum: 0.0,
59 sum_sq: 0.0,
60 })
61 }
62
63 pub const fn period(&self) -> usize {
65 self.period
66 }
67}
68
69impl Indicator for CoefficientOfVariation {
70 type Input = f64;
71 type Output = f64;
72
73 fn update(&mut self, value: f64) -> Option<f64> {
74 if self.window.len() == self.period {
75 let old = self.window.pop_front().expect("non-empty");
76 self.sum -= old;
77 self.sum_sq -= old * old;
78 }
79 self.window.push_back(value);
80 self.sum += value;
81 self.sum_sq += value * value;
82 if self.window.len() < self.period {
83 return None;
84 }
85 let n = self.period as f64;
86 let mean = self.sum / n;
87 let variance = (self.sum_sq / n - mean * mean).max(0.0);
88 let sd = variance.sqrt();
89 if mean == 0.0 {
90 return Some(0.0);
93 }
94 Some(sd / mean)
95 }
96
97 fn reset(&mut self) {
98 self.window.clear();
99 self.sum = 0.0;
100 self.sum_sq = 0.0;
101 }
102
103 fn warmup_period(&self) -> usize {
104 self.period
105 }
106
107 fn is_ready(&self) -> bool {
108 self.window.len() == self.period
109 }
110
111 fn name(&self) -> &'static str {
112 "CoefficientOfVariation"
113 }
114}
115
116#[cfg(test)]
117mod tests {
118 use super::*;
119 use crate::traits::BatchExt;
120 use approx::assert_relative_eq;
121
122 #[test]
123 fn rejects_zero_period() {
124 assert!(matches!(
125 CoefficientOfVariation::new(0),
126 Err(Error::PeriodZero)
127 ));
128 }
129
130 #[test]
131 fn accessors_and_metadata() {
132 let cv = CoefficientOfVariation::new(14).unwrap();
133 assert_eq!(cv.period(), 14);
134 assert_eq!(cv.warmup_period(), 14);
135 assert_eq!(cv.name(), "CoefficientOfVariation");
136 }
137
138 #[test]
139 fn reference_value() {
140 let mut cv = CoefficientOfVariation::new(3).unwrap();
142 let out = cv.batch(&[2.0, 4.0, 6.0]);
143 assert_eq!(out[0], None);
144 let expected = (8.0_f64 / 3.0).sqrt() / 4.0;
145 assert_relative_eq!(out[2].unwrap(), expected, epsilon = 1e-12);
146 }
147
148 #[test]
149 fn constant_series_yields_zero() {
150 let mut cv = CoefficientOfVariation::new(5).unwrap();
151 for o in cv.batch(&[42.0; 20]).into_iter().flatten() {
152 assert_relative_eq!(o, 0.0, epsilon = 1e-12);
153 }
154 }
155
156 #[test]
157 fn zero_mean_returns_zero() {
158 let mut cv = CoefficientOfVariation::new(3).unwrap();
160 let out = cv.batch(&[-1.0, 0.0, 1.0]);
161 assert_relative_eq!(out[2].unwrap(), 0.0, epsilon = 1e-12);
162 }
163
164 #[test]
165 fn reset_clears_state() {
166 let mut cv = CoefficientOfVariation::new(5).unwrap();
167 cv.batch(&[1.0, 2.0, 3.0, 4.0, 5.0]);
168 assert!(cv.is_ready());
169 cv.reset();
170 assert!(!cv.is_ready());
171 assert_eq!(cv.update(1.0), None);
172 }
173
174 #[test]
175 fn batch_equals_streaming() {
176 let prices: Vec<f64> = (0..60)
177 .map(|i| 100.0 + (f64::from(i) * 0.4).sin() * 5.0)
178 .collect();
179 let batch = CoefficientOfVariation::new(14).unwrap().batch(&prices);
180 let mut b = CoefficientOfVariation::new(14).unwrap();
181 let streamed: Vec<_> = prices.iter().map(|p| b.update(*p)).collect();
182 assert_eq!(batch, streamed);
183 }
184}