In this tutorial we will calculate and visualize the MACD for a stock price.
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)
First we want to calcite the MACD.
The calculation (12-26-9 MACD (default)) is defined as follows.
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?
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.
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.
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.
Build and Deploy an AI App with Python Flask, OpenAI API, and Google Cloud: In…
Python REST APIs with gcloud Serverless In the fast-paced world of application development, building robust…
App Development with Python using Docker Are you an aspiring app developer looking to level…
Why Value-driven Data Science is the Key to Your Success In the world of data…
Harnessing the Power of Project-Based Learning and Python for Machine Learning Mastery In today's data-driven…
Is Python the right choice for Machine Learning? Should you learn Python for Machine Learning?…