Skip to main content

wickra_core/indicators/
linreg_slope.rs

1//! Linear Regression Slope.
2
3use std::collections::VecDeque;
4
5use crate::error::{Error, Result};
6use crate::traits::Indicator;
7
8/// Linear Regression Slope — the slope of a rolling least-squares fit.
9///
10/// Over the last `period` inputs, indexed `x = 0, 1, …, period − 1`, it fits
11/// the line `y = a + b·x` by ordinary least squares and reports the slope:
12///
13/// ```text
14/// b = (n·Σxy − Σx·Σy) / (n·Σxx − (Σx)²)
15/// ```
16///
17/// This is TA-Lib's `LINEARREG_SLOPE`: a momentum-like reading of how steeply
18/// price is trending over the window — positive while it rises, negative
19/// while it falls, near zero when it is flat — without the band-pass quirks
20/// of a difference-based oscillator.
21///
22/// Each `update` is O(1): the same incremental OLS state as
23/// [`LinearRegression`](crate::LinearRegression) is maintained — `Σx` and
24/// `Σxx` are precomputed once from `period`, while `Σy` and `Σxy` are slid
25/// forward in closed form on every push.
26///
27/// # Example
28///
29/// ```
30/// use wickra_core::{Indicator, LinRegSlope};
31///
32/// let mut indicator = LinRegSlope::new(14).unwrap();
33/// let mut last = None;
34/// for i in 0..80 {
35///     last = indicator.update(f64::from(i));
36/// }
37/// assert!(last.is_some());
38/// ```
39#[derive(Debug, Clone)]
40pub struct LinRegSlope {
41    period: usize,
42    window: VecDeque<f64>,
43    /// Closed form of `Σx` over `x = 0, 1, …, period − 1` — constant in `period`.
44    sum_x: f64,
45    /// Closed form of `n · Σxx − (Σx)²` — constant in `period`.
46    denom: f64,
47    /// Running sum of the values currently in the window.
48    sum_y: f64,
49    /// Running `Σ(x · y)` where `x` is the position within the trailing window.
50    sum_xy: f64,
51}
52
53impl LinRegSlope {
54    /// Construct a new rolling linear-regression slope over `period` inputs.
55    ///
56    /// # Errors
57    /// Returns [`Error::InvalidPeriod`] if `period < 2` — a regression line is
58    /// undefined for fewer than two points.
59    pub fn new(period: usize) -> Result<Self> {
60        if period < 2 {
61            return Err(Error::InvalidPeriod {
62                message: "linear regression slope needs period >= 2",
63            });
64        }
65        let n = period as f64;
66        // Closed forms for x = 0, 1, …, period − 1.
67        let sum_x = n * (n - 1.0) / 2.0;
68        let sum_xx = (n - 1.0) * n * (2.0 * n - 1.0) / 6.0;
69        Ok(Self {
70            period,
71            window: VecDeque::with_capacity(period),
72            sum_x,
73            denom: n * sum_xx - sum_x * sum_x,
74            sum_y: 0.0,
75            sum_xy: 0.0,
76        })
77    }
78
79    /// Configured period.
80    pub const fn period(&self) -> usize {
81        self.period
82    }
83}
84
85impl Indicator for LinRegSlope {
86    type Input = f64;
87    type Output = f64;
88
89    fn update(&mut self, value: f64) -> Option<f64> {
90        if self.window.len() == self.period {
91            // Sliding-window identity: when the window slides one step forward
92            // the indices `x` for every kept entry shift down by 1, so
93            //   new_sum_xy = old_sum_xy − old_sum_y + y0
94            // (`y0` is the popped front value).
95            let y0 = self.window.pop_front().expect("non-empty");
96            self.sum_xy = self.sum_xy - self.sum_y + y0;
97            self.sum_y -= y0;
98        }
99        let k = self.window.len() as f64;
100        self.window.push_back(value);
101        self.sum_y += value;
102        self.sum_xy += k * value;
103
104        if self.window.len() < self.period {
105            return None;
106        }
107        let n = self.period as f64;
108        Some((n * self.sum_xy - self.sum_x * self.sum_y) / self.denom)
109    }
110
111    fn reset(&mut self) {
112        self.window.clear();
113        self.sum_y = 0.0;
114        self.sum_xy = 0.0;
115    }
116
117    fn warmup_period(&self) -> usize {
118        self.period
119    }
120
121    fn is_ready(&self) -> bool {
122        self.window.len() == self.period
123    }
124
125    fn name(&self) -> &'static str {
126        "LinRegSlope"
127    }
128}
129
130#[cfg(test)]
131mod tests {
132    use super::*;
133    use crate::traits::BatchExt;
134    use approx::assert_relative_eq;
135
136    #[test]
137    fn reference_values() {
138        // period 3 over [1, 2, 9]: fit y = 0 + 4x, so the slope is 4.
139        let mut ls = LinRegSlope::new(3).unwrap();
140        let out = ls.batch(&[1.0, 2.0, 9.0]);
141        assert!(out[0].is_none());
142        assert!(out[1].is_none());
143        assert_relative_eq!(out[2].unwrap(), 4.0, epsilon = 1e-9);
144    }
145
146    #[test]
147    fn perfect_line_returns_its_step() {
148        // A series rising by a fixed step has exactly that slope.
149        let prices: Vec<f64> = (0..40).map(|i| 2.5 * f64::from(i) + 7.0).collect();
150        let mut ls = LinRegSlope::new(10).unwrap();
151        for v in ls.batch(&prices).into_iter().flatten() {
152            assert_relative_eq!(v, 2.5, epsilon = 1e-6);
153        }
154    }
155
156    #[test]
157    fn constant_series_has_zero_slope() {
158        let mut ls = LinRegSlope::new(8).unwrap();
159        for v in ls.batch(&[42.0; 20]).into_iter().flatten() {
160            assert_relative_eq!(v, 0.0, epsilon = 1e-9);
161        }
162    }
163
164    #[test]
165    fn falling_series_has_negative_slope() {
166        let prices: Vec<f64> = (0..30).map(|i| 100.0 - f64::from(i)).collect();
167        let mut ls = LinRegSlope::new(10).unwrap();
168        for v in ls.batch(&prices).into_iter().flatten() {
169            assert!(v < 0.0, "a falling series must have a negative slope");
170        }
171    }
172
173    #[test]
174    fn first_value_on_period_th_input() {
175        let mut ls = LinRegSlope::new(5).unwrap();
176        let out = ls.batch(&[1.0, 3.0, 2.0, 5.0, 4.0, 6.0]);
177        for (i, v) in out.iter().enumerate().take(4) {
178            assert!(v.is_none(), "index {i} must be None during warmup");
179        }
180        assert!(out[4].is_some(), "first value lands at index period - 1");
181        assert_eq!(ls.warmup_period(), 5);
182    }
183
184    #[test]
185    fn rejects_period_below_two() {
186        assert!(LinRegSlope::new(0).is_err());
187        assert!(LinRegSlope::new(1).is_err());
188        assert!(LinRegSlope::new(2).is_ok());
189    }
190
191    /// Cover the const accessor `period` (80-82) and the Indicator-impl
192    /// `name` body (125-127). `warmup_period` is exercised elsewhere.
193    #[test]
194    fn accessors_and_metadata() {
195        let ls = LinRegSlope::new(14).unwrap();
196        assert_eq!(ls.period(), 14);
197        assert_eq!(ls.name(), "LinRegSlope");
198    }
199
200    #[test]
201    fn reset_clears_state() {
202        let mut ls = LinRegSlope::new(5).unwrap();
203        ls.batch(&[1.0, 2.0, 3.0, 4.0, 5.0]);
204        assert!(ls.is_ready());
205        ls.reset();
206        assert!(!ls.is_ready());
207        assert_eq!(ls.update(1.0), None);
208    }
209
210    #[test]
211    fn batch_equals_streaming() {
212        let prices: Vec<f64> = (0..60)
213            .map(|i| 50.0 + (f64::from(i) * 0.3).sin() * 10.0)
214            .collect();
215        let mut a = LinRegSlope::new(14).unwrap();
216        let mut b = LinRegSlope::new(14).unwrap();
217        assert_eq!(
218            a.batch(&prices),
219            prices.iter().map(|x| b.update(*x)).collect::<Vec<_>>()
220        );
221    }
222
223    /// Incremental OLS equivalence for the slope: the O(1) implementation must
224    /// agree bar-by-bar with a fresh-from-scratch O(n) refit, on a noisy ramp
225    /// (sliding-phase dominated) and a step function (large pop/push deltas).
226    #[test]
227    fn incremental_matches_naive_slope_bar_by_bar() {
228        fn naive_slope(window: &[f64]) -> f64 {
229            let n = window.len() as f64;
230            let mut sum_y = 0.0;
231            let mut sum_xy = 0.0;
232            let mut sum_x = 0.0;
233            let mut sum_xx = 0.0;
234            for (i, &y) in window.iter().enumerate() {
235                let x = i as f64;
236                sum_y += y;
237                sum_xy += x * y;
238                sum_x += x;
239                sum_xx += x * x;
240            }
241            (n * sum_xy - sum_x * sum_y) / (n * sum_xx - sum_x * sum_x)
242        }
243
244        fn check(prices: &[f64], period: usize) {
245            let mut ls = LinRegSlope::new(period).unwrap();
246            for (t, p) in prices.iter().enumerate() {
247                let streaming = ls.update(*p);
248                if t + 1 >= period {
249                    let lo = t + 1 - period;
250                    let expected = naive_slope(&prices[lo..=t]);
251                    let got = streaming.expect("warmed up");
252                    assert!(
253                        (got - expected).abs() < 1e-9,
254                        "slope diverges at t={t}, period={period}: got={got}, expected={expected}",
255                    );
256                }
257            }
258        }
259
260        let noisy_ramp: Vec<f64> = (0..120)
261            .map(|i| 100.0 + f64::from(i) * 0.5 + (f64::from(i) * 0.7).sin() * 3.0)
262            .collect();
263        check(&noisy_ramp, 5);
264        check(&noisy_ramp, 14);
265
266        let mut step = vec![1.0; 30];
267        step.extend(std::iter::repeat_n(100.0, 30));
268        check(&step, 7);
269    }
270}