Algorithmic Trading Strategy Using MACD & Python

Determine When To Buy & Sell Stock

Image for post
Image for post

In this article you will learn a simple trading strategy used to determine when to buy and sell stock using the Python programming language. More specifically you will learn how to perform algorithmic trading. It is extremely hard to try and predict the stock market momentum direction, but in this article I will give it a try. Even people with a good understanding of statistics and probabilities have a hard time doing this.

Algorithmic trading is a process for executing orders utilizing automated and pre-programmed trading instructions to account for variables such as price, timing and volume. -investopedia.com

Python is one of the hottest programming languages for finance along with others like C#, and R. The trading strategy that will be used in this article is called the MACD crossover.

Image for post
Image for post
MACD Chart

What Is MACD Crossover ?

The Moving Average Convergence Divergence (MACD) crossover is a technical indicator that uses the difference between exponential moving averages (EMA) to determine the momentum and the direction of the market. The MACD crossover occurs when the MACD line and the signal line intercept, often indicating a change in the momentum/trend of the market.

Components of the MACD:

  • The MACD indicator/line: The MACD line is the difference between the two exponential moving averages (usually the last 12 and 26 days or weeks) and is usually referred to as the faster line.
  • Signal line: The signal line is usually a 9 period exponentially smoothed average of the MACD line and will be referred to as the slower line.
  • Zero line: The MACD lines fluctuate above and below a zero line, giving the MACD the qualities of an oscillator.
  • Histogram: The histogram consists of vertical lines that show the spread between the two MACD lines.

    -dailyfx

In this article I will focus on the MACD indicator line and the signal line to determine when to buy and sell stock, however the use of the zero signal line and the histogram component can help and give you more insight into buying or selling an asset.

What Is MACD ?

MACD, short for moving average convergence/divergence, is a trading indicator used in technical analysis of stock prices, created by Gerald Appel in the late 1970s. It is designed to reveal changes in the strength, direction, momentum, and duration of a trend in a stock’s price. Wikipedia

The MACD is all about the convergence and divergence of the two moving averages.

How Is MACD Computed ?

The MACD indicator or line can be computed simply by subtracting the long term exponential moving average (e.g. 26 period EMA) from the short term exponential moving average (e.g. 12 period EMA).

MACD=12-Period EMA − 26-Period EMA

A positive MACD indicates that the 12-day EMA is above the 26-day EMA. Positive values increase as the shorter EMA diverges further from the longer EMA. This means upside momentum is increasing. Negative MACD values indicate that the 12-day EMA is below the 26-day EMA. Negative values increase as the shorter EMA diverges further below the longer EMA. This means downside momentum is increasing. school.stockcharts.com

Note: A positive MACD is above the zero line and a negative MACD is below the zero line.

When To Buy And Sell The Stock Using MACD ?

When the MACD indicator crosses the signal line this indicates a momentum shift in the stock price. For example if the MACD indicator is greater than the signal line this is considered a bullish crossover and indicates a good time to buy, and when the MACD indicator is less than the signal line, this is considered a bearish crossover and indicates a good time to sell.

Please leave claps on this article if you find it helpful or entertaining. I would also like to know some of your trading strategies as well in the response section.

If you prefer not to read this article and would like a video representation of it, you can check out the YouTube Video below. It goes through everything in this article with a little more detail, and will help make it easy for you to start programming even if you don’t have the programming language Python installed on your computer. Or you can use both as supplementary materials for learning !

If you are interested in reading more on machine learning and algorithmic trading then you might want to read Hands-On Machine Learning for Algorithmic Trading: Design and implement investment strategies based on smart algorithms that learn from data using Python. The book will show you how to implement machine learning algorithms to build, train, and validate algorithmic models. It will also show you how to create your own algorithmic design process to apply probabilistic machine learning approaches to trading decisions, and the book will show you how to develop neural networks for algorithmic trading to perform time series forecasting and smart analytics.

Image for post
Image for post

Hands-On Machine Learning for Algorithmic Trading: Design and implement investment strategies based on smart algorithms that learn from data using Python

Okay now with all of that out of the way, let’s start programming !

Start Programming:

I will start this program with a description.

#Description: This program uses the (MACD) crossover
# to determine when to buy and sell stock.

Import the dependencies.

#import the libraries
import pandas as pd
import numpy as np
from datetime import datetime
import matplotlib.pyplot as plt
plt.style.use('fivethirtyeight')

Next, load the data. Since I am using Googles website to program I need to use Google to upload the data file.

#Load the data 
from google.colab import files # Use to load data on Google Colab
uploaded = files.upload() # Use to load data on Google Colab

The file that I am uploading is a CSV file named ‘AAPL.csv’ that contains data (Date, Open Price, High Price, Close Price, Adj Close Price, & Volume) for the Apple Corporation stock price from Apr. 20, 2017 to Aug. 24, 2017.

Next, Store the data in a variable.

#Store the data into the df variable
df = pd.read_csv('AAPL.csv')

Now show the data.

#Set the date as the index for the data
df = df.set_index(pd.DatetimeIndex(df['Date'].values))
#Show the dataframe
df
Image for post
Image for post

Visually show the stock price.

# Visually Show The Stock Price(s)
# Create the title

title = 'Close Price History '
#Get the stocks
my_stocks = df
#Create and plot the graph
plt.figure(figsize=(12.2,4.5)) #width = 12.2in, height = 4.5
plt.plot( my_stocks['Close'], label='Close')#plt.plot( X-Axis , Y-Axis, line_width, alpha_for_blending, label)
plt.xticks(rotation=45)
plt.title(title)
plt.xlabel('Date',fontsize=18)
plt.ylabel('Price USD ($)',fontsize=18)
plt.show()
Image for post
Image for post

