-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplot.py
More file actions
315 lines (259 loc) · 9.33 KB
/
Copy pathplot.py
File metadata and controls
315 lines (259 loc) · 9.33 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
# standard lib
import datetime
# 3rd party libs
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
def plot_price_volume(dates, values, volume, start_date, end_date):
'''
extract specified slice from total series, generate and return matplotlib figure for slice
'''
# extract desired time-slice from total series
if (dates[0] < dates[len(dates) - 1]):
start_idx = 0
for i in range(0, len(dates)):
if dates[i] <= start_date:
start_idx = i
else:
break
end_idx = 0
for i in range(0, len(dates)):
if dates[i] <= end_date:
end_idx = i
else:
break
else:
start_idx = 0
for i in range(0, len(dates)):
if dates[i] >= start_date:
start_idx = i
else:
break
end_idx = 0
for i in range(0, len(dates)):
if dates[i] >= end_date:
end_idx = i
else:
break
# swap if start_date after end_date
if (start_idx > end_idx):
(start_idx, end_idx) = (end_idx, start_idx)
# if start_date = end_date, use entire series
if (start_idx == end_idx):
start_idx = 0
end_idx = len(dates)
# cut slice
date_slice = dates[start_idx : end_idx]
slice_start_date = dates[start_idx]
slice_end_date = dates[end_idx]
values_slice = values[start_idx : end_idx]
volume_slice = volume[start_idx : end_idx]
# generate matplotlib plot
x = np.array(date_slice) #np.array(ords)
y = np.array(values_slice)
fig = plt.figure()
ax = fig.add_subplot(111)
fig.autofmt_xdate(rotation=90)
ax.plot(x,y, color='blue')
# leg = ax.legend(('Model length'), 'upper center', shadow=True)
v = np.array(volume_slice)
ax2 = ax.twinx()
fig.autofmt_xdate(rotation=90)
ax2.plot(x, v, color='yellow')
ax.grid(False)
ax.set_ylabel('Closing Price')
ax.set_title('Closing Price & Volume Traded')
fig.autofmt_xdate(rotation=90)
# date intervals & markers
(formatter, locator) = tick_info(slice_start_date, slice_end_date)
ax.xaxis.set_major_formatter(formatter)
ax.xaxis.set_major_locator(locator)
ax.set_xlim([slice_start_date, slice_end_date])
ax.set_xlabel('Date')
fig.autofmt_xdate(rotation=90)
#x2.set_xlim([0, np.e]);
ax2.set_ylabel('Volume Traded');
plt.setp(ax2.get_xticklabels(), visible=False)
plt.setp(ax2.get_xaxis ().get_label().set_visible(False))
#fig.autofmt_xdate(rotation=90)
#formatter = mpl.dates.DateFormatter(None)
#locator = mpl.dates.YearLocator(None)
#ax2.xaxis.set_major_formatter(formatter)
#ax2.xaxis.set_major_locator(locator)
#fig.autofmt_xdate()
return plt
def gen_intraday_volatility_plots(dates, high, low, close, start_date, end_date) :
# extract desired time-slice from total series
if (dates[0] < dates[len(dates) - 1]):
start_idx = 0
for i in range(0, len(dates)):
if dates[i] <= start_date:
start_idx = i
else:
break
end_idx = 0
for i in range(0, len(dates)):
if dates[i] <= end_date:
end_idx = i
else:
break
else:
start_idx = 0
for i in range(0, len(dates)):
if dates[i] >= start_date:
start_idx = i
else:
break
end_idx = 0
for i in range(0, len(dates)):
if dates[i] >= end_date:
end_idx = i
else:
break
# swap if start_date after end_date
if (start_idx > end_idx):
(start_idx, end_idx) = (end_idx, start_idx)
# if start_date = end_date, use entire series
if (start_idx == end_idx):
start_idx = 0
end_idx = len(dates)
# cut slice
date_slice = dates[start_idx : end_idx]
slice_start_date = dates[start_idx]
slice_end_date = dates[end_idx]
low_slice = low[start_idx : end_idx]
high_slice = high[start_idx : end_idx]
close_slice = close[start_idx : end_idx]
delta = []
for i in range(len(high_slice)):
delta.append(float(100 * (high_slice[i] - low_slice[i]) / close_slice[i]) )
# generate matplotlib plot
x = np.array(date_slice)
y = np.array(delta)
fever_fig = plt.figure()
ax = fever_fig.add_subplot(111)
ax.plot(x,y)
# leg = ax.legend(('Model length'), 'upper center', shadow=True)
ax.grid(False)
ax.set_ylabel('100 * (High - Low) / Close')
ax.set_title('Intra-Day Range as a Percentage of Closing Price')
# date intervals & markers
(formatter, locator) = tick_info(slice_start_date, slice_end_date)
ax.xaxis.set_major_formatter(formatter)
ax.xaxis.set_major_locator(locator)
fever_fig.autofmt_xdate(rotation=90)
ax.set_xlim([slice_start_date, slice_end_date])
ax.set_xlabel('Date')
# ------------
h = Histogram(delta)
left_edge = []
height = []
for bin in h.bins:
left_edge.append(float(bin.floor))
height.append(h.bin_contrib_perc(bin))
x = np.array(left_edge)
y = np.array(height)
dist_fig = plt.figure()
ax = dist_fig.add_subplot(111)
ax.bar(x, y, width=h.bins[0].range)
ax.set_xlim(h.min, h.max)
ax.set_ylabel('% of Population')
ax.set_xlabel('Intra-Day Range i.t.o Close : 100 * (High - Low) / Close')
ax.set_title('Distribution of Intra-Day Range')
return fever_fig, dist_fig
def gen_plot_png_for_symbol_period(symbol, start_date, end_date):
'''
get candlestick data for symbol from db,
generate and save plot,
return django media path to binary file as served by media server
'''
sym_ob = Symbol.objects.get(symbol=symbol)
candlesticks = DailyCandleSticks.objects.filter(symbol=sym_ob).order_by('date')
dates, openn, high, low, close, volume = [], [], [], [], [], []
for stick in candlesticks:
dates.append(stick.date)
openn.append(stick.open)
high.append(stick.high)
low.append(stick.low)
close.append(stick.close)
volume.append(stick.vol)
analyser = OHLCVAnalysis(dates, openn, high, low, close, volume, start_date, end_date)
report = analyser.report()
fig = gen_matplot_figure(dates, close, volume, start_date, end_date)
img_file_name = 'plot.png'
save_path = MEDIA_ROOT + '/' + img_file_name
fig.savefig(save_path)
fever_fig, dist_fig = gen_intraday_volatility_plots(dates, high, low, close, start_date, end_date)
intraday_volatility_fever_fname = 'intraday_volatility_fever.png'
save_path = MEDIA_ROOT + '/' + intraday_volatility_fever_fname
fever_fig.savefig(save_path)
intraday_volatility_dist_fname = 'intraday_volatility_dist.png'
save_path = MEDIA_ROOT + '/' + intraday_volatility_dist_fname
dist_fig.savefig(save_path)
return img_file_name, intraday_volatility_fever_fname, intraday_volatility_dist_fname, report
def tick_info(slice_start_date, slice_end_date):
'''
return appropriate - visually attractive and informative - (formatter, locator) for data series
'''
duration = slice_end_date - slice_start_date
day_count = duration.days
if (day_count < 0):
day_count = - day_count
desired_interval_count = 10
interval_day_length = day_count / desired_interval_count
formatter = None # '%Y-%m-%d'
locator = None
if interval_day_length > 365:
formatter = mpl.dates.DateFormatter('%Y')
locator = mpl.dates.YearLocator(10)
interval_year_length = interval_day_length / 365
elif interval_day_length > 30:
formatter = mpl.dates.DateFormatter('%Y-%m')
interval_month_length = interval_day_length / 30
locator = mpl.dates.MonthLocator(interval=int(interval_month_length))
else:
formatter = mpl.dates.DateFormatter('%Y-%m-%d')
locator = mpl.dates.DayLocator(interval=int(interval_day_length))
return (formatter, locator)
class Plot(object):
'''
houses plotting methods for simagora algo
'''
def save_fig(self, fig, fname):
fig.savefig(fname)
def plot_price_and_position(self):
'''
'''
aDate = np.array(date_slice)
aPrice = np.array(price_slice)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.grid(false)
fig.autofmt_xdate(rotation=90)
ax.plot(aDate, aPrice, color='blue')
# leg = ax.legend(('Model length'), 'upper center', shadow=True)
#~ v = np.array(volume_slice)
#~ ax2 = ax.twinx()
#~ fig.autofmt_xdate(rotation=90)
#~ ax2.plot(x, v, color='yellow')
#~ ax.set_ylabel('closing price')
#~ ax.set_title('closing price & volume traded')
#~ fig.autofmt_xdate(rotation=90)
# date intervals & markers
#~ (formatter, locator) = tick_info(slice_start_date, slice_end_date)
#~ ax.xaxis.set_major_formatter(formatter)
#~ ax.xaxis.set_major_locator(locator)
#~ ax.set_xlim([slice_start_date, slice_end_date])
#~ ax.set_xlabel('date')
#~ fig.autofmt_xdate(rotation=90)
##x2.set_xlim([0, np.e]);
#~ ax2.set_ylabel('volume traded');
#~ plt.setp(ax2.get_xticklabels(), visible=false)
#~ plt.setp(ax2.get_xaxis ().get_label().set_visible(false))
#~ #fig.autofmt_xdate(rotation=90)
#~ #formatter = mpl.dates.dateformatter(none)
#~ #locator = mpl.dates.yearlocator(none)
#~ #ax2.xaxis.set_major_formatter(formatter)
#~ #ax2.xaxis.set_major_locator(locator)
#~ #fig.autofmt_xdate()
return plt