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.
Python for Finance: Unlock Financial Freedom and Build Your Dream Life
Discover the key to financial freedom and secure your dream life with Python for Finance!
Say goodbye to financial anxiety and embrace a future filled with confidence and success. If you’re tired of struggling to pay bills and longing for a life of leisure, it’s time to take action.
Imagine breaking free from that dead-end job and opening doors to endless opportunities. With Python for Finance, you can acquire the invaluable skill of financial analysis that will revolutionize your life.
Make informed investment decisions, unlock the secrets of business financial performance, and maximize your money like never before. Gain the knowledge sought after by companies worldwide and become an indispensable asset in today’s competitive market.
Don’t let your dreams slip away. Master Python for Finance and pave your way to a profitable and fulfilling career. Start building the future you deserve today!
Python for Finance a 21 hours course that teaches investing with Python.
Learn pandas, NumPy, Matplotlib for Financial Analysis & learn how to Automate Value Investing.
“Excellent course for anyone trying to learn coding and investing.” – Lorenzo B.
