Calculate the rolling least-squares slope
For N observations, number bars x = 0 through N − 1 from oldest to newest, and let y be the selected price source. Least squares chooses a and b to minimize the sum of squared errors from yhat = a + bx. Require N ≥ 2 and a complete valid window. Repeat the fit when the window advances; b describes the observations in that window rather than a forecast.
- For consecutive x values, the denominator is N(N² − 1)/12. At N = 1 it is zero, so a slope cannot be estimated.
- Reversing x so that zero means the newest bar reverses the sign. Match the indexing convention before comparing a manual loop with a built-in calculation.
- On a 15-minute chart, one step means one 15-minute bar. On a daily chart it means one daily bar. Session gaps and non-time-based charts prevent a bar count from being a universal elapsed-time measure.
| Quantity | Calculation | Unit |
|---|---|---|
| Slope b | Σ[(x − mean(x))(y − mean(y))] / Σ[(x − mean(x))²] | Price units per bar |
| Intercept a | mean(y) − b × mean(x) | Price units |
| Newest fitted endpoint | a + b × (N − 1) | Price units |
| Newest residual | Newest price − newest fitted endpoint | Price units |