Calculate MACD with Pandas DataFrames

What will we cover?

In this tutorial we will calculate and visualize the MACD for a stock price.

Step 1: Retrieve stock prices into a DataFrame (Pandas)

Let’s get started. You can get the CSV file from here or get your own from Yahoo! Finance.

import pandas as pd
import matplotlib.pyplot as plt
%matplotlib notebook
data = pd.read_csv("AAPL.csv", index_col=0, parse_dates=True)

Step 2: Calculate the MACD indicator with Pandas DataFrame

First we want to calcite the MACD.

The calculation (12-26-9 MACD (default)) is defined as follows.

  • MACD=12-Period EMA − 26-Period EMA
  • Singal line 9-Perioed EMA of MACD

Where EMA is the Exponential Moving Average we learned about in the last lesson.

exp1 = data['Close'].ewm(span=12, adjust=False).mean()exp2 = data['Close'].ewm(span=26, adjust=False).mean()data['MACD'] = exp1 - exp2data['Signal line'] = data['MACD'].ewm(span=9, adjust=False).mean()

Now that was simple, right?

Step 3: Visualize the MACD with matplotlib

To visualize it you can use the following with Matplotlib.

fig, ax = plt.subplots()
data[['MACD', 'Signal line']].plot(ax=ax)
data['Close'].plot(ax=ax, alpha=0.25, secondary_y=True)

Resulting in an output similar to this one.

Want to learn more?

This is part of the course of Master Technical Analysis with pandas.

In the next lesson you will learn how to calculate Stochastic Oscillator 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