nexus-stats 3.0.0

Fixed-memory, zero-allocation streaming statistics for real-time systems
Documentation
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
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
use crate::math::MulAdd;

#[cfg(feature = "alloc")]
macro_rules! impl_kama {
    ($name:ident, $builder:ident, $ty:ty) => {
        /// KAMA — Kaufman Adaptive Moving Average.
        ///
        /// EMA with an efficiency-ratio-driven alpha. In trending markets,
        /// the alpha increases (fast response). In noisy/choppy markets,
        /// the alpha decreases (slow response).
        ///
        /// The efficiency ratio = |direction| / volatility, where:
        /// - direction = price_now - price_N_ago
        /// - volatility = sum of |price_i - price_{i-1}| over N periods
        ///
        /// The window size is specified at runtime via the builder. The ring
        /// buffer is heap-allocated once during `build()` — no allocation
        /// after construction.
        ///
        /// # Use Cases
        /// - Adaptive smoothing that auto-tunes to market conditions
        /// - Noise-resistant trend following
        /// - Signal processing with variable noise levels
        pub struct $name {
            ring: *mut $ty,
            window: usize,
            head: usize,
            value: $ty,
            fast_sc: $ty,
            slow_sc: $ty,
            volatility_sum: $ty,
            count: u64,
            min_samples: u64,
        }

        // SAFETY: buffer is exclusively owned, T is Copy + Send
        unsafe impl Send for $name {}

        impl $name {
            #[inline]
            fn ring(&self) -> &[$ty] {
                // SAFETY: buffer allocated with capacity `window`, all elements initialized
                unsafe { core::slice::from_raw_parts(self.ring, self.window) }
            }

            #[inline]
            fn ring_mut(&mut self) -> &mut [$ty] {
                // SAFETY: buffer exclusively owned, all elements initialized
                unsafe { core::slice::from_raw_parts_mut(self.ring, self.window) }
            }
        }

        /// Builder for [`
        #[doc = stringify!($name)]
        /// `].
        #[derive(Debug, Clone)]
        pub struct $builder {
            window: Option<usize>,
            fast_span: u64,
            slow_span: u64,
            min_samples: Option<u64>,
        }

        impl $name {
            /// Creates a builder.
            #[inline]
            #[must_use]
            pub fn builder() -> $builder {
                $builder {
                    window: Option::None,
                    fast_span: 2,
                    slow_span: 30,
                    min_samples: Option::None,
                }
            }

            /// Feeds a sample. Returns the adaptive smoothed value once primed.
            ///
            /// # Errors
            ///
            /// Returns `DataError::NotANumber` if the sample is NaN, or
            /// `DataError::Infinite` if the sample is infinite.
            #[inline]
            pub fn update(&mut self, sample: $ty) -> Result<Option<$ty>, crate::DataError> {
                check_finite!(sample);
                let n = self.window;
                let idx = (self.count as usize) % n;
                // SAFETY: idx is in [0, window), buffer exclusively owned
                unsafe { *self.ring.add(idx) = sample; }
                self.count += 1;

                if self.count == 1 {
                    self.value = sample;
                    return if self.count >= self.min_samples { Ok(Option::Some(self.value)) } else { Ok(Option::None) };
                }

                if self.count <= n as u64 {
                    self.value = sample;
                    return if self.count >= self.min_samples { Ok(Option::Some(self.value)) } else { Ok(Option::None) };
                }

                // Window is full — compute ER from the ring buffer
                // SAFETY: buffer allocated with capacity `window`, all initialized
                let ring = unsafe { core::slice::from_raw_parts(self.ring, n) };

                // The ring is ordered: oldest at (idx+1)%n, newest at idx.
                // Split into two contiguous slices to avoid modular indexing
                // per iteration, enabling SIMD vectorization.
                let oldest = (idx + 1) % n;

                // Compute volatility: sum of |consecutive differences| in ring order
                let mut volatility = 0.0 as $ty;

                // Slice 1: oldest..end of buffer
                let s1 = &ring[oldest..];
                for w in s1.windows(2) {
                    volatility += (w[1] - w[0]).abs();
                }

                // Bridge: last element of s1 to first element of s2
                if oldest > 0 && !s1.is_empty() {
                    volatility += (ring[0] - s1[s1.len() - 1]).abs();
                }

                // Slice 2: start..oldest (the wrap-around portion)
                let s2 = &ring[..oldest];
                for w in s2.windows(2) {
                    volatility += (w[1] - w[0]).abs();
                }

                // Direction: |newest - oldest|
                let direction = (sample - ring[oldest]).abs();
                self.volatility_sum = volatility;
                let er = if volatility > 0.0 as $ty {
                    direction / volatility
                } else {
                    0.0 as $ty
                };

                // Smoothing constant: sc = (er * (fast - slow) + slow)^2
                let sc = er * (self.fast_sc - self.slow_sc) + self.slow_sc;
                let alpha = sc * sc;

                self.value = alpha.fma(sample - self.value, self.value);

                if self.count >= self.min_samples {
                    Ok(Option::Some(self.value))
                } else {
                    Ok(Option::None)
                }
            }

            /// Current adaptive smoothed value, or `None` if not primed.
            #[inline]
            #[must_use]
            pub fn value(&self) -> Option<$ty> {
                if self.count >= self.min_samples { Option::Some(self.value) } else { Option::None }
            }

            /// Current efficiency ratio (0 to 1), or `None` if < window samples.
            #[inline]
            #[must_use]
            pub fn efficiency_ratio(&self) -> Option<$ty> {
                let n = self.window;
                if self.count <= n as u64 {
                    return Option::None;
                }
                let newest_idx = ((self.count - 1) as usize) % n;
                let oldest_idx = (self.count as usize) % n;
                let ring = self.ring();
                let direction = (ring[newest_idx] - ring[oldest_idx]).abs();
                if self.volatility_sum > 0.0 as $ty {
                    Option::Some(direction / self.volatility_sum)
                } else {
                    Option::Some(0.0 as $ty)
                }
            }

            /// Window size.
            #[inline]
            #[must_use]
            pub fn window_size(&self) -> usize { self.window }

            /// Number of samples processed.
            #[inline]
            #[must_use]
            pub fn count(&self) -> u64 { self.count }

            /// Whether the KAMA has reached `min_samples`.
            #[inline]
            #[must_use]
            pub fn is_primed(&self) -> bool { self.count >= self.min_samples }

            /// Resets to uninitialized state.
            #[inline]
            pub fn reset(&mut self) {
                self.ring_mut().fill(0.0 as $ty);
                self.head = 0;
                self.value = 0.0 as $ty;
                self.volatility_sum = 0.0 as $ty;
                self.count = 0;
            }
        }

        impl $builder {
            /// Window size (number of samples in the ring buffer).
            #[inline]
            #[must_use]
            pub fn window_size(mut self, n: usize) -> Self {
                self.window = Option::Some(n);
                self
            }

            /// Fast EMA span (most reactive). Default: 2.
            #[inline]
            #[must_use]
            pub fn fast_span(mut self, n: u64) -> Self {
                self.fast_span = n;
                self
            }

            /// Slow EMA span (least reactive). Default: 30.
            #[inline]
            #[must_use]
            pub fn slow_span(mut self, n: u64) -> Self {
                self.slow_span = n;
                self
            }

            /// Minimum samples before value is valid. Default: window size.
            #[inline]
            #[must_use]
            pub fn min_samples(mut self, min: u64) -> Self {
                self.min_samples = Option::Some(min);
                self
            }

            /// Builds the KAMA.
            ///
            /// # Errors
            ///
            /// - Window size must have been set and > 0.
            /// - `fast_span` must be >= 1.
            /// - `slow_span` must be > `fast_span`.
            #[inline]
            pub fn build(self) -> Result<$name, crate::ConfigError> {
                let window = self.window.ok_or(crate::ConfigError::Missing("window_size"))?;
                if window == 0 {
                    return Err(crate::ConfigError::Invalid("window_size must be > 0"));
                }
                if self.fast_span < 1 {
                    return Err(crate::ConfigError::Invalid("fast_span must be >= 1"));
                }
                if self.slow_span <= self.fast_span {
                    return Err(crate::ConfigError::Invalid("slow_span must be > fast_span"));
                }
                let min_samples = self.min_samples.unwrap_or(window as u64);

                let mut vec = core::mem::ManuallyDrop::new(alloc::vec![0.0 as $ty; window]);
                let ring = vec.as_mut_ptr();

                Ok($name {
                    ring,
                    window,
                    head: 0,
                    value: 0.0 as $ty,
                    fast_sc: 2.0 as $ty / (self.fast_span as $ty + 1.0 as $ty),
                    slow_sc: 2.0 as $ty / (self.slow_span as $ty + 1.0 as $ty),
                    volatility_sum: 0.0 as $ty,
                    count: 0,
                    min_samples,
                })
            }
        }

        impl Drop for $name {
            fn drop(&mut self) {
                // SAFETY: buffer was allocated by Vec with capacity `window`.
                // T is Copy so no element drops needed. Reclaim the allocation.
                unsafe {
                    let _ = alloc::vec::Vec::from_raw_parts(self.ring, 0, self.window);
                }
            }
        }

        impl Clone for $name {
            fn clone(&self) -> Self {
                let mut vec = alloc::vec![0.0 as $ty; self.window];
                vec.copy_from_slice(self.ring());
                let mut cloned = core::mem::ManuallyDrop::new(vec);
                let ring = cloned.as_mut_ptr();
                Self {
                    ring,
                    window: self.window,
                    head: self.head,
                    value: self.value,
                    fast_sc: self.fast_sc,
                    slow_sc: self.slow_sc,
                    volatility_sum: self.volatility_sum,
                    count: self.count,
                    min_samples: self.min_samples,
                }
            }
        }

        impl core::fmt::Debug for $name {
            fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
                f.debug_struct(stringify!($name))
                    .field("window", &self.window)
                    .field("count", &self.count)
                    .field("value", &self.value)
                    .finish()
            }
        }
    };
}