Calculate the MACD and Signal Line indicators.

#Calculate the MACD and Signal Line indicators
#Calculate the Short Term Exponential Moving Average

ShortEMA = df.Close.ewm(span=12, adjust=False).mean() #AKA Fast moving average
#Calculate the Long Term Exponential Moving Average
LongEMA = df.Close.ewm(span=26, adjust=False).mean() #AKA Slow moving average
#Calculate the Moving Average Convergence/Divergence (MACD)
MACD = ShortEMA - LongEMA
#Calcualte the signal line
signal = MACD.ewm(span=9, adjust=False).mean()

Plot the chart. I am interested to see when the two lines cross as that is an indication to either buy or sell the asset.

#Plot the chart
plt.figure(figsize=(12.2,4.5)) #width = 12.2in, height = 4.5
plt.plot(df.index, MACD, label='AAPL MACD', color = 'red')
plt.plot(df.index, signal, label='Signal Line', color='blue')
plt.xticks(rotation=45)
plt.legend(loc='upper left')
plt.show()
Image for post
Image for post

Create new columns for the data set and show the new data.

#Create new columns for the data frame 
df['MACD'] = MACD
df['Signal Line'] = signal
#Show the new data frame
df
Image for post
Image for post

Create a function to signal when to buy and sell the stock.

#Create a function to signal when to buy and sell an asset
def buy_sell(signal):
sigPriceBuy = []
sigPriceSell = []
flag = -1
for i in range(0,len(signal)):
#if MACD > signal line then buy else sell
if signal['MACD'][i] > signal['Signal Line'][i]:
if flag != 1:
sigPriceBuy.append(signal['Close'][i])
sigPriceSell.append(np.nan)
flag = 1
else:
sigPriceBuy.append(np.nan)
sigPriceSell.append(np.nan)
elif signal['MACD'][i] < signal['Signal Line'][i]:
if flag != 0:
sigPriceSell.append(signal['Close'][i])
sigPriceBuy.append(np.nan)
flag = 0
else:
sigPriceBuy.append(np.nan)
sigPriceSell.append(np.nan)
else: #Handling nan values
sigPriceBuy.append(np.nan)
sigPriceSell.append(np.nan)

return (sigPriceBuy, sigPriceSell)

Create buy and sell columns and show the data.

#Create buy and sell columns
x = buy_sell(df)
df['Buy_Signal_Price'] = x[0]
df['Sell_Signal_Price'] = x[1]
#Show the data frame
df
Image for post
Image for post

Visually show the stock buy and sell signals.

# Visually Show The Stock buy and sell signals
# Create the title

title = 'Close Price History Buy / Sell Signals '
#Get the stocks
my_stocks = df

#Create and plot the graph
plt.figure(figsize=(12.2,4.5)) #width = 12.2in, height = 4.5
plt.scatter(my_stocks.index, my_stocks['Buy_Signal_Price'], color = 'green', label='Buy Signal', marker = '^', alpha = 1)
plt.scatter(my_stocks.index, my_stocks['Sell_Signal_Price'], color = 'red', label='Sell Signal', marker = 'v', alpha = 1)
plt.plot( my_stocks['Close'], label='Close Price', alpha = 0.35)#plt.plot( X-Axis , Y-Axis, line_width, alpha_for_blending, label)
plt.xticks(rotation=45)
plt.title(title)
plt.xlabel('Date',fontsize=18)
plt.ylabel('Close Price USD ($)',fontsize=18)
plt.legend( loc='upper left')
plt.show()
Image for post
Image for post

From the graph above, it looks like for this time period on this particular asset, I would’ve profited by following this buy and sell strategy. By buying the stock at around $143 between Apr. 15, 2017 and May. 1, 2017 and selling it around $153 between the dates May 15, 2017 and Jun. 1, 2017 (where the indicators tell me to buy and sell), I would’ve have profited $10 per share.

By buying a share around $145 between the dates Jul. 1, 2017 and Jul. 15, 2017 and then selling those shares after Aug. 15, 2017 for about $157.5, I would’ve profited about $12.5 per share.

So, looks like by using this strategy for this data set. I would’ve come out with a total of $10 (per share 1) + $12.5 (per share 2). Not bad, however I also noticed that the indicators did not show the optimal time to buy or sell the stock. For example, it would’ve been more profitable to buy the stock at $142.5 on Apr. 15, 2017 and then sell the stock for about $156 between the dates May 1, 2017 and May 15, 2017 for a total profit of about $13.5 per share.

In conclusion, this looks like a promising strategy, but I only used 89 trading days to test it and only tested it on one asset. Much more testing is needed before a strategy like this should be implemented.

That’s it, we are done creating this program ! If you want to start an investment portfolio of your own, then sign up with WeBull using this link, deposit $100 and get 2 FREE stocks worth up to $1600 USD! It’s free stocks that you can either sell, or play with.

Thanks for reading this article I hope its helpful and entertaining to you all ! If you enjoyed this article and found it helpful please leave some claps to show your appreciation. Keep up the learning, and if you like machine learning, mathematics, computer science, programming or algorithm analysis, please visit and subscribe to my YouTube channels (randerson112358 & computer science).

Other Resources:

(1) Investopedia
(2) Moving Average Convergence Divergence
(3) When To Use And How To Read The MACD Indicator
(4) Data Source
(5) The MACD Indicator Explained: What It Is And How To Use It

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store