Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Moving Average Pandas

I would like to add a moving average calculation to my exchange time series.

Original data from Quandl

Exchange = Quandl.get("BUNDESBANK/BBEX3_D_SEK_USD_CA_AC_000",                       authtoken="xxxxxxx")  #               Value # Date                # 1989-01-02  6.10500 # 1989-01-03  6.07500 # 1989-01-04  6.10750 # 1989-01-05  6.15250 # 1989-01-09  6.25500 # 1989-01-10  6.24250 # 1989-01-11  6.26250 # 1989-01-12  6.23250 # 1989-01-13  6.27750 # 1989-01-16  6.31250  # Calculating Moving Avarage MovingAverage = pd.rolling_mean(Exchange,5)  #               Value # Date           # 1989-01-02      NaN # 1989-01-03      NaN # 1989-01-04      NaN # 1989-01-05      NaN # 1989-01-09  6.13900 # 1989-01-10  6.16650 # 1989-01-11  6.20400 # 1989-01-12  6.22900 # 1989-01-13  6.25400 # 1989-01-16  6.26550 

I would like to add the calculated Moving Average as a new column to the right after Value using the same index (Date). Preferably I would also like to rename the calculated moving average to MA.

like image 696
Martin598 Avatar asked Oct 15 '16 15:10

Martin598


People also ask

How do pandas calculate moving averages?

In Python, we can calculate the moving average using . rolling() method. This method provides rolling windows over the data, and we can use the mean function over these windows to calculate moving averages. The size of the window is passed as a parameter in the function .

How do you calculate SMA in pandas?

SMA can be implemented by using pandas. DataFrame. rolling() function is used to calculate the moving average over a fixed window. Where the window will be a fixed size and it is the number of observations used for calculating the statistic.

How do you plot a moving average?

No matter how long or short of a moving average you are looking to plot, the basic calculations remain the same. The change will be in the number of closing prices you use. So, for example, a 200-day moving average is the closing price for 200 days summed together and then divided by 200.

What is the formula for calculating moving average?

Summary. A moving average is a technical indicator that investors and traders use to determine the trend direction of securities. It is calculated by adding up all the data points during a specific period and dividing the sum by the number of time periods.

How to calculate the moving average in a pandas Dataframe?

In this article, we will be looking at how to calculate the moving average in a pandas DataFrame. Moving Average is calculating the average of data over a period of time. The moving average is also known as the rolling mean and is calculated by averaging data of the time series within k periods of time.

How do you calculate the rolling average in pandas?

Explaining the Pandas Rolling () Function. To calculate a moving average in Pandas, you combine the rolling () function with the mean () function. Let’s take a moment to explore the rolling () function in Pandas: The window parameter determines the number of observations used to calculate a statistic.

How to calculate moving average in Python?

In Python, we can calculate the moving average using .rolling () method. This method provides rolling windows over the data, and we can use the mean function over these windows to calculate moving averages. The size of the window is passed as a parameter in the function .rolling (window).

How do you use rolling windows to calculate moving averages?

This method provides rolling windows over the data, and we can use the mean function over these windows to calculate moving averages. The size of the window is passed as a parameter in the function .rolling (window). Now let’s see an example of how to calculate a simple rolling mean over a period of 30 days.


2 Answers

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 web import matplotlib.pyplot as plt import datetime plt.style.use('ggplot')  # Input variables start = datetime.datetime(2016, 1, 01) end = datetime.datetime(2018, 3, 29) stock = 'WFC'  # Extrating data df = 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

like image 41
Martin598 Avatar answered Sep 23 '22 13:09

Martin598


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_*, and pd.ewm* were module level functions and are now deprecated. These are replaced by using the Rolling, Expanding and EWM. 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 
like image 126
Romain Avatar answered Sep 21 '22 13:09

Romain