learn-algorithmic-trading/courses/sources/sec2/macd.py

97 lines
3.1 KiB
Python

import os
import time
import statistics
from matplotlib.pyplot import legend, ylabel
import pandas as pd
import numpy as np
from pandas_datareader import data
dir_path = os.path.dirname(os.path.realpath(__file__))
start_date = '2014-01-01'
end_date = '2018-01-01'
SRC_DATA_FILENAME = dir_path + '/goog_data.pkl'
try:
goog_data = pd.read_pickle(SRC_DATA_FILENAME)
print('File data found...reading GOOG data')
except FileNotFoundError:
print('File not found...downloading the GOOG data')
goog_data = data.DataReader('GOOG', 'yahoo', start_date, end_date)
goog_data.to_pickle(SRC_DATA_FILENAME)
goog_data_signal = pd.DataFrame(index=goog_data.index)
goog_data_signal['price'] = goog_data['Adj Close']
close = goog_data_signal['price']
exe_start_time = time.time()
""" Calculate MACD """
num_periods_fast = 10 # fast EMA time period
K_fast = 2/(num_periods_fast+1)
ema_fast = 0
num_periods_slow = 40 # slow EMA time period
K_slow = 2/(num_periods_slow+1)
ema_slow = 0
num_periods_macd = 20 # MACD EMA time period
K_macd = 2/(num_periods_macd+1)
ema_macd=0
ema_fast_values = []
ema_slow_values = []
macd_values = []
macd_signal_values = []
macd_histogram_values = []
for close_price in close:
if (ema_fast == 0):
ema_fast = close_price
ema_slow = close_price
else:
ema_fast = (close_price - ema_fast) * K_fast + ema_fast
ema_slow = (close_price - ema_slow) * K_slow + ema_slow
ema_fast_values.append(ema_fast)
ema_slow_values.append(ema_slow)
macd = ema_fast - ema_slow # calculate MACD
# Based on APO(MACD), calculate EMA_MACD
if ema_macd == 0:
ema_macd = macd
else:
ema_macd = (macd - ema_macd) * K_slow + ema_macd
macd_values.append(macd)
macd_signal_values.append(ema_macd)
macd_histogram_values.append(macd - ema_macd)
""" Visualization """
# assign data back to goog_data to get index and aligned
goog_data = goog_data.assign(ClosePrice=pd.Series(close, index=goog_data.index))
goog_data = goog_data.assign(Fast_EMA_110Days=pd.Series(ema_fast_values, index=goog_data.index))
goog_data = goog_data.assign(Slow_EMA_140Days=pd.Series(ema_slow_values, index=goog_data.index))
goog_data = goog_data.assign(MACD=pd.Series(macd_values, index=goog_data.index))
goog_data = goog_data.assign(EMA_of_MACD_120Days=pd.Series(macd_signal_values, index=goog_data.index))
goog_data = goog_data.assign(MACDHistogram=pd.Series(macd_histogram_values, index=goog_data.index))
print(goog_data['MACDHistogram'])
import matplotlib.pyplot as plt
fig = plt.figure()
ax1 = fig.add_subplot(311, ylabel='Google price in $')
goog_data['ClosePrice'].plot(ax=ax1, color='g', lw=2., legend=True)
goog_data['Fast_EMA_110Days'].plot(ax=ax1, color='b', lw=2., legend=True)
goog_data['Slow_EMA_140Days'].plot(ax=ax1, color='r', lw=2., legend=True)
ax2 = fig.add_subplot(312, ylabel='MACD')
goog_data['MACD'].plot(ax=ax2, color='black', lw=2., legend=True)
goog_data['EMA_of_MACD_120Days'].plot(ax=ax2, color='g', lw=2., legend=True)
ax3 = fig.add_subplot(313, ylabel='MACD')
goog_data['MACDHistogram'].plot(ax=ax3, color='r', kind='bar', legend=True, use_index=False)
plt.savefig(dir_path + "/macd.png")
plt.show()