Lesson 8 of 15

Z-Score Mean Reversion

Z-Score Mean Reversion

The z-score measures how many standard deviations a value is from the rolling mean. It is widely used in mean-reversion strategies: if a price is far above its recent average (high z-score), it may revert downward; if it is far below (low z-score), it may revert upward.

Rolling Z-Score

For a window w ending at index t:

mean = sum(xs[t-w+1:t+1]) / w
std  = sqrt(sum((x - mean)^2 for x in window) / w)   # population std
z    = (xs[t] - mean) / std

If std == 0, return 0.0 to avoid division by zero.

The first window - 1 values are None.

Task

Implement zscore(xs, window) that returns the rolling z-score list.

Python runtime loading...
Loading...
Click "Run" to execute your code.