Moving Average Pandas
The rolling mean returns a Series
you only have to add it as a new column of your DataFrame
(MA
) as described below.
For information, the rolling_mean
function has been deprecated in pandas newer versions. I have used the new method in my example, see below a quote from the pandas documentation.
Warning Prior to version 0.18.0,
pd.rolling_*
,pd.expanding_*
, andpd.ewm*
were module level functions and are now deprecated. These are replaced by using theRolling
,Expanding
andEWM.
objects and a corresponding method call.
df['MA'] = df.rolling(window=5).mean()print(df)# Value MA# Date # 1989-01-02 6.11 NaN# 1989-01-03 6.08 NaN# 1989-01-04 6.11 NaN# 1989-01-05 6.15 NaN# 1989-01-09 6.25 6.14# 1989-01-10 6.24 6.17# 1989-01-11 6.26 6.20# 1989-01-12 6.23 6.23# 1989-01-13 6.28 6.25# 1989-01-16 6.31 6.27
A moving average can also be calculated and visualized directly in a line chart by using the following code:
Example using stock price data:
import pandas_datareader.data as webimport matplotlib.pyplot as pltimport datetimeplt.style.use('ggplot')# Input variablesstart = datetime.datetime(2016, 1, 01)end = datetime.datetime(2018, 3, 29)stock = 'WFC'# Extrating datadf = web.DataReader(stock,'morningstar', start, end)df = df['Close']print df plt.plot(df['WFC'],label= 'Close')plt.plot(df['WFC'].rolling(9).mean(),label= 'MA 9 days')plt.plot(df['WFC'].rolling(21).mean(),label= 'MA 21 days')plt.legend(loc='best')plt.title('Wells Fargo\nClose and Moving Averages')plt.show()
Tutorial on how to do this: https://youtu.be/XWAPpyF62Vg
In case you are calculating more than one moving average:
for i in range(2,10): df['MA{}'.format(i)] = df.rolling(window=i).mean()
Then you can do an aggregate average of all the MA
df[[f for f in list(df) if "MA" in f]].mean(axis=1)