1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
//! Z-Score.
use std::collections::VecDeque;
use crate::error::{Error, Result};
use crate::traits::Indicator;
/// Z-Score — how many standard deviations the latest price sits from its
/// rolling mean.
///
/// ```text
/// ZScore = (price − SMA(price, n)) / population_stddev(price, n)
/// ```
///
/// A reading of `+2` means price is two standard deviations above its recent
/// average — statistically stretched to the upside; `−2` is the mirror. It is
/// the standard normalisation behind mean-reversion strategies: a large
/// magnitude flags an extension, a return toward `0` flags reversion. A window
/// with zero dispersion (a flat series) yields `0`.
///
/// # Example
///
/// ```
/// use wickra_core::{Indicator, ZScore};
///
/// let mut indicator = ZScore::new(20).unwrap();
/// let mut last = None;
/// for i in 0..80 {
/// last = indicator.update(f64::from(i));
/// }
/// assert!(last.is_some());
/// ```
#[derive(Debug, Clone)]
pub struct ZScore {
period: usize,
window: VecDeque<f64>,
sum: f64,
sum_sq: f64,
}
impl ZScore {
/// Construct a new Z-Score over a rolling window of `period` prices.
///
/// # Errors
/// Returns [`Error::PeriodZero`] if `period == 0`.
pub fn new(period: usize) -> Result<Self> {
if period == 0 {
return Err(Error::PeriodZero);
}
Ok(Self {
period,
window: VecDeque::with_capacity(period),
sum: 0.0,
sum_sq: 0.0,
})
}
/// Configured period.
pub const fn period(&self) -> usize {
self.period
}
}
impl Indicator for ZScore {
type Input = f64;
type Output = f64;
fn update(&mut self, value: f64) -> Option<f64> {
if self.window.len() == self.period {
let old = self.window.pop_front().expect("non-empty");
self.sum -= old;
self.sum_sq -= old * old;
}
self.window.push_back(value);
self.sum += value;
self.sum_sq += value * value;
if self.window.len() < self.period {
return None;
}
let n = self.period as f64;
let mean = self.sum / n;
// Population variance E[x²] − E[x]²; clamp away tiny negative drift.
let variance = (self.sum_sq / n - mean * mean).max(0.0);
let std = variance.sqrt();
if std == 0.0 {
// A window with no dispersion: the price is exactly its own mean.
return Some(0.0);
}
Some((value - mean) / std)
}
fn reset(&mut self) {
self.window.clear();
self.sum = 0.0;
self.sum_sq = 0.0;
}
fn warmup_period(&self) -> usize {
self.period
}
fn is_ready(&self) -> bool {
self.window.len() == self.period
}
fn name(&self) -> &'static str {
"ZScore"
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::traits::BatchExt;
use approx::assert_relative_eq;
#[test]
fn reference_values() {
// Window [1, 3]: mean 2, population variance (1 + 9)/2 − 4 = 1,
// stddev 1; the latest price 3 is (3 − 2) / 1 = 1 stddev above.
let mut z = ZScore::new(2).unwrap();
let out = z.batch(&[1.0, 3.0]);
assert!(out[0].is_none());
assert_relative_eq!(out[1].unwrap(), 1.0, epsilon = 1e-12);
}
#[test]
fn constant_series_yields_zero() {
let mut z = ZScore::new(10).unwrap();
for v in z.batch(&[42.0; 30]).into_iter().flatten() {
assert_relative_eq!(v, 0.0, epsilon = 1e-12);
}
}
#[test]
fn rising_price_is_above_its_mean() {
// A monotonically rising series always sits above its trailing mean.
let prices: Vec<f64> = (0..40).map(f64::from).collect();
let mut z = ZScore::new(10).unwrap();
for v in z.batch(&prices).into_iter().flatten() {
assert!(
v > 0.0,
"a rising price should score above its mean, got {v}"
);
}
}
#[test]
fn first_value_on_period_th_input() {
let mut z = ZScore::new(5).unwrap();
let out = z.batch(&[1.0, 2.0, 3.0, 4.0, 5.0, 6.0]);
for (i, v) in out.iter().enumerate().take(4) {
assert!(v.is_none(), "index {i} must be None during warmup");
}
assert!(out[4].is_some(), "first value lands at index period - 1");
assert_eq!(z.warmup_period(), 5);
}
#[test]
fn rejects_zero_period() {
assert!(ZScore::new(0).is_err());
}
/// Cover the const accessor `period` (59-61) and the Indicator-impl
/// `name` body (106-108). `warmup_period` is exercised elsewhere.
#[test]
fn accessors_and_metadata() {
let z = ZScore::new(20).unwrap();
assert_eq!(z.period(), 20);
assert_eq!(z.name(), "ZScore");
}
#[test]
fn reset_clears_state() {
let mut z = ZScore::new(5).unwrap();
z.batch(&[1.0, 2.0, 3.0, 4.0, 5.0]);
assert!(z.is_ready());
z.reset();
assert!(!z.is_ready());
assert_eq!(z.update(1.0), None);
}
#[test]
fn batch_equals_streaming() {
let prices: Vec<f64> = (0..60)
.map(|i| 50.0 + (f64::from(i) * 0.3).sin() * 10.0)
.collect();
let mut a = ZScore::new(20).unwrap();
let mut b = ZScore::new(20).unwrap();
assert_eq!(
a.batch(&prices),
prices.iter().map(|x| b.update(*x)).collect::<Vec<_>>()
);
}
}