Problems
Loading...
1 / 1

Rolling Standard Deviation

Time Series
Medium

Rolling standard deviation measures the variability within a sliding window of a time series. It is widely used in finance (Bollinger Bands), anomaly detection, and signal processing to quantify local volatility. A rising rolling standard deviation indicates increasing instability, while a falling one signals convergence.

Given a list of values and a window size, compute the population standard deviation for each sliding window position.

Algorithm

For each window starting at position i with size k:

μ=1kj=0k1x[i+j]σ=1kj=0k1(x[i+j]μ)2\mu = \frac{1}{k} \sum_{j=0}^{k-1} x[i+j] \\ \sigma = \sqrt{\frac{1}{k} \sum_{j=0}^{k-1} (x[i+j] - \mu)^2}

The output has length n - k + 1.

Loading visualization...

Examples

Input:

values = [1, 2, 3, 4, 5], window_size = 3

Output:

[0.8165, 0.8165, 0.8165]

Window [1,2,3]: mean=2, variance=((1-2)^2+(2-2)^2+(3-2)^2)/3=2/3, std=sqrt(2/3)=0.8165. Each consecutive window of 3 has the same spread.

Input:

values = [5, 5, 5, 5], window_size = 2

Output:

[0.0, 0.0, 0.0]

All values are identical, so every window has zero variance and zero standard deviation.

Hint 1

For each window of size k, first compute the mean, then compute the average of squared deviations from the mean, and finally take the square root. Use math.sqrt or ** 0.5.

Hint 2

Remember to use population variance (divide by k, not k-1). The output length is len(values) - window_size + 1, same as a moving average.

Requirements

  • Compute the population standard deviation for each sliding window
  • Use population variance (divide by n, not n-1)
  • The window size determines the number of elements in each group
  • Return a list of floats of length n - window_size + 1

Constraints

  • values has at least window_size elements
  • window_size >= 1
  • Return a list of floats
  • Time limit: 300 ms
Try Similar Problems