Skip to main content

wickra_core/indicators/
standard_error.rs

1//! Standard Error of the rolling least-squares regression.
2
3use std::collections::VecDeque;
4
5use crate::error::{Error, Result};
6use crate::traits::Indicator;
7
8/// Standard Error of the regression line fit over the last `period` inputs.
9///
10/// Over the trailing window indexed `x = 0, 1, …, period − 1` the OLS line
11/// `y = a + b·x` is fitted, then:
12///
13/// ```text
14/// slope     = (n·Σxy − Σx·Σy) / (n·Σxx − (Σx)²)
15/// SS_total  = Σy² − n·ȳ²                            // total sum of squares
16/// RSS       = SS_total − slope² · S_xx              // residual sum of squares
17/// StdErr    = √( RSS / (n − 2) )                    // n − 2 residual d.o.f.
18/// ```
19///
20/// where `S_xx = (n·Σxx − (Σx)²) / n` is the centred sum of squares of the
21/// design.
22///
23/// This is the textbook **standard error of estimate** of OLS: it measures
24/// the typical distance between the observed prices and the fitted line,
25/// using the residual degrees of freedom `n − 2`. It is the spread that
26/// drives [`crate::BollingerBands`]-style bands around a regression instead of
27/// around an SMA — when the price hugs its trend, `StdErr` is small.
28///
29/// Each `update` is O(period): the `Σx` and `Σxx` terms depend only on
30/// `period` and are precomputed once, but the residuals are summed directly
31/// over the window rather than reconstructed from rolling sums.
32///
33/// That is a deliberate trade. The residual sum of squares *can* be written as
34/// `Σ(y − ȳ)² − slope²·S_xx`, which slides in constant time, and this indicator
35/// did exactly that. But the two terms converge as the fit improves, so the
36/// subtraction cancels precisely when the answer is smallest: on a line
37/// carrying a wobble of 1e-4 around a price of 100 the constant-time form was
38/// 6.2e-08 out, and at a wobble of 1e-8 it was off by 215% — for the case the
39/// indicator is most likely to be asked about, a market hugging its trend.
40/// Summing the residuals costs one further pass over a window the indicator
41/// already holds, and is what the sibling [`crate::StandardErrorBands`] and
42/// [`crate::LinRegChannel`] have always done.
43///
44/// # Example
45///
46/// ```
47/// use wickra_core::{Indicator, StandardError};
48///
49/// let mut indicator = StandardError::new(14).unwrap();
50/// let mut last = None;
51/// for i in 0..40 {
52///     last = indicator.update(100.0 + f64::from(i) + (f64::from(i) * 0.5).sin());
53/// }
54/// assert!(last.is_some());
55/// ```
56#[derive(Debug, Clone)]
57pub struct StandardError {
58    period: usize,
59    window: VecDeque<f64>,
60    /// `n·Σxx − (Σx)²` — OLS denominator, constant in `period`.
61    denom: f64,
62}
63
64impl StandardError {
65    /// Construct a new rolling standard error of regression.
66    ///
67    /// # Errors
68    /// Returns [`Error::InvalidPeriod`] if `period < 3` — the residual
69    /// degrees of freedom `n − 2` would be non-positive.
70    pub fn new(period: usize) -> Result<Self> {
71        if period < 3 {
72            return Err(Error::InvalidPeriod {
73                message: "standard error needs period >= 3",
74            });
75        }
76        if period > crate::error::MAX_PERIOD {
77            return Err(Error::InvalidPeriod {
78                message: crate::error::PERIOD_ABOVE_MAX,
79            });
80        }
81        let n = period as f64;
82        let sum_x = n * (n - 1.0) / 2.0;
83        let sum_xx = (n - 1.0) * n * (2.0 * n - 1.0) / 6.0;
84        Ok(Self {
85            period,
86            window: VecDeque::with_capacity(period),
87            denom: n * sum_xx - sum_x * sum_x,
88        })
89    }
90
91    /// Configured period.
92    pub const fn period(&self) -> usize {
93        self.period
94    }
95}
96
97impl Indicator for StandardError {
98    type Input = f64;
99    type Output = f64;
100
101    #[inline]
102    fn update(&mut self, value: f64) -> Option<f64> {
103        if !value.is_finite() {
104            return None;
105        }
106        if self.window.len() == self.period {
107            self.window.pop_front();
108        }
109        self.window.push_back(value);
110
111        if self.window.len() < self.period {
112            return None;
113        }
114        let n = self.period as f64;
115        // Two passes over the window, on deviations from its mean. On that
116        // scale the fitted line passes through `(mean_x, 0)`, so a residual is
117        // never formed as the difference of two numbers the size of the price,
118        // and the residual sum of squares is never rebuilt by subtraction.
119        let mean_x = (n - 1.0) / 2.0;
120        // `S_xx = Σ(x − x̄)²` over the index, which is `denom / n` and depends
121        // only on `period`.
122        let s_xx = self.denom / n;
123        // Anchored on a value from inside the window rather than on its mean.
124        // The mean is a computed quantity carrying rounding at the scale of the
125        // price -- around 1e-08 at a level of 1e8 -- and every residual would
126        // inherit it. Subtracting a stored input instead is exact whenever the
127        // two share an exponent, which prices within one window always do.
128        let anchor = *self.window.front().expect("the window is full");
129        let mut sum_z = 0.0;
130        for &y in &self.window {
131            sum_z += y - anchor;
132        }
133        let mean_z = sum_z / n;
134        let mut sum_xz = 0.0;
135        for (i, &y) in self.window.iter().enumerate() {
136            sum_xz += (i as f64 - mean_x) * (y - anchor - mean_z);
137        }
138        let slope = sum_xz / s_xx;
139        let mut rss = 0.0;
140        for (i, &y) in self.window.iter().enumerate() {
141            let residual = (y - anchor - mean_z) - slope * (i as f64 - mean_x);
142            rss += residual * residual;
143        }
144        Some((rss / (n - 2.0)).sqrt())
145    }
146
147    fn reset(&mut self) {
148        self.window.clear();
149    }
150
151    #[inline]
152    fn warmup_period(&self) -> usize {
153        self.period
154    }
155
156    #[inline]
157    fn is_ready(&self) -> bool {
158        self.window.len() == self.period
159    }
160
161    #[inline]
162    fn name(&self) -> &'static str {
163        "StandardError"
164    }
165}
166
167#[cfg(test)]
168mod tests {
169    use super::*;
170    use crate::traits::BatchExt;
171    use approx::assert_relative_eq;
172
173    #[test]
174    fn rejects_period_below_three() {
175        assert!(StandardError::new(0).is_err());
176        assert!(StandardError::new(2).is_err());
177        assert!(StandardError::new(3).is_ok());
178    }
179
180    #[test]
181    fn accessors_and_metadata() {
182        let se = StandardError::new(14).unwrap();
183        assert_eq!(se.period(), 14);
184        assert_eq!(se.warmup_period(), 14);
185        assert_eq!(se.name(), "StandardError");
186    }
187
188    #[test]
189    fn perfect_line_has_zero_error() {
190        // Residuals from a perfectly linear fit are zero, so SE = 0.
191        let prices: Vec<f64> = (0..30).map(|i| 2.0 * f64::from(i) + 5.0).collect();
192        let mut se = StandardError::new(10).unwrap();
193        for v in se.batch(&prices).into_iter().flatten() {
194            assert_relative_eq!(v, 0.0, epsilon = 1e-9);
195        }
196    }
197
198    #[test]
199    fn constant_series_yields_zero() {
200        let mut se = StandardError::new(5).unwrap();
201        for v in se.batch(&[42.0; 20]).into_iter().flatten() {
202            assert_relative_eq!(v, 0.0, epsilon = 1e-9);
203        }
204    }
205
206    #[test]
207    fn matches_naive_definition() {
208        // Compare the O(1) update against a fresh-from-scratch OLS refit each bar.
209        fn naive(window: &[f64]) -> f64 {
210            let n = window.len() as f64;
211            let mean_y = window.iter().sum::<f64>() / n;
212            let mut sum_xy = 0.0;
213            let mut sum_x = 0.0;
214            let mut sum_xx = 0.0;
215            for (i, &y) in window.iter().enumerate() {
216                let x = i as f64;
217                sum_xy += x * y;
218                sum_x += x;
219                sum_xx += x * x;
220            }
221            let mean_x = sum_x / n;
222            let s_xx = sum_xx - n * mean_x * mean_x;
223            let slope = (sum_xy - n * mean_x * mean_y) / s_xx;
224            let intercept = mean_y - slope * mean_x;
225            let rss: f64 = window
226                .iter()
227                .enumerate()
228                .map(|(i, &y)| {
229                    let r = y - (intercept + slope * i as f64);
230                    r * r
231                })
232                .sum();
233            (rss / (n - 2.0)).sqrt()
234        }
235
236        let prices: Vec<f64> = (0..60)
237            .map(|i| 100.0 + f64::from(i) * 0.5 + (f64::from(i) * 0.7).sin() * 3.0)
238            .collect();
239        let period = 14;
240        let got = StandardError::new(period).unwrap().batch(&prices);
241        for (i, g) in got.iter().enumerate() {
242            if let Some(v) = g {
243                let expected = naive(&prices[i + 1 - period..=i]);
244                assert_relative_eq!(*v, expected, epsilon = 1e-9);
245            }
246        }
247    }
248
249    #[test]
250    fn reset_clears_state() {
251        let mut se = StandardError::new(5).unwrap();
252        se.batch(&[1.0, 2.0, 3.0, 4.0, 5.0]);
253        assert!(se.is_ready());
254        se.reset();
255        assert!(!se.is_ready());
256        assert_eq!(se.update(1.0), None);
257    }
258
259    #[test]
260    fn batch_equals_streaming() {
261        let prices: Vec<f64> = (0..60)
262            .map(|i| 100.0 + (f64::from(i) * 0.4).sin() * 10.0)
263            .collect();
264        let batch = StandardError::new(14).unwrap().batch(&prices);
265        let mut b = StandardError::new(14).unwrap();
266        let streamed: Vec<_> = prices.iter().map(|p| b.update(*p)).collect();
267        assert_eq!(batch, streamed);
268    }
269
270    /// Least-squares fit of a window against its own index, computed entirely
271    /// on deviations. Returns `(slope, mean, sse)`.
272    ///
273    /// Forming the residuals as `y - (intercept + slope*i)` instead, with both
274    /// sides the size of the price, is exactly what this file stopped doing:
275    /// at a price level of 1e8 that subtraction alone costs eight digits. On
276    /// the centred scale the fitted line is just `slope * (i - mean_x)`.
277    fn centred_fit(window: &[f64]) -> (f64, f64, f64) {
278        let n = window.len() as f64;
279        let mean = window.iter().sum::<f64>() / n;
280        let mean_x = (n - 1.0) / 2.0;
281        let (mut sxy, mut sxx) = (0.0, 0.0);
282        for (i, &y) in window.iter().enumerate() {
283            let dx = i as f64 - mean_x;
284            sxy += dx * (y - mean);
285            sxx += dx * dx;
286        }
287        let slope = sxy / sxx;
288        let mut sse = 0.0;
289        for (i, &y) in window.iter().enumerate() {
290            let r = (y - mean) - slope * (i as f64 - mean_x);
291            sse += r * r;
292        }
293        (slope, mean, sse)
294    }
295
296    /// A one-unit wobble on top of a large price level: the level-to-deviation
297    /// ratio is what drives the cancellation, and scaling the wobble with the
298    /// level instead keeps that ratio constant and hides the defect entirely.
299    fn high_level_series(bars: usize) -> Vec<f64> {
300        (0..bars)
301            .map(|i| {
302                let t = i as f64;
303                1e8 + ((t * 0.11).sin() + 0.4 * (t * 0.37).cos())
304            })
305            .collect()
306    }
307
308    /// The residual sum of squares was reconstructed by subtracting the
309    /// explained variation from a total that was itself computed from raw power
310    /// sums of the price. At a level of 1e8 the total collapsed far enough that
311    /// the subtraction clamped to zero, so the indicator reported a *perfect*
312    /// fit for a series it had not fitted at all -- a relative error of exactly
313    /// 1. Scored against an exact rational computation it is now 3.1e-16.
314    #[test]
315    fn standard_error_at_a_high_price_level_does_not_collapse() {
316        const P: usize = 20;
317        let data = high_level_series(400);
318        let mut ind = StandardError::new(P).unwrap();
319        let mut compared = 0_usize;
320        for (i, &v) in data.iter().enumerate() {
321            let Some(stderr) = ind.update(v) else {
322                continue;
323            };
324            let (_, _, sse) = centred_fit(&data[i + 1 - P..=i]);
325            let want = (sse / (P as f64 - 2.0)).sqrt();
326            assert!(stderr > 0.0, "collapsed to zero at bar {i}");
327            compared += 1;
328            assert_relative_eq!(stderr, want, max_relative = 1e-9);
329        }
330        assert_eq!(compared, data.len() - ind.warmup_period() + 1);
331    }
332    /// The residual sum of squares used to be rebuilt as
333    /// `Σ(y − ȳ)² − slope²·S_xx`, which slides in constant time but cancels
334    /// exactly when the fit is good and the answer is smallest. Scored against
335    /// exact rational arithmetic on a straight line carrying a small wobble:
336    ///
337    /// ```text
338    ///   wobble 1e-4 on a price of 100     6.2e-08  ->  5.5e-14
339    ///   wobble 1e-8 on a price of 100     2.148    ->  7.4e-10
340    ///   wobble 1e-4 on a price of 1e8     3.4e-02  ->  7.2e-11
341    /// ```
342    ///
343    /// A relative error of 2.148 is not a rounding problem; the reported spread
344    /// had no relationship to the data. A market hugging its trend is precisely
345    /// what this indicator is asked about, so the constant-time form failed in
346    /// its own best case.
347    #[test]
348    fn a_near_perfect_fit_still_reports_a_meaningful_spread() {
349        const P: usize = 20;
350        const BARS: usize = 240;
351        const WOBBLE: f64 = 1e-8;
352
353        let data: Vec<f64> = (0..BARS)
354            .map(|i| {
355                let t = i as f64;
356                100.0 + 0.05 * t + WOBBLE * ((t * 1.7).sin() + 0.3 * (t * 0.41).cos())
357            })
358            .collect();
359
360        let mut ind = StandardError::new(P).unwrap();
361        let mean_x = (P as f64 - 1.0) / 2.0;
362        let mut compared = 0_usize;
363        for (i, &v) in data.iter().enumerate() {
364            let Some(stderr) = ind.update(v) else {
365                continue;
366            };
367            let window = &data[i + 1 - P..=i];
368            let mean = window.iter().sum::<f64>() / P as f64;
369            let (mut sxy, mut sxx) = (0.0, 0.0);
370            for (j, &y) in window.iter().enumerate() {
371                let dx = j as f64 - mean_x;
372                sxy += dx * (y - mean);
373                sxx += dx * dx;
374            }
375            let slope = sxy / sxx;
376            let sse: f64 = window
377                .iter()
378                .enumerate()
379                .map(|(j, &y)| {
380                    let r = (y - mean) - slope * (j as f64 - mean_x);
381                    r * r
382                })
383                .sum();
384            let want = (sse / (P as f64 - 2.0)).sqrt();
385            // The old form clamped to zero here and reported a perfect fit.
386            assert!(stderr > 0.0, "collapsed to zero at bar {i}");
387            compared += 1;
388            assert_relative_eq!(stderr, want, max_relative = 1e-6);
389        }
390        assert_eq!(compared, data.len() - ind.warmup_period() + 1);
391    }
392}