insideout Get Pro

04 · Returns and rolling windows

Pro

Python for Market Data, lesson 4

Returns and rolling windows

Daily returns, moving averages and rolling volatility.

You can line up prices by date, and move a column down a day with .shift(1).

Part 1. A window that slides

A simulated stock that's calm, then stormy. The orange line is its volatility over a window of recent days. Drag the window.

A rolling windowLive

Each point on the line looked back over the last few days of returns, and only those. A short window reacted to the storm quickly and jumped around; a long one was smooth and slow. The shaded stretch at the start was the window filling up: until it holds enough days there's no answer, and pandas says NaN.

Rolling window

rolling(20) takes each row together with the 19 rows before it, and applies a function such as mean() or std() to those 20 values. By default it needs all 20, so the first rows are NaN. center=True moves the window so each row sits in its middle, which reads rows that come after it.

Your turn

prices has 10 rows. How many NaN does prices.pct_change().rolling(5).mean() have?

The first return is NaN, because the first day has no day before it. The window then needs 5 real returns, which it first has at row 5. So rows 0 to 4 are NaN: five of them, one from pct_change and four from the window filling.

Part 2. Returns, two ways

Keep going with Pro

You've done the first part. Pro opens the rest of this lesson, and every other one.

Still to come
  1. Returns, two ways
  2. Worked: rolling volatility per stock
  3. The same thing, for real

Python for Market Data overviewSpotted a mistake? Tell us.