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

73 lines
2.4 KiB
Python
Raw Normal View History

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()
import statistics as stats
import math as math
time_period = 20 # history length for Simple Moving Average for middle band
stdev_factor = 2 # Standard Deviation Scaling factor for the upper and lower bands
history = []
sma_values = []
upper_band = []
lower_band = []
""" Calculate BBAND """
for close_price in close:
history.append(close_price)
if len(history) > time_period:
del(history[0])
sma = stats.mean(history) # BBAND_Middle
sma_values.append(sma)
variance = 0
# Calculate variance using pure python
for hist_price in history:
variance = variance + ((hist_price - sma) ** 2)
stdev = math.sqrt(variance / len(history))
upper_band.append(sma + stdev_factor * stdev)
lower_band.append(sma - stdev_factor * stdev)
""" Draw Gragh """
goog_data = goog_data.assign(ClosePrice=pd.Series(close, index=goog_data.index))
goog_data = goog_data.assign(MiddleBollingerBand20DaySMA=pd.Series(sma_values, index=goog_data.index))
goog_data = goog_data.assign(UpperBollingerBand20DaysSMA2StddevFactor=pd.Series(upper_band, index=goog_data.index))
goog_data = goog_data.assign(LowerBollingerBand20DaysSMA2StddevFactor=pd.Series(lower_band, index=goog_data.index))
import matplotlib.pyplot as plt
fig = plt.figure()
ax1 = fig.add_subplot(111, ylabel='Google price in $')
goog_data['ClosePrice'].plot(ax=ax1, color='g', lw=2., legend=True)
goog_data['MiddleBollingerBand20DaySMA'].plot(ax=ax1, color='b', lw=2., legend=True)
goog_data['UpperBollingerBand20DaysSMA2StddevFactor'].plot(ax=ax1, color='y', lw=2., legend=True)
goog_data['LowerBollingerBand20DaysSMA2StddevFactor'].plot(ax=ax1, color='r', lw=2., legend=True)
plt.savefig(dir_path + '/bbands.png')
plt.show()