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


Resulting in this.

                 High        Low       Open      Close       Volume  Adj Close
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 the course of Master Technical Analysis with pandas.

In the next lesson you will learn about Calculating MACD with Pandas DataFrames.

12% Investment Solution

Would you like to get 12% in return of 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.


Recent Posts

Build and Deploy an AI App

Build and Deploy an AI App with Python Flask, OpenAI API, and Google Cloud: In…

5 days ago

Building Python REST APIs with gcloud Serverless

Python REST APIs with gcloud Serverless In the fast-paced world of application development, building robust…

5 days ago

Accelerate Your Web App Development Journey with Python and Docker

App Development with Python using Docker Are you an aspiring app developer looking to level…

6 days ago

Data Science Course Made Easy: Unlocking the Path to Success

Why Value-driven Data Science is the Key to Your Success In the world of data…

2 weeks ago

15 Machine Learning Projects: From Beginner to Pro

Harnessing the Power of Project-Based Learning and Python for Machine Learning Mastery In today's data-driven…

2 weeks ago

Unlock the Power of Python: 17 Project-Based Lessons from Zero to Machine Learning

Is Python the right choice for Machine Learning? Should you learn Python for Machine Learning?…

2 weeks ago