Simple and Exponential Moving Average with Python and Pandas

How to Calculate the Moving Average with Pyhton

In this tutorial, we will cover how to calculate the Simple Moving Average (MA) and the Exponential Moving Average (EMA) of a Time Series using the Pandas library in Python.

We will also take a brief look at what the Simple Moving Average and the Exponential Aveareg is.

What is the Moving Average?

Moving Average Explained

The Moving Average is calcualted to identify the trend direction of a stock.

  • The Moving Average can be used to determine the support and restance levels.
  • Often categorized as a lagging indicator, as it is trendfollowing.
  • The longer period used, the greater the lag.
  • The 50-day and 200-day Moving Averages are considered by many the as important trading signals.
Simple and Exponential Moving Average
  • The Simple Moving Average is taking the arithmetic mean over a specific number of days.
  • The Exponential Moving Average is a weighted average with more importance in recent days. This makes it a more responsive indicator.

Watch how to calculate the Moving Average with Python

See the video to see how it can be done using the Python library pandas or see the code below.

Volatility and Moving Average using Python library pandas

Step 1: Read some Financial Historic Time Series Stock Prices

We will use Pandas DataReader to read some historic stock prices. See this tutorial for details.

import pandas_datareader as pdr
from datetime import datetime
ticker = "AAPL"
start = datetime(2019, 1, 1)
data = pdr.get_data_yahoo(ticker, start)  # You can also add end-date
print(data.head())

Resulting in this.

                 High        Low       Open      Close       Volume  Adj Close
Date                                                                          
2019-01-02  39.712502  38.557499  38.722500  39.480000  148158800.0  38.505024
2019-01-03  36.430000  35.500000  35.994999  35.547501  365248800.0  34.669640
2019-01-04  37.137501  35.950001  36.132500  37.064999  234428400.0  36.149662
2019-01-07  37.207500  36.474998  37.174999  36.982498  219111200.0  36.069202
2019-01-08  37.955002  37.130001  37.389999  37.687500  164101200.0  36.756794

Step 2: Calculate the Simple Moving Average with Python and Pandas

Calculating the Simple Moving Average (MA) of the data can be done using the rolling and mean methods.

data['MA10'] = data['Close'].rolling(10).mean()

Where here we calculate the Simple Moving Average of 10 days. You can change it to fit your needs.

Step 3: Calculate the Exponential Moving Average with Python and Pandas

It is a bit more involved to calculate the Exponential Moving Average.

data['EMA10'] = data['Close'].ewm(span=10, adjust=False).mean()

There you need to set the span and adjust it to False. This is needed to get the same numbers as on Yahoo! Finance.

Bonus: Visualize the result

If you want to see the data on a chart you can use the following code.

import pandas_datareader as pdr
from datetime import datetime
import matplotlib.pyplot as plt
data = pdr.get_data_yahoo('AAPL', datetime(2021,1,1))
data['MA50'] = data['Close'].rolling(50).mean()
data['EMA50'] = data['Close'].ewm(span=50, adjust=False).mean()
data[['Close', 'MA50', 'EMA50']].plot(figsize=(10,8))

This should result in a chart similar to this one.

Apple stock price with the MA50 and EMA50 indicators

Want to learn more?

This is part of a 2-hour full video course in 8 parts about Technical Analysis with Python.

If you are serious about learning Python for Finance check out this course.

  • Learn Python for Finance with pandas and NumPy.
  • 21 hours of video in over 180 lectures.
  • “Excellent course for anyone trying to learn to code and invest.” – Lorenzo B.

Get Python for Finance HERE.

Python for Finance

12% Investment Solution

Would you like to get a 12% return on your investments?

D. A. Carter promises and shows how his simple investment strategy will deliver that in the book The 12% Solution. The book shows how to test this statement by using backtesting.

Did Carter find a strategy that will consistently beat the market?

Actually, it is not that hard to use Python to validate his calculations. But we can do better than that. If you want to work smarter than traditional investors then continue to read here.

Learn Python

Learn Python A BEGINNERS GUIDE TO PYTHON

  • 70 pages to get you started on your journey to master Python.
  • How to install your setup with Anaconda.
  • Written description and introduction to all concepts.
  • Jupyter Notebooks prepared for 17 projects.

Python 101: A CRASH COURSE

  1. How to get started with this 8 hours Python 101: A CRASH COURSE.
  2. Best practices for learning Python.
  3. How to download the material to follow along and create projects.
  4. A chapter for each lesson with a descriptioncode snippets for easy reference, and links to a lesson video.

Expert Data Science Blueprint

Expert Data Science Blueprint

  • Master the Data Science Workflow for actionable data insights.
  • How to download the material to follow along and create projects.
  • A chapter to each lesson with a Description, Learning Objective, and link to the lesson video.

Machine Learning

Machine Learning – The Simple Path to Mastery

  • How to get started with Machine Learning.
  • How to download the material to follow along and make the projects.
  • One chapter for each lesson with a Description, Learning Objectives, and link to the lesson video.

Leave a Comment