Window Operations—Rolling
Discover how to work with windowing operations in pandas, with a focus on rolling windows.
Categories of windowing operations
Windowing operations are one of the features in pandas
that stand at the intersection of grouping and aggregation. The idea is to divide the data into partitions (aka windows of time) and then calculate an aggregate function for each window instead of the entire dataset.
There are four categories of windowing operations, namely:
Rolling windows
Weighted windows
Expanding windows
Exponential moving windows
We’ll use the Amazon (AMZN) stock prices in 2017 as the primary dataset for the code examples in this lesson.
Preview of Amazon 2017 Stock Price Dataset
Date | Open | High | Low | Close | Volume | Stock |
3/1/2017 | 757.92 | 758.7595 | 747.7 | 753.67 | 3521066 | AMZN |
4/1/2017 | 758.39 | 759.68 | 754.2 | 757.18 | 2510526 | AMZN |
5/1/2017 | 761.55 | 782.3999 | 760.2557 | 780.45 | 5830068 | AMZN |
6/1/2017 | 782.36 | 799.44 | 778.48 | 795.99 | 5986234 | AMZN |
9/1/2017 | 798 | 801.7742 | 791.77 | 796.92 | 3446109 | AMZN |
Note: Windowing operations currently only support numeric data (integer and float) and will always return
float64
values.
Rolling windows
We start by looking at rolling windows that are characterized by a fixed window size that slides along the data points. Each window contains the current observation at a time point and a fixed number of preceding observations. Rolling windows are useful for smoothing out short-term fluctuations and highlighting longer-term trends in the data.
The image below provides a simple illustration of what rolling windows of a fixed size three look like:
The rolling()
method
We can use the rolling()
method for the computation of rolling statistics on our time series data. For example, we can use the following code to calculate the rolling mean of the closing price over a ...
Get hands-on with 1400+ tech skills courses.