Volatility: Sample Standard Deviation in Every Window

Time SeriesMedium+15 XP+15

Volatility: Sample Standard Deviation in Every Window

A rolling mean tells you where a series is. A rolling standard deviation tells you how turbulent it is right now — which is often the more actionable number. In finance it's volatility; in monitoring it's the signal that a metric has become unstable even though its average looks fine.

Task: write rolling_std(series, window) returning the standard deviation of each window, each rounded to 4 decimal places.

  • Slide a window of window consecutive values along the series, one step at a time. The output has len(series) - window + 1 entries.
  • For each window: take its mean, sum the squared distances from it, divide by window - 1, and square-root.
  • That's the sample standard deviation, matching pandas' rolling(...).std() default — each window is treated as a sample, not as the whole population.
  • window is at least 2, so window - 1 is never zero.
  • A window of identical values gives exactly 0.0.

The window - 1 is the detail that makes implementations disagree. NumPy's std divides by n by default and pandas divides by n - 1, so the same data run through the two gives different volatility numbers — a discrepancy that has confused a great many people comparing a hand-rolled calculation against a library's.

Notice the shape of what you get back: a stretch of calm produces near-zero values, and one violent jump raises the output for window consecutive positions, because it stays inside the window that long before sliding out.

Examples

series = [1, 2, 3, 4]
window = 2
returns [0.7071, 0.7071, 0.7071]
series = [2, 4, 4, 4, 5]
window = 3
returns [1.1547, 0.0, 0.5774]

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run