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.
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?
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.
- Returns, two ways
- Worked: rolling volatility per stock
- The same thing, for real
Python for Market Data overviewSpotted a mistake? Tell us.