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

54 lines
1.7 KiB
Python

import os
import time
import statistics
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 momentum """
time_period = 20 # lookback period
history = [] # history of observed prices to use in momentum calculation
mom_values = [] # track momentum values for visualization purposes
for close_price in close:
history.append(close_price)
if len(history) > time_period:
del(history[0])
mom = close_price - history[0]
mom_values.append(mom)
goog_data = goog_data.assign(ClosePrice=pd.Series(close, index=goog_data.index))
goog_data = goog_data.assign(MomentumFromPrice20DaysAgo=pd.Series(mom_values, index=goog_data.index))
""" Visualization """
import matplotlib.pyplot as plt
fig = plt.figure()
ax1 = fig.add_subplot(211, ylabel='Google price in $')
goog_data['ClosePrice'].plot(ax=ax1, color='g', lw=2., legend=True)
ax2 = fig.add_subplot(212, ylabel='Momentum in $')
goog_data['MomentumFromPrice20DaysAgo'].plot(ax=ax2, color='b', lw=2., legend=True)
plt.savefig(dir_path + '/momentum.png')
plt.show()