Lesson 3 of 15

Rolling Statistics

Rolling Statistics

A rolling window calculation computes a statistic over a sliding fixed-size window of data. This is essential for detecting trends, smoothing noise, and measuring recent volatility in time series.

For a window of size ww applied to a series x1,x2,...,xnx_1, x_2, ..., x_n:

  • Positions 0 through w2w-2 have fewer than ww values available → output None
  • Position iw1i \geq w-1 uses values xiw+1x_{i-w+1} through xix_i

Rolling Mean at position ii: xˉi=1wj=iw+1ixj\bar{x}_i = \frac{1}{w} \sum_{j=i-w+1}^{i} x_j

Rolling Std at position ii (sample standard deviation): si=1w1j=iw+1i(xjxˉi)2s_i = \sqrt{\frac{1}{w-1} \sum_{j=i-w+1}^{i} (x_j - \bar{x}_i)^2}

Your Task

Implement:

  • rolling_mean(xs, window) — list of rolling means, None for first window-1 positions
  • rolling_std(xs, window) — list of rolling sample stds, None for first window-1 positions
Python runtime loading...
Loading...
Click "Run" to execute your code.