From 03e36d74cc5f8f00dcaa29ec5fa2626671f10f26 Mon Sep 17 00:00:00 2001 From: Jens Ahrensfeld Date: Fri, 13 Dec 2019 18:38:23 +0000 Subject: [PATCH] improved git-svn-id: http://moon:8086/svn/projects/Stock@302 fda53097-d464-4ada-af97-ba876c37ca34 --- date_plot.py | 40 ++++++++++++++++++++++ mpl_test.py | 25 ++++++++++++++ pandas_eval.py | 90 +++++++++++++++++++++++++++++++++++--------------- picker.py | 39 ++++++++++++++++++++++ 4 files changed, 168 insertions(+), 26 deletions(-) create mode 100644 date_plot.py create mode 100644 mpl_test.py create mode 100644 picker.py diff --git a/date_plot.py b/date_plot.py new file mode 100644 index 0000000..7c1dd4c --- /dev/null +++ b/date_plot.py @@ -0,0 +1,40 @@ +import numpy as np +import matplotlib.pyplot as plt +import matplotlib.dates as mdates +import matplotlib.cbook as cbook + +years = mdates.YearLocator() # every year +months = mdates.MonthLocator() # every month +years_fmt = mdates.DateFormatter('%Y') + +# Load a numpy structured array from yahoo csv data with fields date, open, +# close, volume, adj_close from the mpl-data/example directory. This array +# stores the date as an np.datetime64 with a day unit ('D') in the 'date' +# column. +with cbook.get_sample_data('/home/jens/Downloads/goog.npz') as datafile: + data = np.load(datafile)['price_data'] + +print (data) +fig, ax = plt.subplots() +ax.plot('date', 'adj_close', data=data) + +# format the ticks +ax.xaxis.set_major_locator(years) +ax.xaxis.set_major_formatter(years_fmt) +ax.xaxis.set_minor_locator(months) + +# round to nearest years. +datemin = np.datetime64(data['date'][0], 'Y') +datemax = np.datetime64(data['date'][-1], 'Y') + np.timedelta64(1, 'Y') +ax.set_xlim(datemin, datemax) + +# format the coords message box +ax.format_xdata = mdates.DateFormatter('%Y-%m-%d') +ax.format_ydata = lambda y: '$%1.2f' % y # format the price. +ax.grid(True) + +# rotates and right aligns the x labels, and moves the bottom of the +# axes up to make room for them +fig.autofmt_xdate() + +plt.show() \ No newline at end of file diff --git a/mpl_test.py b/mpl_test.py new file mode 100644 index 0000000..438232c --- /dev/null +++ b/mpl_test.py @@ -0,0 +1,25 @@ +from matplotlib import pyplot as plt + +class LineBuilder: + def __init__(self, line): + self.line = line + self.xs = list(line.get_xdata()) + self.ys = list(line.get_ydata()) + self.cid = line.figure.canvas.mpl_connect('button_press_event', self) + + def __call__(self, event): + print('click', event) + if event.inaxes!=self.line.axes: return + self.xs.append(event.xdata) + self.ys.append(event.ydata) + self.line.set_data(self.xs, self.ys) + self.line.figure.canvas.draw() + +fig = plt.figure() +ax = fig.add_subplot(111) +ax.set_title('click to build line segments') +line, = ax.plot([0], [0]) # empty line +linebuilder = LineBuilder(line) + +plt.show() + diff --git a/pandas_eval.py b/pandas_eval.py index 8804738..d757fdd 100644 --- a/pandas_eval.py +++ b/pandas_eval.py @@ -101,9 +101,14 @@ titles.append('AAPL') titles.append('XLNX') titles.append('QCOM') titles.append('DPW.DE') +titles.append('CSCO') +titles.append('AIR') -for title in titles: +show_title = 'QCOM' +show_range_days = 20 +pd.DatetimeIndex +def fetch(title): filename = title + '.h5' fetch = False today = dt.date.today() @@ -111,11 +116,14 @@ for title in titles: try: hdf = pd.HDFStore(filename, 'r') hdf.close() - except IOError as e: + except: fetch = True - lastmodified = dt.datetime.fromtimestamp(os.stat(filename).st_mtime).date() - if lastmodified != today: + try: + lastmodified = dt.datetime.fromtimestamp(os.stat(filename).st_mtime).date() + if lastmodified != today: + fetch = True + except: fetch = True if fetch: @@ -131,30 +139,60 @@ for title in titles: data = hdf[title] hdf.close() +def show(title): -data['ema'] = ema(data, key='close', alpha=0.75) -data['macd'] = macd(data, key='close') -data['sma'] = sma(data, key='close', window_days=30) -boll = bollinger(data, window_days=30) + k_euro = 1/1.11 -plt.subplot(311) -plt.title(title) -data['close'].plot() -data['ema'].plot() -data['sma'].plot() -plt.legend() -plt.grid() + filename = title + '.h5' -plt.subplot(312) -boll['upper'].plot() -boll['mid'].plot() -boll['lower'].plot() -plt.legend() -plt.grid() + hdf = pd.HDFStore(filename, 'r') + data_full = hdf[title]*k_euro -plt.subplot(313) -data['macd'].plot() -plt.legend() -plt.grid() + 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 = bollinger(data_full, window_days=30) + hdf.close() -plt.show() + data = data_full[len(data_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) diff --git a/picker.py b/picker.py new file mode 100644 index 0000000..ec924f6 --- /dev/null +++ b/picker.py @@ -0,0 +1,39 @@ +""" +compute the mean and stddev of 100 data sets and plot mean vs stddev. +When you click on one of the mu, sigma points, plot the raw data from +the dataset that generated the mean and stddev +""" +import numpy as np +import matplotlib.pyplot as plt + +X = np.random.rand(100, 1000) +xs = np.mean(X, axis=1) +ys = np.std(X, axis=1) + +fig = plt.figure() +ax = fig.add_subplot(111) +ax.set_title('click on point to plot time series') +line, = ax.plot(xs, ys, 'o', picker=5) # 5 points tolerance + + +def onpick(event): + + if event.artist!=line: return True + + N = len(event.ind) + if not N: return True + + + figi = plt.figure() + for subplotnum, dataind in enumerate(event.ind): + ax = figi.add_subplot(N,1,subplotnum+1) + ax.plot(X[dataind]) + ax.text(0.05, 0.9, 'mu=%1.3f\nsigma=%1.3f'%(xs[dataind], ys[dataind]), + transform=ax.transAxes, va='top') + ax.set_ylim(-0.5, 1.5) + figi.show() + return True + +fig.canvas.mpl_connect('pick_event', onpick) + +plt.show() \ No newline at end of file