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
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
use crate::math::MulAdd;
macro_rules! impl_ewma_var {
($name:ident, $builder:ident, $ty:ty) => {
/// EWMA Variance — Exponentially Weighted Moving Average with variance tracking.
///
/// Tracks both the exponentially smoothed mean and variance of a streaming
/// signal. Based on the RiskMetrics (JP Morgan, 1996) pattern.
///
/// # Use Cases
/// - Volatility tracking
/// - Adaptive thresholds (mean ± k * std_dev)
/// - Regime detection (variance spike = regime change)
#[derive(Debug, Clone)]
pub struct $name {
alpha: $ty,
one_minus_alpha: $ty,
mean: $ty,
variance: $ty,
count: u64,
min_samples: u64,
}
/// Builder for [`
#[doc = stringify!($name)]
/// `].
#[derive(Debug, Clone)]
pub struct $builder {
alpha: Option<$ty>,
min_samples: u64,
seed_mean: Option<$ty>,
seed_variance: Option<$ty>,
}
impl $name {
/// Creates a builder.
#[inline]
#[must_use]
pub fn builder() -> $builder {
$builder {
alpha: Option::None,
min_samples: 2,
seed_mean: Option::None,
seed_variance: Option::None,
}
}
/// Feeds a sample. Returns `(mean, variance)` once primed.
#[inline]
#[must_use]
pub fn update(&mut self, sample: $ty) -> Option<($ty, $ty)> {
self.count += 1;
if self.count == 1 {
self.mean = sample;
self.variance = 0.0 as $ty;
} else {
let diff = sample - self.mean;
self.mean = self.alpha.fma(sample, self.one_minus_alpha * self.mean);
let diff2 = sample - self.mean;
self.variance = self
.alpha
.fma(diff * diff2, self.one_minus_alpha * self.variance);
}
if self.count >= self.min_samples {
Option::Some((self.mean, self.variance))
} else {
Option::None
}
}
/// Current smoothed mean, or `None` if not primed.
#[inline]
#[must_use]
pub fn mean(&self) -> Option<$ty> {
if self.count >= self.min_samples {
Option::Some(self.mean)
} else {
Option::None
}
}
/// Current exponentially weighted variance, or `None` if not primed.
#[inline]
#[must_use]
pub fn variance(&self) -> Option<$ty> {
if self.count >= self.min_samples {
Option::Some(self.variance)
} else {
Option::None
}
}
/// Current exponentially weighted standard deviation, or `None` if not primed.
#[inline]
#[must_use]
#[cfg(any(feature = "std", feature = "libm"))]
pub fn std_dev(&self) -> Option<$ty> {
self.variance().map(|v| {
#[allow(clippy::cast_possible_truncation)]
{
crate::math::sqrt(v as f64) as $ty
}
})
}
/// The smoothing factor alpha.
#[inline]
#[must_use]
pub fn alpha(&self) -> $ty {
self.alpha
}
/// Number of samples processed.
#[inline]
#[must_use]
pub fn count(&self) -> u64 {
self.count
}
/// Whether the EWMA has reached `min_samples`.
#[inline]
#[must_use]
pub fn is_primed(&self) -> bool {
self.count >= self.min_samples
}
/// Resets to uninitialized state. Parameters unchanged.
#[inline]
pub fn reset(&mut self) {
self.mean = 0.0 as $ty;
self.variance = 0.0 as $ty;
self.count = 0;
}
}
impl $builder {
/// Direct smoothing factor. Must be in (0, 1) exclusive.
#[inline]
#[must_use]
pub fn alpha(mut self, alpha: $ty) -> Self {
self.alpha = Option::Some(alpha);
self
}
/// Samples for weight to decay by half.
#[inline]
#[must_use]
#[cfg(any(feature = "std", feature = "libm"))]
pub fn halflife(mut self, halflife: $ty) -> Self {
let ln2 = core::f64::consts::LN_2 as $ty;
let alpha = 1.0 as $ty - crate::math::exp((-ln2 / halflife) as f64) as $ty;
self.alpha = Option::Some(alpha);
self
}
/// Number of samples for center of mass (pandas convention).
#[inline]
#[must_use]
pub fn span(mut self, n: u64) -> Self {
let alpha = 2.0 as $ty / (n as $ty + 1.0 as $ty);
self.alpha = Option::Some(alpha);
self
}
/// Minimum samples before values are valid. Default: 2.
#[inline]
#[must_use]
pub fn min_samples(mut self, min: u64) -> Self {
self.min_samples = min;
self
}
/// Pre-loads the mean and variance from calibration data.
///
/// When seeded, `is_primed()` returns true immediately.
#[inline]
#[must_use]
pub fn seed(mut self, mean: $ty, variance: $ty) -> Self {
self.seed_mean = Option::Some(mean);
self.seed_variance = Option::Some(variance);
self
}
/// Builds the EWMA variance tracker.
///
/// # Errors
///
/// - Alpha must have been set.
/// - Alpha must be in (0, 1) exclusive.
#[inline]
pub fn build(self) -> Result<$name, crate::ConfigError> {
let alpha = self.alpha.ok_or(crate::ConfigError::Missing("alpha"))?;
if !(alpha > 0.0 as $ty && alpha < 1.0 as $ty) {
return Err(crate::ConfigError::Invalid(
"EWMA variance alpha must be in (0, 1)",
));
}
let (mean, variance, count) = match (self.seed_mean, self.seed_variance) {
(Some(m), Some(v)) => (m, v, self.min_samples),
_ => (0.0 as $ty, 0.0 as $ty, 0),
};
Ok($name {
alpha,
one_minus_alpha: 1.0 as $ty - alpha,
mean,
variance,
count,
min_samples: self.min_samples,
})
}
}
};
}
impl_ewma_var!(EwmaVarF64, EwmaVarF64Builder, f64);
impl_ewma_var!(EwmaVarF32, EwmaVarF32Builder, f32);
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn constant_input_zero_variance() {
let mut ev = EwmaVarF64::builder().alpha(0.1).build().unwrap();
for _ in 0..100 {
let _ = ev.update(100.0);
}
let var = ev.variance().unwrap();
assert!(
var.abs() < 1e-10,
"constant input should have ~zero variance, got {var}"
);
}
#[test]
fn variance_positive_for_varying_input() {
let mut ev = EwmaVarF64::builder().alpha(0.1).build().unwrap();
for i in 0..100 {
let _ = ev.update(if i % 2 == 0 { 100.0 } else { 110.0 });
}
let var = ev.variance().unwrap();
assert!(
var > 0.0,
"varying input should have positive variance, got {var}"
);
}
#[test]
fn priming_behavior() {
let mut ev = EwmaVarF64::builder()
.alpha(0.1)
.min_samples(5)
.build()
.unwrap();
for _ in 0..4 {
assert!(ev.update(100.0).is_none());
}
assert!(ev.update(100.0).is_some());
assert!(ev.is_primed());
}
#[test]
fn reset_clears_state() {
let mut ev = EwmaVarF64::builder().alpha(0.1).build().unwrap();
for i in 0..50 {
let _ = ev.update(i as f64);
}
ev.reset();
assert_eq!(ev.count(), 0);
assert!(ev.mean().is_none());
assert!(ev.variance().is_none());
}
#[test]
fn std_dev_is_sqrt_of_variance() {
let mut ev = EwmaVarF64::builder().alpha(0.3).build().unwrap();
for i in 0..50 {
let _ = ev.update(100.0 + (i % 10) as f64);
}
let var = ev.variance().unwrap();
let sd = ev.std_dev().unwrap();
let expected = crate::math::sqrt(var);
assert!((sd - expected).abs() < 1e-10);
}
#[test]
fn f32_basic() {
let mut ev = EwmaVarF32::builder().alpha(0.1).build().unwrap();
let _ = ev.update(100.0);
let _ = ev.update(110.0);
assert!(ev.variance().is_some());
}
#[test]
fn seeded_is_primed() {
let ev = EwmaVarF64::builder()
.alpha(0.1)
.seed(100.0, 25.0)
.build()
.unwrap();
assert!(ev.is_primed());
assert!((ev.mean().unwrap() - 100.0).abs() < 1e-10);
assert!((ev.variance().unwrap() - 25.0).abs() < 1e-10);
}
#[test]
fn errors_without_alpha() {
let result = EwmaVarF64::builder().build();
assert!(matches!(result, Err(crate::ConfigError::Missing("alpha"))));
}
}