04-14-2022, 10:19 AM
How to Use Pandas Rolling – A Simple Illustrated Guide
![[Image: oZyocnFR62x1vikMg_8MVm2WHSkCFjGdTHUIzqVj...hgjIY1-KM4]](https://lh4.googleusercontent.com/oZyocnFR62x1vikMg_8MVm2WHSkCFjGdTHUIzqVj2Ium47ZKd-_-IYZo8xy7nLtkzK97gWfeRgWgWLQtAT5E9nl-FDNBlusIL7ujR5UKuzOL1icKvPVPBwhYZlxPrjhgjIY1-KM4)
This article will demonstrate how to use a pandas dataframe method called.
What does the method do?
In short, it performs rolling windows calculations.
It is often used when working with time-series data or signal processing. I will shortly dive into a few practical examples to clarify what this means in practice.
The method will be given a parameter that specifies how big the window the desired calculations should be performed in.
A simple example of using time series data could be that each row of a pandas dataframe represents a day with some values.
Let’s say that the desired window size is five days. The rolling method is given a five as input, and it will perform the expected calculation based on steps of five days.
Before an example of this, let’s see the method, its syntax, and its parameters.
pandas.DataFrame.rolling()
Let’s dive into the parameters one by one:
window
: , , or subclass
This is the size of the moving window.
If an integer, the fixed number of observations is used for each window.
If an offset, the time period of each window. Each window will be variable-sized based on the observations included in the time period. This is only valid for-like indexes.
If a subclass, the window boundaries are based on the defined method. Additional rolling keywords argument, namely , , and will be passed to .
min_periods
: , default
This is the minimum number of observations in the window required to have a value.
Otherwise, the result is assigned.
center
: , default
If, set the window labels as the right edge of the window index. If , set the window labels as the center of the window index.
win_type
: , default
If, all points are evenly weighted.
If a string, it must be a valid window function from.
Some of the Scipy window types require additional parameters to be passed in the aggregation function.
The additional parameters must match the keywords specified in the Scipy window type method signature.
on
: , optional
For a Dataframe, a column label or index level on which to calculate the rolling window, rather than the Dataframes index.
The provided integer column is ignored and excluded from the result since an integer index is not used to calculate the rolling window.
axis
: or , default 0
If 0 or, roll across the rows. If 1 or , roll across the columns.
closed
: , default
Default means .
method
: , default
Execute the rolling operation per single column or row for or over the entire object for .
This argument is only implemented when specifying in the method call.
This part was obtained from the official pandas documentation.
Data
The data I will be working with for this tutorial is historical data for a stock, the amazon stock.
I use the python package to import the data. I will use data starting from and running one year forward in time.
The data only includes trading days, i.e., days when the stock market was open.
![[Image: zvwb_9G7ndEgIGlYaImPZXbTlNp-XAHIhp9RfR7z...hz8XymsCTv]](https://lh6.googleusercontent.com/zvwb_9G7ndEgIGlYaImPZXbTlNp-XAHIhp9RfR7zVxmGuvRZ4ZB9AUNKnChtgd30CShiCZ6KjDvQpHWGkgWfc6OMhVD2r1l6BmlI3FpR5nh3ElE6munQWbxfF3LKQEhz8XymsCTv)
The resulting dataframe contains data about the opening price, the highest price, the lowest price, the closing price, and the trading volume for each day.
Calculating moving averages
The first calculations using the rolling method I will do are some different moving averages values. They are often applied in stock analysis.
A moving average value is a statistic that captures the average change in a data series over time. (source)
Let’s calculate the moving averages for seven days and 15 days for the stock closing price and add those values as new columns to the existing amazon dataframe.
They are named and .
![[Image: clZ14KnZ_PAwayYCoeaWT16QUiQCelMHYdf7uF6d...R9TNf6Ab_p]](https://lh3.googleusercontent.com/clZ14KnZ_PAwayYCoeaWT16QUiQCelMHYdf7uF6d4K915xmqSSaMK9R0tafg3hAuVbACgjCPdsIsE_xgir1LV07rUd4hhZ3lsiP_WrOR1R-UelQLXEeDWjxnrtVOkER9TNf6Ab_p)
Since there is no data before, no seven-day moving average can be calculated before and no 15-day moving average before .
Calculating the Sum of Trading Volume
Let’s now instead use the rolling method to calculate the sum of the volume from the last five trading days to spot if there was any spike in volume.
It is done in the same way as for the moving average, but here the method is used together with the rolling method instead of the method.
I will also add this as a new column to the existing Amazon dataframe.
![[Image: rSd107FYEgpg88bQgfdDZpvSn942PyuygydvwdAQ...v9krkDrxhQ]](https://lh6.googleusercontent.com/rSd107FYEgpg88bQgfdDZpvSn942PyuygydvwdAQ3SDpZM02lee31bHlvPKKhmvuwvwSQZN7qHTVB6sDcg3nNq6DYVmAP88wmmGSkgT0tu7hGL_-ikMqJD2qbjKNGdv9krkDrxhQ)
This metric might not be the most useful but it is a good way to explain how you could use the rolling method together with the method.
Using rolling() with Aggregation
If combining the method with the aggregation method , it is easy to perform rolling calculations on multiple columns simultaneously.
Say that I would like to find the highest high and the lowest low for the last seven days.
![[Image: UtKxjPzoAASwzbcdDubHkvW2bV9n-3T3ZOGdLCR6...Z7Ifp5wnpW]](https://lh6.googleusercontent.com/UtKxjPzoAASwzbcdDubHkvW2bV9n-3T3ZOGdLCR62k7JsJ4ma-ScQGZDW1ONBJmxYaZOtJQdldJWyzIjrAr4sgC8QzXeYacPOv2YDz9TLsV2wFckJv2WZlMofgthOnZ7Ifp5wnpW)
Plotting the Values
This part will be included to visualize the value calculated. It’s a bit more appealing than simply just looking at columns of a dataframe.
First, let’s plot the calculated moving averages values alongside the closing price.
![[Image: jQSp1ogckMdep922IJMkK3PKa6ENu1-o8GWNm2g0...c5IRgY2_p1]](https://lh6.googleusercontent.com/jQSp1ogckMdep922IJMkK3PKa6ENu1-o8GWNm2g0AhyID1JYYhO9La2nPac0QWvCFe9V0_Nz4KnMl490DE5EGXhg7IallhEjy8C9iQGR2NV7TiMXa8oqv0517ue6mUc5IRgY2_p1)
And then the accumulated 5 day volume alongside the closing price.
![[Image: 83qk16yeQwY9zCJJY3w2KbOIvQWZzCX2RjCjUHZt...dDscI5IaEB]](https://lh5.googleusercontent.com/83qk16yeQwY9zCJJY3w2KbOIvQWZzCX2RjCjUHZtkADH9smK10IfGK4y5-gHLclys9eCUnNfoaUXjjeWzPJS2B4_umhPg0mOviZ2W8Hlg1tNfkWhej4k4_TZRSHMF6dDscI5IaEB)
Summary
This was a short tutorial on applying the method on a pandas dataframe using some statistics.
The goal of this article was to demonstrate some simple examples of how the method works, and I hope that it did accomplish that goal.
The method can be used for most statistics calculations, so try and explore it using other methods than those used for this article.
This article will demonstrate how to use a pandas dataframe method called
Code:
rolling()What does the
Code:
pandas.DataFrame.rolling()In short, it performs rolling windows calculations.
It is often used when working with time-series data or signal processing. I will shortly dive into a few practical examples to clarify what this means in practice.
The method will be given a parameter that specifies how big the window the desired calculations should be performed in.
A simple example of using time series data could be that each row of a pandas dataframe represents a day with some values.
Let’s say that the desired window size is five days. The rolling method is given a five as input, and it will perform the expected calculation based on steps of five days.
Before an example of this, let’s see the method, its syntax, and its parameters.
pandas.DataFrame.rolling()
Code:
Dataframe.rolling(window, min_periods=None, center=False, win_type=None, on=None, axis=0, closed=None, method=’single’)Let’s dive into the parameters one by one:
window
Code:
windowCode:
intCode:
offsetCode:
BaseIndexerThis is the size of the moving window.
If an integer, the fixed number of observations is used for each window.
If an offset, the time period of each window. Each window will be variable-sized based on the observations included in the time period. This is only valid for
Code:
datetimeIf a
Code:
BaseIndexerCode:
get_window_bounds()Code:
min_periodsCode:
centerCode:
closedCode:
get_window_bounds()min_periods
Code:
min_periodsCode:
intCode:
NoneThis is the minimum number of observations in the window required to have a value.
Otherwise, the result is assigned
Code:
np.nan- For a window that is specified by an offset, will default to 1.Code:
min_periods
- For a window specified by an integer, will default to the size of the window.Code:
min_periods
center
Code:
centerCode:
boolCode:
FalseIf
Code:
FalseCode:
Truewin_type
Code:
win_typeCode:
strCode:
NoneIf
Code:
NoneIf a string, it must be a valid window function from
Code:
scipy.signalSome of the Scipy window types require additional parameters to be passed in the aggregation function.
The additional parameters must match the keywords specified in the Scipy window type method signature.
on
Code:
onCode:
strFor a Dataframe, a column label or index level on which to calculate the rolling window, rather than the Dataframes index.
The provided integer column is ignored and excluded from the result since an integer index is not used to calculate the rolling window.
axis
Code:
axisCode:
intCode:
strIf 0 or
Code:
'index'Code:
'columns'closed
Code:
closedCode:
strCode:
None- If , the first point in the window is excluded from calculations.Code:
'right'
- If , the last point in the window is excluded from calculations.Code:
'left'
- If , then no points in the window are excluded from the calculations.Code:
'both'
- If , the first and last points in the window are excluded from the calculations.Code:
'neither'
Default
Code:
NoneCode:
'right'method
Code:
methodCode:
strCode:
{'single', 'table'}Code:
'single'Execute the rolling operation per single column or row for
Code:
'single'Code:
'table'This argument is only implemented when specifying
Code:
engine='numba'This part was obtained from the official pandas documentation.
Data
The data I will be working with for this tutorial is historical data for a stock, the amazon stock.
I use the python package
Code:
yfinanceCode:
2021-04-01The data only includes trading days, i.e., days when the stock market was open.
Code:
# Get the stock data from Yahoo finance
AmazonData1y = yfinance.Ticker("AMZN").history(period='1y', actions=False, end='2022-04-01')
display(AmazonData1y.head(20))The resulting dataframe contains data about the opening price, the highest price, the lowest price, the closing price, and the trading volume for each day.
Calculating moving averages
The first calculations using the rolling method I will do are some different moving averages values. They are often applied in stock analysis.
A moving average value is a statistic that captures the average change in a data series over time. (source)Let’s calculate the moving averages for seven days and 15 days for the stock closing price and add those values as new columns to the existing amazon dataframe.
They are named
Code:
'MA7'Code:
'MA15'Code:
# Calculating the 7 and 15 day moving averages based on closing price
# and adding them as new columns
AmazonData1y['7MA'] = AmazonData1y['Close'].rolling(7).mean()
AmazonData1y['15MA'] = AmazonData1y['Close'].rolling(15).mean() display(AmazonData1y.head(20))Since there is no data before
Code:
2021-04-01Code:
2021-04-13Code:
2021-04-23Calculating the Sum of Trading Volume
Let’s now instead use the rolling method to calculate the sum of the volume from the last five trading days to spot if there was any spike in volume.
It is done in the same way as for the moving average, but here the
Code:
sum()Code:
mean()I will also add this as a new column to the existing Amazon dataframe.
Code:
# Calculating 5 day volume using rolling
AmazonData1y['5VOL'] = AmazonData1y['Volume'].rolling(5).sum() display(AmazonData1y.head(20))This metric might not be the most useful but it is a good way to explain how you could use the rolling method together with the
Code:
sum()Using rolling() with Aggregation
If combining the
Code:
rolling()Code:
agg()Say that I would like to find the highest high and the lowest low for the last seven days.
Code:
# Performing rolling calculations on multiple columns at the
# same time using .agg()
SevenHighAndLow = AmazonData1y.rolling(7).agg({'High': 'max', 'Low': 'min'}) display(SevenHighAndLow.head(20))Plotting the Values
This part will be included to visualize the value calculated. It’s a bit more appealing than simply just looking at columns of a dataframe.
First, let’s plot the calculated moving averages values alongside the closing price.
Code:
# Plotting the closing price with the 7 and 15 day moving averages
AmazonData1y.plot(y=['Close', '7MA', '15MA'], kind='line', figsize=(14,12)) plt.title('Closing price, 7MA and 15MA', fontsize=16)
plt.xlabel('Date')
plt.ylabel('Stock price($)')
plt.show()And then the accumulated 5 day volume alongside the closing price.
Code:
# Plotting the closing price alongside the 5 day volume
AmazonData1y.plot(y=['Close', '5VOL'], secondary_y='5VOL', kind='line', ylabel='Stock Price ($)', figsize=(14,12)) plt.title('Closing price and 5 day accumulated volume', fontsize=16)
plt.xlabel('Date')
plt.ylabel('Volume')
plt.show()Summary
This was a short tutorial on applying the
Code:
rolling()The goal of this article was to demonstrate some simple examples of how the
Code:
rolling()The
Code:
rolling()
