This tutorial explains how to create a moving average in pandas using the gold and silver price data from rdatasets.
The documentation for each package used in this tutorial is linked below:
Open up a Jupyter notebook and import the following:
The data is from rdatasets imported using the Python package statsmodels.
To create a moving average, a rolling window first needs to be created using the pandas function rolling. Then any aggregation function, sum, mean, std, etc.
your dataframe should look like this:
Alternatively, a rolling window could be created and multiple aggregations applied to it.
This creates a moving average based on the last five observations, but rolling can also take an offset to specify the time to use in the rolling window. For example, 5D can be used as an offset for 5 days.
First, a datetime index must be created from date.