#[cfg(feature = "alloc")]
impl_kama!(KamaF64, KamaF64Builder, f64);
#[cfg(feature = "alloc")]
impl_kama!(KamaF32, KamaF32Builder, f32);

#[cfg(all(test, feature = "alloc"))]
mod tests {
    use super::*;

    #[test]
    fn trending_signal_fast_response() {
        let mut kama = KamaF64::builder().window_size(10).build().unwrap();

        // Linear trend — ER should be high, KAMA should track closely
        for i in 0..50 {
            kama.update(i as f64).unwrap();
        }

        let er = kama.efficiency_ratio().unwrap();
        assert!(er > 0.5, "trending signal should have high ER, got {er}");
    }

    #[test]
    fn noisy_signal_slow_response() {
        let mut kama = KamaF64::builder().window_size(10).build().unwrap();

        // Oscillating — ER should be low
        for i in 0..50 {
            let v = if i % 2 == 0 { 100.0 } else { 0.0 };
            kama.update(v).unwrap();
        }

        let er = kama.efficiency_ratio().unwrap();
        assert!(er < 0.3, "noisy signal should have low ER, got {er}");
    }

    #[test]
    fn er_bounds() {
        let mut kama = KamaF64::builder().window_size(10).build().unwrap();
        for i in 0..20 {
            kama.update(i as f64).unwrap();
        }
        let er = kama.efficiency_ratio().unwrap();
        assert!(
            (0.0..=1.0).contains(&er),
            "ER should be in [0, 1], got {er}"
        );
    }

