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

58 lines
1.7 KiB
Python
Raw Normal View History

import os
import time
import statistics
from matplotlib.pyplot import 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 EMA """
num_periods = 20 # number of days over which to average
K = 2/(num_periods + 1) # smoothing constant
ema_p = 0
ema_values = []
for close_price in close:
if (ema_p == 0):
# first observation, EMA = current price
ema_p = close_price
else:
ema_p = (close_price - ema_p) * K + ema_p
ema_values.append(ema_p)
goog_data = goog_data.assign(ClosePrice=pd.Series(close, index=goog_data.index))
goog_data = goog_data.assign(Exponential120DayMovingAverage=pd.Series(ema_values, index=goog_data.index))
close_price = goog_data['ClosePrice']
ema = goog_data['Exponential120DayMovingAverage']
""" Draw plot """
import matplotlib.pyplot as plt
fig = plt.figure()
ax1 = fig.add_subplot(111, ylabel='Google price in $')
close_price.plot(ax=ax1, color='g', lw=2., legend=True)
ema.plot(ax=ax1, color='b', lw=2., legend=True)
plt.savefig(dir_path + '/ema.png')
plt.show()