import pandas as pd import pandas_datareader.data as web import numpy as np import math import matplotlib.pyplot as plt import datetime as dt import os # Stock Investors Financial Math # https://www.fmlabs.com/reference/default.htm?url=SimpleMA.htm # Alpha Vantage # https://www.alphavantage.co/documentation/ # Pandas # https://pandas.pydata.org/pandas-docs/stable/index.html # Knowledge # https://www.investopedia.com/articles/technical/02/050602.asp # https://ntguardian.wordpress.com/2016/09/19/introduction-stock-market-data-python-1 key = '0UO7Z2MVZ2YSQSVE' def ema(data, key, alpha=0.5, ic=None): result = [] if ic is None: r = data[key][0] else: r = ic for v in data[key]: r = alpha*r + (1-alpha)*v result.append(r) return np.array(result) def sma(data, key, window_days, ic=None): mem = [0] * window_days result = [] k=0 cumsum = 0 for v in data[key]: cumsum += (v - mem[k]) mem[k] = v k += 1 if k >= window_days: k=0 result.append(cumsum/window_days) return result def sd(data, key, window_days, ic=None): mem = [0] * window_days result = [] k=0 cumsum = 0 data_mean = data[key] - sma(data, key, window_days, ic) for v in data_mean: v2 = v * v cumsum += (v2 - mem[k]) mem[k] = v2 k += 1 if k >= window_days: k=0 var = max(0, cumsum) / window_days result.append(math.sqrt(var)) return result def colsum(data, keys): result = np.zeros(data.shape[0]) for key in keys: result += data[key] return result def macd(data, key): ema_short = ema(data, key, alpha=0.85) ema_long = ema(data, key, alpha=0.925) return ema_short - ema_long def bollinger(data, window_days, f=2): tp_ser = colsum(data, keys=['high', 'low', 'close']) / 3 tp_df = tp_ser.to_frame(name='tp') stddev = np.array(sd(tp_df, 'tp', window_days)) mid = np.array(sma(tp_df, key='tp', window_days=window_days)) upper = mid + f * stddev lower = mid - f * stddev result = pd.DataFrame(upper, index=data.index, columns=['upper']) result['lower'] = lower result['mid'] = mid return result data = {} titles = [] titles.append('AAPL') titles.append('XLNX') titles.append('QCOM') titles.append('DPW.DE') titles.append('CSCO') titles.append('AIR') show_title = 'QCOM' show_range_days = 20 pd.DatetimeIndex def fetch(title): filename = title + '.h5' fetch = False today = dt.date.today() try: hdf = pd.HDFStore(filename, 'r') hdf.close() except: fetch = True try: lastmodified = dt.datetime.fromtimestamp(os.stat(filename).st_mtime).date() if lastmodified != today: fetch = True except: fetch = True if fetch: print ("Fetching \"{}\"".format(title)) # Get stock price via data reader start = dt.datetime(2019,1,1) end = dt.date.today() data = web.DataReader(title, "av-daily", start, end, api_key=key) hdf = pd.HDFStore(title + '.h5') hdf[title] = data else: hdf = pd.HDFStore(filename, 'r') data = hdf[title] hdf.close() def show(title): k_euro = 1/1.11 filename = title + '.h5' hdf = pd.HDFStore(filename, 'r') data_full = hdf[title]*k_euro data_full['ema'] = ema(data_full, key='close', alpha=0.75) data_full['macd'] = macd(data_full, key='close') data_full['sma'] = sma(data_full, key='close', window_days=30) boll_full = bollinger(data_full, window_days=30) hdf.close() data = data_full[len(data_full)-1 - show_range_days:] boll = boll_full[len(boll_full)-1 - show_range_days:] dates = data.index fig = plt.figure(1) ax = plt.subplot(311) def hover(event): if event.inaxes == ax: x_idx = int(event.xdata) ax.format_xdata = lambda x: dates[x_idx] ax.format_ydata = lambda y: '{:.2f}'.format(data['close'][x_idx]) fig.canvas.mpl_connect("motion_notify_event", hover) data['close'].plot() data['ema'].plot() data['sma'].plot() plt.title(title) plt.legend() plt.grid() plt.subplot(312) boll['upper'].plot() boll['mid'].plot() boll['lower'].plot() plt.legend() plt.grid() plt.subplot(313) data['macd'].plot() plt.legend() plt.grid() plt.show() for title in titles: fetch(title) show(show_title)