    #[test]
    fn priming() {
        let mut kama = KamaF64::builder().window_size(10).build().unwrap();
        for i in 0..9 {
            assert!(kama.update(i as f64).unwrap().is_none());
        }
        assert!(kama.update(9.0).unwrap().is_some());
    }

    #[test]
    fn reset() {
        let mut kama = KamaF64::builder().window_size(10).build().unwrap();
        for i in 0..20 {
            kama.update(i as f64).unwrap();
        }
        kama.reset();
        assert_eq!(kama.count(), 0);
    }

    #[test]
    fn f32_basic() {
        let mut kama = KamaF32::builder().window_size(5).build().unwrap();
        for i in 0..10 {
            kama.update(i as f32).unwrap();
        }
        assert!(kama.value().is_some());
    }

    #[test]
    fn window_size_accessor() {
        let kama = KamaF64::builder().window_size(10).build().unwrap();
        assert_eq!(kama.window_size(), 10);
    }

    #[test]
    fn rejects_nan_and_inf() {
        let mut kama = KamaF64::builder().window_size(10).build().unwrap();
        assert!(matches!(
            kama.update(f64::NAN),
            Err(crate::DataError::NotANumber)
        ));
        assert!(matches!(
            kama.update(f64::INFINITY),
            Err(crate::DataError::Infinite)
        ));
        assert!(matches!(
            kama.update(f64::NEG_INFINITY),
            Err(crate::DataError::Infinite)
        ));
        assert_eq!(kama.count(), 0);
    }
}