Update – Investing with Python: MACD

Download the accompanying IPython Notebook for this Tutorial from Github. 

I received a question from Sam Khorsand about applying the Python Tutorial: MACD (Moving Average Convergence/Divergence) Tutorial   to multiple stocks. The code below will produce yesterday’s MACD Crossover for a list of stocks. Also, by adding ‘to_string(index = False’), you can clean up the date formatting. Enjoy!

import pandas as pd
from pandas_datareader import data as web
import matplotlib.pyplot as plt
import datetime as dt
%matplotlib inline

def MACD(stock, start, end):
    df = pd.DataFrame(web.DataReader(stock,'google',start,end)['Close'])
    df = df.reset_index()
    df['30 mavg'] = pd.rolling_mean(df['Close'], 30)
    df['26 ema'] = pd.ewma(df['Close'], span=26)
    df['12 ema'] = pd.ewma(df['Close'], span=12)
    df['MACD'] = (df['12 ema'] - df['26 ema'])
    df['Signal'] = pd.ewma(df['MACD'], span=9)
    df['Crossover'] = df['MACD'] - df['Signal']
    return stock, df['Date'][-1:].to_string(),df['Crossover'][-1:].mean()
    

stocks = ['FB', 'AAPL', 'GOOG', 'AMZN', 'TSLA']

d = []

for stock in stocks:
    stock, date, macd = MACD(stock, '1/1/2016', dt.datetime.today())
    d.append({'Stock':stock, 'Date':date, 'MACD':macd})
    
df2 = pd.DataFrame(d)
df2[['Date', 'Stock', 'MACD']]
Date Stock MACD
0 249 2017-09-20 FB -0.211440
1 249 2017-09-20 AAPL -0.828956
2 249 2017-09-20 GOOG -0.069812
3 249 2017-09-20 AMZN 1.028655
4 249 2017-09-20 TSLA 2.287354