-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy pathDataHandler.py
More file actions
547 lines (464 loc) · 19 KB
/
DataHandler.py
File metadata and controls
547 lines (464 loc) · 19 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
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
from __future__ import print_function
import numpy as np
import os
import pandas as pd
import yfinance as yf
from abc import ABCMeta, abstractmethod
from Events import MarketEvent
class DataManagement(object):
"""
Data management class implemented in an abstract manner to handle different
types of datafeed (coming from database, webscraping, direct datafeed, csv, etc..)
this generates a Market event in the back test loop
"""
__metaclass__ = ABCMeta
@abstractmethod
def get_latest_bar(self, symbol):
"""
Returns the last bar updated.
"""
raise NotImplementedError("Should implement get_latest_bar()")
@abstractmethod
def get_latest_bars(self, symbol, N=1):
"""
Returns the last N bars updated.
"""
raise NotImplementedError("Should implement get_latest_bars()")
@abstractmethod
def get_latest_bar_datetime(self, symbol):
"""
Returns a Python datetime object for the last bar.
"""
raise NotImplementedError("Should implement get_latest_bar_datetime()")
@abstractmethod
def get_latest_bar_value(self, symbol, val_type):
"""
Returns one of the Open, High, Low, Close, Volume or OI
from the last bar.
"""
raise NotImplementedError("Should implement get_latest_bar_value()")
@abstractmethod
def get_latest_bars_values(self, symbol, val_type, N=1):
"""
Returns the last N bar values from the
latest_symbol list, or N-k if less available.
"""
raise NotImplementedError("Should implement get_latest_bars_values()")
@abstractmethod
def update_bars(self):
"""
Pushes the latest bars to the bars_queue for each symbol
in a tuple OHLCVI format: (datetime, open, high, low,
close, volume, adj closing price).
"""
raise NotImplementedError("Should implement update_bars()")
class YahooDataHandler(DataManagement):
"""
Get data directly from Yahoo Finance website, and provide an interface
to obtain the "latest" bar in a manner identical to a live
trading interface.
"""
def __init__(self, events, symbol_list, interval, start_date, end_date):
"""
Initialize Queries from yahoo finance api to
receive historical data transformed to dataframe
Parameters:
events - The Event Queue.
symbol_list - A list of symbol strings.
interval - 1d, 1wk, 1mo - daily, weekly monthly data
start_date - starting date for the historical data (format: datetime)
end_date - final date of the data (format: datetime)
"""
self.events = events
self.symbol_list = symbol_list
self.interval = interval
self.start_date = start_date
self.end_date = end_date
self.symbol_data = {}
self.latest_symbol_data = {}
self.continue_backtest = True
self._load_data_from_Yahoo_finance()
def _load_data_from_Yahoo_finance(self):
"""
Queries yfinance api to receive historical data in csv file format
"""
combined_index = None
for symbol in self.symbol_list:
# download data from yfinance for symbol. This could be improved as yfinance can download several
# symbols at the same time
self.symbol_data[symbol] = yf.download(tickers=[symbol], start=self.start_date,
end=self.end_date, interval=self.interval)
# rename columns for consistency
self.symbol_data[symbol].rename(columns={'Open': 'open',
'High': 'high',
'Low': 'low',
'Close': 'close',
'Adj Close': 'adj_close',
'Volume': 'volume'}, inplace=True)
# rename index as well from 'Date' to 'datetime'
self.symbol_data[symbol].index.name = 'datetime'
# create returns column (used for some strategies)
self.symbol_data[symbol]['returns'] = self.symbol_data[symbol]["adj_close"].pct_change() * 100.0
# Combine the index to pad forward values
if combined_index is None:
combined_index = self.symbol_data[symbol].index
else:
combined_index.union(self.symbol_data[symbol].index)
# Set the latest symbol_data to None
self.latest_symbol_data[symbol] = []
# Reindex the dataframes
for symbol in self.symbol_list:
self.symbol_data[symbol] = self.symbol_data[symbol].reindex(index=combined_index, method="pad").iterrows()
def _get_new_bar(self, symbol):
"""
Returns the latest bar from the data feed as a tuple of
(symbol, datetime, open, low, high, close, volume, adj_close, etc).
"""
for bar in self.symbol_data[symbol]:
yield bar
def get_latest_bar(self, symbol):
"""
Returns the last bar from the latest_symbol list.
"""
try:
bars_list = self.latest_symbol_data[symbol]
except KeyError:
print("That symbol is not available in the historical data set.")
raise
else:
return bars_list[-1]
def get_latest_bars(self, symbol, N=1):
"""
Returns the last N bars from the latest_symbol list,
or N-k if less available.
"""
try:
bars_list = self.latest_symbol_data[symbol]
except KeyError:
print("That symbol is not available in the historical data set.")
raise
else:
return bars_list[-N:]
def get_latest_bar_datetime(self, symbol):
"""
Returns a Python datetime object for the last bar.
"""
try:
bars_list = self.latest_symbol_data[symbol]
except KeyError:
print("That symbol is not available in the historical data set.")
raise
else:
return bars_list[-1][0]
def get_latest_bar_value(self, symbol, value_type):
"""
Returns one of the Open, High, Low, Close, Volume or OI
values from the pandas Bar series object.
"""
try:
bars_list = self.latest_symbol_data[symbol]
except KeyError:
print("That symbol is not available in the historical data set.")
raise
else:
return getattr(bars_list[-1][1], value_type)
def get_latest_bars_values(self, symbol, value_type, N=1):
"""
Returns the last N bar values from the
latest_symbol list, or N-k if less available.
"""
try:
bars_list = self.get_latest_bars(symbol, N) # bars_list = bars_list[-N:]
except KeyError:
print("That symbol is not available in the historical data set.")
raise
else:
return np.array([getattr(bar[1], value_type) for bar in bars_list])
def update_bars(self):
"""
Pushes the latest bar to the latest_symbol_data structure
for all symbols in the symbol list.
"""
for symbol in self.symbol_list:
try:
bar = next(self._get_new_bar(symbol))
except StopIteration:
self.continue_backtest = False
else:
if bar is not None:
self.latest_symbol_data[symbol].append(bar)
self.events.put(MarketEvent())
class HistoricCSVDataHandler(DataManagement):
"""
HistoricCSVDataHandler is designed to read CSV files for
each requested symbol from disk and provide an interface
to obtain the "latest" bar in a manner identical to a live
trading interface.
"""
def __init__(self, events, csv_dir, symbol_list):
"""
Initialises the historic data handler by requesting
the location of the CSV files and a list of symbols.
It will be assumed that all files are of the form
'symbol.csv', where symbol is a string in the list.
Parameters:
events - The Event Queue.
csv_dir - Absolute directory path to the CSV files.
symbol_list - A list of symbol strings.
"""
self.events = events
self.csv_dir = csv_dir
self.symbol_list = symbol_list
self.symbol_data = {}
self.latest_symbol_data = {}
self.continue_backtest = True
self._data_conversion_from_csv_files()
def _data_conversion_from_csv_files(self):
"""
Opens the CSV files from the data directory, converting
them into pandas DataFrames within a symbol dictionary.
"""
combined_index = None
for symbol in self.symbol_list:
# Load the CSV file with no header information, indexed on date
self.symbol_data[symbol] = pd.io.parsers.read_csv(
os.path.join(self.csv_dir, "%s.csv" % symbol),
header=0, index_col=0,
names=["datetime", "open", "high", "low", "close", "adj_close", "volume"]
)
# Combine the index to pad forward values
if combined_index is None:
combined_index = self.symbol_data[symbol].index
else:
combined_index.union(self.symbol_data[symbol].index)
# Set the latest symbol_data to None
self.latest_symbol_data[symbol] = []
# Reindex the dataframes
for symbol in self.symbol_list:
self.symbol_data[symbol] = self.symbol_data[symbol].reindex(index=combined_index, method="pad").iterrows()
def _get_new_bar(self, symbol):
"""
Returns the latest bar from the data feed as a tuple of
(symbol, datetime, open, low, high, close, volume, adj_close).
"""
for bar in self.symbol_data[symbol]:
yield bar
def get_latest_bar(self, symbol):
"""
Returns the last bar from the latest_symbol list.
"""
try:
bars_list = self.latest_symbol_data[symbol]
except KeyError:
print("That symbol is not available in the historical data set.")
raise
else:
return bars_list[-1]
def get_latest_bars(self, symbol, N=1):
"""
Returns the last N bars from the latest_symbol list,
or N-k if less available.
"""
try:
bars_list = self.latest_symbol_data[symbol]
except KeyError:
print("That symbol is not available in the historical data set.")
raise
else:
return bars_list[-N:]
def get_latest_bar_datetime(self, symbol):
"""
Returns a Python datetime object for the last bar.
"""
try:
bars_list = self.latest_symbol_data[symbol]
except KeyError:
print("That symbol is not available in the historical data set.")
raise
else:
return bars_list[-1][0]
def get_latest_bar_value(self, symbol, value_type):
"""
Returns one of the Open, High, Low, Close, Volume or OI
values from the pandas Bar series object.
"""
try:
bars_list = self.latest_symbol_data[symbol]
except KeyError:
print("That symbol is not available in the historical data set.")
raise
else:
return getattr(bars_list[-1][1], value_type)
def get_latest_bars_values(self, symbol, value_type, N=1):
"""
Returns the last N bar values from the
latest_symbol list, or N-k if less available.
"""
try:
bars_list = self.get_latest_bars(symbol, N) # bars_list = bars_list[-N:]
except KeyError:
print("That symbol is not available in the historical data set.")
raise
else:
return np.array([getattr(bar[1], value_type) for bar in bars_list])
def update_bars(self):
"""
Pushes the latest bar to the latest_symbol_data structure
for all symbols in the symbol list.
"""
for symbol in self.symbol_list:
try:
bar = next(self._get_new_bar(symbol))
except StopIteration:
self.continue_backtest = False
else:
if bar is not None:
self.latest_symbol_data[symbol].append(bar)
self.events.put(MarketEvent())
'''
class HistoricMySQLDataHandler(DataManagement):
"""
HistoricMySQLDataHandler is designed to read a MySQL database for each requested symbol from disk and
provide an interface to obtain the "latest" bar in a manner identical to a live trading interface.
"""
def __init__(self, events, db_host, db_user, db_pass, db_name, symbol_list):
"""
Initialises the historic data handler by requesting
the location of the database and a list of symbols.
It will be assumed that all price data is in a table called
'symbols', where the field 'symbol' is a string in the list.
Parameters:
events - The Event Queue.
db_host - host of the database
db_user - database user
db_pass - password to access database
db_name - database's name
symbol_list - A list of symbol stringss
"""
self.events = events
self.db_host = db_host
self.db_user = db_user
self.db_pass = db_pass
self.db_name = db_name
self.symbol_list = symbol_list
self.symbol_data = {}
self.latest_symbol_data = {}
self.continue_backtest = True
self._data_conversion_from_database()
def _get_data_from_database(self, symbol, columns):
try:
connection = MySQLdb.connect(host=self.db_host, user=self.db_user, passwd=self.db_pass, db=self.db_name)
except MySQLdb.Error as e:
print("Error:%d:%s" % (e.args[0], e.args[1]))
sql = SELECT {},{},{},{},{},{},{}
FROM {}.format(columns[0],
columns[1],
columns[2],
columns[3],
columns[4],
columns[5],
columns[6],
symbol)
return pd.read_sql_query(sql, con=connection, index_col="datetime")
def _data_conversion_from_database(self):
"""
Opens the database files, converting them into
pandas DataFrames within a symbol dictionary.
For this handler it will be assumed that the data is
assumed to be stored in a database with similar columns
as the pandas dataframes. Thus, the format will be respected.
"""
combined_index = None
columns = ["datetime","open","high","low","close","volume","adj_close"]
for symbol in self.symbol_list:
self.symbol_data[symbol] = self._get_data_from_database(symbol, columns)
# Combine the index to pad forward values
if combined_index is None:
combined_index = self.symbol_data[symbol].index
else:
combined_index.union(self.symbol_data[symbol].index)
# Set the latest symbol_data to None
self.latest_symbol_data[symbol] = []
# Reindex the dataframes
for symbol in self.symbol_list:
self.symbol_data[symbol] = self.symbol_data[symbol].reindex(index=combined_index, method="pad").iterrows()
def _get_new_bar(self, symbol):
"""
Returns the latest bar from the data feed as a tuple of
(symbol, datetime, open, low, high, close, volume, adj_close).
"""
for bar in self.symbol_data[symbol]:
yield bar
def get_latest_bar(self, symbol):
"""
Returns the last bar from the latest_symbol list.
"""
try:
bars_list = self.latest_symbol_data[symbol]
except KeyError:
print("That symbol is not available in the historical data set.")
raise
else:
return bars_list[-1]
def get_latest_bars(self, symbol, N=1):
"""
Returns the last N bars from the latest_symbol list,
or N-k if less available.
"""
try:
bars_list = self.latest_symbol_data[symbol]
except KeyError:
print("That symbol is not available in the historical data set.")
raise
else:
return bars_list[-N:]
def get_latest_bar_datetime(self, symbol):
"""
Returns a Python datetime object for the last bar.
"""
try:
bars_list = self.latest_symbol_data[symbol]
except KeyError:
print("That symbol is not available in the historical data set.")
raise
else:
return bars_list[-1][0]
def get_latest_bar_value(self, symbol, value_type):
"""
Returns one of the Open, High, Low, Close, Volume or OI
values from the pandas Bar series object.
"""
try:
bars_list = self.latest_symbol_data[symbol]
except KeyError:
print("That symbol is not available in the historical data set.")
raise
else:
return getattr(bars_list[-1][1], value_type)
def get_latest_bars_values(self, symbol, value_type, N=1):
"""
Returns the last N bar values from the
latest_symbol list, or N-k if less available.
"""
try:
bars_list = self.get_latest_bars(symbol, N) # bars_list = bars_list[-N:]
except KeyError:
print("That symbol is not available in the historical data set.")
raise
else:
return np.array([getattr(bar[1], value_type) for bar in bars_list])
def update_bars(self):
"""
Pushes the latest bar to the latest_symbol_data structure
for all symbols in the symbol list.
"""
for symbol in self.symbol_list:
try:
bar = next(self._get_new_bar(symbol))
except StopIteration:
self.continue_backtest = False
else:
if bar is not None:
self.latest_symbol_data[symbol].append(bar)
self.events.put(MarketEvent())
'''