git-svn-id: http://moon:8086/svn/projects/Stock@302 fda53097-d464-4ada-af97-ba876c37ca34
This commit is contained in:
2019-12-13 18:38:23 +00:00
parent ca3c143522
commit 03e36d74cc
4 changed files with 168 additions and 26 deletions
+40
View File
@@ -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()
+25
View File
@@ -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()
+64 -26
View File
@@ -101,9 +101,14 @@ titles.append('AAPL')
titles.append('XLNX') titles.append('XLNX')
titles.append('QCOM') titles.append('QCOM')
titles.append('DPW.DE') 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' filename = title + '.h5'
fetch = False fetch = False
today = dt.date.today() today = dt.date.today()
@@ -111,11 +116,14 @@ for title in titles:
try: try:
hdf = pd.HDFStore(filename, 'r') hdf = pd.HDFStore(filename, 'r')
hdf.close() hdf.close()
except IOError as e: except:
fetch = True fetch = True
lastmodified = dt.datetime.fromtimestamp(os.stat(filename).st_mtime).date() try:
if lastmodified != today: lastmodified = dt.datetime.fromtimestamp(os.stat(filename).st_mtime).date()
if lastmodified != today:
fetch = True
except:
fetch = True fetch = True
if fetch: if fetch:
@@ -131,30 +139,60 @@ for title in titles:
data = hdf[title] data = hdf[title]
hdf.close() hdf.close()
def show(title):
data['ema'] = ema(data, key='close', alpha=0.75) k_euro = 1/1.11
data['macd'] = macd(data, key='close')
data['sma'] = sma(data, key='close', window_days=30)
boll = bollinger(data, window_days=30)
plt.subplot(311) filename = title + '.h5'
plt.title(title)
data['close'].plot()
data['ema'].plot()
data['sma'].plot()
plt.legend()
plt.grid()
plt.subplot(312) hdf = pd.HDFStore(filename, 'r')
boll['upper'].plot() data_full = hdf[title]*k_euro
boll['mid'].plot()
boll['lower'].plot()
plt.legend()
plt.grid()
plt.subplot(313) data_full['ema'] = ema(data_full, key='close', alpha=0.75)
data['macd'].plot() data_full['macd'] = macd(data_full, key='close')
plt.legend() data_full['sma'] = sma(data_full, key='close', window_days=30)
plt.grid() 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)
+39
View File
@@ -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()