Investing with Python: MACD

Python streamlines tasks requiring multiple steps in a single block of code. For this reason, it is a great tool for querying and performing analysis on data.

In this post, we outline steps for calculating a stock’s MACD indicator. But first, what is MACD (Moving Average Convergence/Divergence)?

Developed by Gerald Appel in the late seventies, MACD is one of the simplest and most effective momentum indicators available. MACD turns two trend-following indicators, moving averages, into a momentum oscillator by subtracting the longer moving average from the shorter moving average. As a result, MACD offers the best of both worlds: trend following and momentum.

To calculate MACD, the formula is:

MACD: (12-day EMA - 26-day EMA)

EMA stands for Exponential Moving Average.

With that background, let’s use Python to compute MACD.

1. Start with the 30 Day Moving Average Tutorial code.

import pandas as pd
import pandas.io.data as web

stocks = ['FB']
def get_stock(stock, start, end):
     return web.get_data_yahoo(stock, start, end)['Adj Close']
px = pd.DataFrame({n: get_px(n, '1/1/2016', '12/31/2016') for n in names})
px

2. Compute the 26 Day Exponential Moving Average. We must call the column by the stock ticker.

px['26 ema'] = pd.ewma(px["FB"], span=26)

3. Then the 12 Day Exponential Moving Average.

px['12 ema'] = pd.ewma(px["FB"], span=12)

4. Subtract the 26 Day EMA from the 12 Day EMA, arriving at the MACD.

px['MACD'] = (px['12 ema'] - px['26 ema'])

5. Plot close price against MACD.

px.plot(y= ['FB'], title='FB')
px.plot(y= ['MACD'], title='MACD')

There you have it! We created our MACD indicator. Here’s the full code:

import pandas.io.data as web
import pandas as pd
%matplotlib inline
import matplotlib.pyplot as plt

names = ['FB']
def get_px(stock, start, end): 
     return web.get_data_yahoo(stock, start, end)['Adj Close']
px = pd.DataFrame({n: get_px(n, '1/1/2016', '1/17/2017') for n in names})
px['26 ema'] = pd.ewma(px["FB"], span=26)
px['12 ema'] = pd.ewma(px["FB"], span=12)
px['MACD'] = (px['12 ema'] - px['26 ema'])
px.plot(y= ['FB'], title='FB')
px.plot(y= ['MACD'], title='MACD')

So when would you enter the position 😕 ?