65 lines
2.2 KiB
Python
65 lines
2.2 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 = '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']
|
||
|
|
||
|
exe_start_time = time.time()
|
||
|
|
||
|
import statistics as stats
|
||
|
|
||
|
time_period = 20 # number of days over which to average
|
||
|
history = [] # to track a history of prices
|
||
|
sma_values = [] # to track simple moving average values
|
||
|
|
||
|
for close_price in goog_data_signal['price']:
|
||
|
history.append(close_price)
|
||
|
if len(history) > time_period:
|
||
|
# we remove oldest price because we only average over last 'time_period' prices
|
||
|
# i.e. keep the latest 20 day window
|
||
|
del(history[0])
|
||
|
sma_values.append(stats.mean(history))
|
||
|
# The first 20 sma of this data will not be mean of 20 values
|
||
|
|
||
|
print("--- algo1: %s seconds ---" % (time.time() - exe_start_time))
|
||
|
|
||
|
exe_start_time = time.time()
|
||
|
|
||
|
sma_values_improved = goog_data_signal.rolling(window=20, win_type='boxcar').mean()
|
||
|
|
||
|
print("--- algo2: %s seconds ---" % (time.time() - exe_start_time))
|
||
|
|
||
|
goog_data = goog_data.assign(ClosePrice=pd.Series(goog_data_signal['price'], index=goog_data.index))
|
||
|
goog_data = goog_data.assign(Simple20DayMovingAverage=pd.Series(sma_values, index=goog_data.index))
|
||
|
goog_data = goog_data.assign(Simple20DayMovingAverage_pd = sma_values_improved)
|
||
|
close_price = goog_data['ClosePrice']
|
||
|
sma = goog_data['Simple20DayMovingAverage']
|
||
|
|
||
|
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)
|
||
|
sma.plot(ax=ax1, color='r', lw=2., legend=True)
|
||
|
goog_data['Simple20DayMovingAverage_pd'].plot(ax=ax1, color='b', lw=1., legend=True)
|
||
|
plt.savefig(dir_path+'/sma.png')
|
||
|
plt.show()
|