/
ioengine.py
1673 lines (1282 loc) · 56.4 KB
/
ioengine.py
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
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
__author__ = "saeedamen" # Saeed Amen
#
# Copyright 2016 Cuemacro
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not
# use this file except in compliance with the License. You may obtain a copy of
# the License at http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on a "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#
# See the License for the specific language governing permissions and
# limitations under the License.
#
from typing import List
import io
import datetime
import json
from dateutil.parser import parse
import codecs
import glob
import shutil
import copy
import os.path
import math
import numpy as np
import pandas as pd
try:
from arctic import Arctic
import pymongo
except:
pass
# Needs this for AWS S3 bucket support
try:
from s3fs import S3FileSystem
except:
pass
# pyarrow necessary for caching
try:
import pyarrow as pa
except:
pass
# for reading and writing to S3
try:
import pyarrow.fs
import pyarrow.parquet as pq
from s3fs import S3FileSystem
except:
pass
try:
import redis
except:
pass
from openpyxl import load_workbook
from findatapy.util.dataconstants import DataConstants
from findatapy.util.loggermanager import LoggerManager
constants = DataConstants()
class IOEngine(object):
"""Write and reads time series data to disk in various formats, CSV, HDF5 (fixed and table formats) and MongoDB/Arctic.
Can be used to save down output of finmarketpy backtests and also to cache market data locally.
Also supports BColz (but not currently stable). Planning to add other interfaces such as SQL etc.
"""
def __init__(self):
pass
### functions to handle Excel on disk
def write_time_series_to_excel(self,
fname: str,
sheet: str,
data_frame: pd.DataFrame,
create_new: bool = False):
"""Writes Pandas data frame to disk in Excel format
Parameters
----------
fname : str
Excel filename to be written to
sheet : str
sheet in excel
data_frame : DataFrame
data frame to be written
create_new : boolean
to create a new Excel file
"""
if (create_new):
writer = pd.ExcelWriter(fname, engine='xlsxwriter')
else:
if self.path_exists(fname):
book = load_workbook(fname)
writer = pd.ExcelWriter(fname, engine='xlsxwriter')
writer.book = book
writer.sheets = dict((ws.title, ws) for ws in book.worksheets)
else:
writer = pd.ExcelWriter(fname, engine='xlsxwriter')
data_frame.to_excel(writer, sheet_name=sheet, engine='xlsxwriter')
writer.save()
writer.close()
def write_time_series_to_excel_writer(self,
writer,
sheet: str,
data_frame: pd.DataFrame):
"""Writes Pandas data frame to disk in Excel format for a writer
Parameters
----------
writer : ExcelWriter
File handle to use for writing Excel file to disk
sheet : str
sheet in excel
data_frame : DataFrame
data frame to be written
"""
data_frame.to_excel(writer, sheet, engine='xlsxwriter')
def read_excel_data_frame(self, f_name: str,
excel_sheet: str,
freq: str,
cutoff: str = None,
dateparse: str= None,
postfix: str = '.close',
intraday_tz: str = 'UTC'):
"""Reads Excel from disk into DataFrame
Parameters
----------
f_name : str
Excel file path to read
freq : str
Frequency of data to read (intraday/daily etc)
cutoff : DateTime (optional)
end date to read up to
dateparse : str (optional)
date parser to use
postfix : str (optional)
postfix to add to each columns
intraday_tz : str
timezone of file if uses intraday data
Returns
-------
DataFrame
"""
return self.read_csv_data_frame(f_name, freq, cutoff=cutoff,
dateparse=dateparse,
postfix=postfix,
intraday_tz=intraday_tz,
excel_sheet=excel_sheet)
def remove_time_series_cache_on_disk(self,
fname: str,
engine: str = 'hdf5_fixed',
db_server: str = constants.db_server,
db_port: int = constants.db_port,
timeout: int = 10,
username: int = None,
password: int = None):
logger = LoggerManager().getLogger(__name__)
if 'hdf5' in engine:
engine = 'hdf5'
if engine == 'redis':
fname = os.path.basename(fname).replace('.', '_')
try:
r = redis.StrictRedis(host=db_server, port=db_port, db=0,
socket_timeout=timeout,
socket_connect_timeout=timeout)
if fname == 'flush_all_keys':
r.flushall()
else:
# Allow deletion of keys by pattern matching
matching_keys = r.keys('*' + fname)
if matching_keys:
# Use pipeline to speed up command
pipe = r.pipeline()
for key in matching_keys:
pipe.delete(key)
pipe.execute()
# r.delete(fname)
except Exception as e:
logger.warning(
"Cannot delete non-existent key " + fname + " in Redis: " + str(
e))
elif (engine == 'arctic'):
from arctic import Arctic
import pymongo
socketTimeoutMS = 30 * 1000
fname = os.path.basename(fname).replace('.', '_')
logger.info('Load MongoDB library: ' + fname)
if username is not None and password is not None:
c = pymongo.MongoClient(
host="mongodb://" + username + ":" + password + "@" + str(
db_server) + ":" + str(db_port),
connect=False) # , username=username, password=password)
else:
c = pymongo.MongoClient(
host="mongodb://" + str(db_server) + ":" + str(db_port),
connect=False)
store = Arctic(c, socketTimeoutMS=socketTimeoutMS,
serverSelectionTimeoutMS=socketTimeoutMS,
connectTimeoutMS=socketTimeoutMS)
store.delete_library(fname)
c.close()
logger.info("Deleted MongoDB library: " + fname)
elif engine == 'hdf5':
h5_filename = self.get_h5_filename(fname)
# delete the old copy
try:
os.remove(h5_filename)
except:
pass
### functions to handle HDF5 on disk, arctic etc.
def write_time_series_cache_to_disk(
self,
fname: str,
data_frame: pd.DataFrame,
engine: str = 'hdf5_fixed',
append_data: bool = False,
db_server: str = constants.db_server,
db_port: int = constants.db_port,
username: str = constants.db_username,
password: str = constants.db_password,
filter_out_matching: str = None,
timeout: int = 10,
use_cache_compression: bool = constants.use_cache_compression,
parquet_compression: str = constants.parquet_compression,
use_pyarrow_directly: bool =False,
md_request=None,
ticker: str =None,
cloud_credentials: dict = None):
"""Writes Pandas data frame to disk as Parquet, HDF5 format or bcolz
format, in Arctic or to Redis
Note, that Redis uses pickle (you must make sure that your Redis
instance is not accessible from unverified users, given you should not
unpickle from unknown sources)
Parmeters
---------
fname : str
path of file
data_frame : DataFrame
data frame to be written to disk
engine : str
'hdf5_fixed' - use HDF5 fixed format, very quick, but cannot append to this
'hdf5_table' - use HDF5 table format, slower but can append to
'parquet' - use Parquet
'arctic' - use Arctic/MongoDB database
'redis' - use Redis
append_data : bool
False - write a fresh copy of data on disk each time
True - append data to disk
db_server : str
Database server for arctic (default: '127.0.0.1')
timeout : int
Number of seconds to do timeout
"""
logger = LoggerManager().getLogger(__name__)
if cloud_credentials is None:
cloud_credentials = constants.cloud_credentials
if md_request is not None:
fname = self.path_join(fname, md_request.create_category_key(
ticker=ticker))
# default HDF5 format
hdf5_format = 'fixed'
if 'hdf5' in engine:
hdf5_format = engine.split('_')[1]
engine = 'hdf5'
if engine == 'redis':
fname = os.path.basename(fname).replace('.', '_')
# Will fail if Redis is not installed
try:
r = redis.StrictRedis(host=db_server, port=db_port, db=0,
socket_timeout=timeout,
socket_connect_timeout=timeout)
ping = r.ping()
# If Redis is alive, try pushing to it
if ping:
if data_frame is not None:
if isinstance(data_frame, pd.DataFrame):
mem = data_frame.memory_usage(deep='deep').sum()
mem_float = round(float(mem) / (1024.0 * 1024.0),
3)
if mem_float < 500:
if use_cache_compression:
ser = io.BytesIO()
data_frame.to_pickle(ser,
compression="gzip")
ser.seek(0)
r.set('comp_' + fname, ser.read())
else:
ser = io.BytesIO()
data_frame.to_pickle(ser)
ser.seek(0)
r.set(fname, ser.read())
logger.info("Pushed " + fname + " to Redis")
else:
logger.warn(
"Did not push " + fname + " to Redis, given size")
else:
logger.info(
"Object " + fname + " is empty, not pushed to Redis.")
else:
logger.warning(
"Didn't push " + fname + " to Redis given not running")
except Exception as e:
fname_msg = fname
if len(fname_msg) > 150:
fname_msg = fname_msg[:149] + "..."
error_msg = str(e)
if len(error_msg) > 150:
error_msg = error_msg[:149] + "..."
logger.warning(
"Couldn't push " + fname_msg + " to Redis: " + error_msg)
elif engine == 'arctic':
socketTimeoutMS = 30 * 1000
fname = os.path.basename(fname).replace('.', '_')
logger.info('Load Arctic/MongoDB library: ' + fname)
if username is not None and password is not None:
c = pymongo.MongoClient(
host="mongodb://" + username + ":" + password + "@" + str(
db_server) + ":" + str(db_port),
connect=False) # , username=username, password=password)
else:
c = pymongo.MongoClient(
host="mongodb://" + str(db_server) + ":" + str(db_port),
connect=False)
store = Arctic(c, socketTimeoutMS=socketTimeoutMS,
serverSelectionTimeoutMS=socketTimeoutMS,
connectTimeoutMS=socketTimeoutMS)
database = None
try:
database = store[fname]
except:
pass
if database is None:
store.initialize_library(fname, audit=False)
logger.info("Created MongoDB library: " + fname)
else:
logger.info("Got MongoDB library: " + fname)
# Access the library
library = store[fname]
if 'intraday' in fname:
data_frame = data_frame.astype('float32')
if filter_out_matching is not None:
cols = data_frame.columns
new_cols = []
for col in cols:
if filter_out_matching not in col:
new_cols.append(col)
data_frame = data_frame[new_cols]
# Problems with Arctic when writing timezone to disk sometimes,
# so strip
data_frame = data_frame.copy().tz_localize(None)
try:
# Can duplicate values if we have existing dates
if append_data:
library.append(fname, data_frame)
else:
library.write(fname, data_frame)
c.close()
logger.info("Written MongoDB library: " + fname)
except Exception as e:
logger.warning(
"Couldn't write MongoDB library: " + fname + " " + str(e))
elif engine == 'hdf5':
h5_filename = self.get_h5_filename(fname)
# Append data only works for HDF5 stored as tables (but this is
# much slower than fixed format) removes duplicated entries at
# the end
if append_data:
store = pd.HDFStore(h5_filename, format=hdf5_format,
complib="zlib", complevel=9)
if ('intraday' in fname):
data_frame = data_frame.astype('float32')
# get last row which matches and remove everything after that
# (because append function doesn't check for duplicated rows)
nrows = len(store['data'].index)
last_point = data_frame.index[-1]
i = nrows - 1
while (i > 0):
read_index = \
store.select('data', start=i, stop=nrows).index[0]
if (read_index <= last_point): break
i = i - 1
# Remove rows at the end, which are duplicates of the
# incoming time series
store.remove(key='data', start=i, stop=nrows)
store.put(key='data', value=data_frame, format=hdf5_format,
append=True)
store.close()
else:
h5_filename_temp = self.get_h5_filename(fname + ".temp")
# delete the old copy
try:
os.remove(h5_filename_temp)
except:
pass
store = pd.HDFStore(h5_filename_temp, complib="zlib",
complevel=9)
if ('intraday' in fname):
data_frame = data_frame.astype('float32')
store.put(key='data', value=data_frame, format=hdf5_format)
store.close()
# delete the old copy
try:
os.remove(h5_filename)
except:
pass
# once written to disk rename
os.rename(h5_filename_temp, h5_filename)
logger.info("Written HDF5: " + fname)
elif engine == 'parquet':
if '.parquet' not in fname:
if fname[-5:] != '.gzip':
fname = fname + '.parquet'
self.to_parquet(data_frame, fname,
cloud_credentials=cloud_credentials,
parquet_compression=parquet_compression,
use_pyarrow_directly=use_pyarrow_directly)
# data_frame.to_parquet(fname, compression=parquet_compression)
logger.info("Written Parquet: " + fname)
elif engine == 'csv':
if '.csv' not in fname:
fname = fname + '.csv'
data_frame.to_csv(fname)
logger.info("Written CSV: " + fname)
def get_h5_filename(self, fname: str):
"""Strips h5 off filename returning first portion of filename
Parameters
----------
fname : str
h5 filename to strip
Returns
-------
str
"""
if fname[-3:] == '.h5':
return fname
return fname + ".h5"
def get_bcolz_filename(self, fname: str):
"""Strips bcolz off filename returning first portion of filename
Parameters
----------
fname : str
bcolz filename to strip
Returns
-------
str
"""
if fname[-6:] == '.bcolz':
return fname
return fname + ".bcolz"
def write_r_compatible_hdf_dataframe(self,
data_frame: pd.DataFrame,
fname: str,
fields: List[str]=None):
"""Write a DataFrame to disk in as an R compatible HDF5 file.
Parameters
----------
data_frame : DataFrame
data frame to be written
fname : str
file path to be written
fields : list(str)
columns to be written
"""
logger = LoggerManager().getLogger(__name__)
fname_r = self.get_h5_filename(fname)
logger.info("About to dump R binary HDF5 - " + fname_r)
data_frame32 = data_frame.astype('float32')
if fields is None:
fields = data_frame32.columns.values
# decompose date/time into individual fields (easier to pick up in R)
data_frame32['Year'] = data_frame.index.year
data_frame32['Month'] = data_frame.index.month
data_frame32['Day'] = data_frame.index.day
data_frame32['Hour'] = data_frame.index.hour
data_frame32['Minute'] = data_frame.index.minute
data_frame32['Second'] = data_frame.index.second
data_frame32['Millisecond'] = data_frame.index.microsecond / 1000
data_frame32 = data_frame32[
['Year', 'Month', 'Day', 'Hour', 'Minute', 'Second',
'Millisecond'] + fields]
cols = data_frame32.columns
store_export = pd.HDFStore(fname_r)
store_export.put('df_for_r', data_frame32, data_columns=cols)
store_export.close()
def read_time_series_cache_from_disk(self, fname,
engine: str ='hdf5',
start_date: str = None,
finish_date: str = None,
db_server: str = constants.db_server,
db_port: int = constants.db_port,
username: str = constants.db_username,
password: str = constants.db_password):
"""Reads time series cache from disk in either HDF5 or bcolz
Parameters
----------
fname : str (or list)
file to be read from
engine : str (optional)
'hd5' - reads HDF5 files (default)
'arctic' - reads from Arctic/MongoDB database
'bcolz' - reads from bcolz file (not fully implemented)
'parquet' - reads from Parquet
start_date : str/datetime (optional)
Start date
finish_date : str/datetime (optional)
Finish data
db_server : str
IP address of MongdDB (default '127.0.0.1')
Returns
-------
DataFrame
"""
logger = LoggerManager.getLogger(__name__)
data_frame_list = []
if not (isinstance(fname, list)):
if '*' in fname:
fname = glob.glob(fname)
else:
fname = [fname]
for fname_single in fname:
logger.debug("Reading " + fname_single + "..")
if engine == 'parquet' and '.gzip' not in fname_single \
and '.parquet' not in fname_single:
fname_single = fname_single + '.parquet'
if engine == 'redis':
fname_single = os.path.basename(fname_single).replace('.', '_')
msg = None
try:
r = redis.StrictRedis(host=db_server, port=db_port, db=0)
# is there a compressed key stored?)
k = r.keys('comp_' + fname_single)
# If so, then it means that we have stored it as a
# compressed object if have more than 1 element, take the
# last (which will be the latest to be added)
if (len(k) >= 1):
k = k[-1].decode('utf-8')
msg = r.get(k)
msg = io.BytesIO(msg)
msg = pd.read_pickle(msg, compression="gzip")
else:
msg = r.get(fname_single)
msg = pd.read_pickle(msg.read())
except Exception as e:
logger.info(
"Cache not existent for " +
fname_single + " in Redis: " + str(
e))
if msg is None:
data_frame = None
else:
logger.info("Load Redis cache: " + fname_single)
data_frame = msg # pd.read_msgpack(msg)
elif engine == 'arctic':
socketTimeoutMS = 2 * 1000
import pymongo
from arctic import Arctic
fname_single = os.path.basename(fname_single).replace('.', '_')
logger.info("Load Arctic/MongoDB library: " + fname_single)
if username is not None and password is not None:
c = pymongo.MongoClient(
host="mongodb://" + username + ":" + password + "@" + str(
db_server) + ":" + str(db_port),
connect=False) # , username=username, password=password)
else:
c = pymongo.MongoClient(
host="mongodb://" + str(db_server) + ":" + str(
db_port), connect=False)
store = Arctic(c, socketTimeoutMS=socketTimeoutMS,
serverSelectionTimeoutMS=socketTimeoutMS)
# Access the library
try:
library = store[fname_single]
if start_date is None and finish_date is None:
item = library.read(fname_single)
else:
from arctic.date import DateRange
item = library.read(fname_single, date_range=DateRange(
start_date.replace(tzinfo=None),
finish_date.replace(tzinfo=None)))
c.close()
logger.info('Read ' + fname_single)
data_frame = item.data
except Exception as e:
logger.warning(
'Library may not exist or another error: '
+ fname_single + ' & message is ' + str(e))
data_frame = None
elif self.path_exists(self.get_h5_filename(fname_single)):
store = pd.HDFStore(self.get_h5_filename(fname_single))
data_frame = store.select("data")
if ('intraday' in fname_single):
data_frame = data_frame.astype('float32')
store.close()
elif self.path_exists(fname_single) and '.csv' in fname_single:
data_frame = pd.read_csv(fname_single, index_col=0)
data_frame.index = pd.to_datetime(data_frame.index)
elif self.path_exists(fname_single):
data_frame = self.read_parquet(fname_single)
# data_frame = pd.read_parquet(fname_single)
data_frame_list.append(data_frame)
if len(data_frame_list) == 0:
return None
if len(data_frame_list) == 1:
return data_frame_list[0]
return data_frame_list
### functions for CSV reading and writing
def write_time_series_to_csv(self, csv_path, data_frame):
data_frame.to_csv(csv_path)
def read_csv_data_frame(self, f_name, freq, cutoff=None, dateparse=None,
postfix='.close', intraday_tz='UTC',
excel_sheet=None):
"""Reads CSV/Excel from disk into DataFrame
Parameters
----------
f_name : str
CSV/Excel file path to read
freq : str
Frequency of data to read (intraday/daily etc)
cutoff : DateTime (optional)
end date to read up to
dateparse : str (optional)
date parser to use
postfix : str (optional)
postfix to add to each columns
intraday_tz : str (optional)
timezone of file if uses intraday data
excel_sheet : str (optional)
Excel sheet to be read
Returns
-------
DataFrame
"""
if freq == 'intraday':
if dateparse is None:
dateparse = lambda x: datetime.datetime(
*map(int, [x[6:10], x[3:5], x[0:2],
x[11:13], x[14:16], x[17:19]]))
elif dateparse == 'dukascopy':
dateparse = lambda x: datetime.datetime(
*map(int, [x[0:4], x[5:7], x[8:10],
x[11:13], x[14:16], x[17:19]]))
elif dateparse == 'c':
# use C library for parsing dates, several hundred times quicker
# requires compilation of library to install
import ciso8601
dateparse = lambda x: ciso8601.parse_datetime(x)
if excel_sheet is None:
data_frame = pd.read_csv(f_name, index_col=0, parse_dates=True,
date_parser=dateparse)
else:
data_frame = pd.read_excel(f_name, excel_sheet, index_col=0,
na_values=['NA'])
data_frame = data_frame.astype('float32')
data_frame.index.names = ['Date']
old_cols = data_frame.columns
new_cols = []
# add '.close' to each column name
for col in old_cols:
new_cols.append(col + postfix)
data_frame.columns = new_cols
else:
# daily data
if 'events' in f_name:
data_frame = pd.read_csv(f_name)
# very slow conversion
data_frame = data_frame.convert_objects(convert_dates='coerce')
else:
if excel_sheet is None:
try:
data_frame = pd.read_csv(f_name, index_col=0,
parse_dates=["DATE"],
date_parser=dateparse)
except:
data_frame = pd.read_csv(f_name, index_col=0,
parse_dates=["Date"],
date_parser=dateparse)
else:
data_frame = pd.read_excel(f_name, excel_sheet,
index_col=0, na_values=['NA'])
# convert Date to Python datetime
# datetime data_frame['Date1'] = data_frame.index
# slower method: lambda x: pd.datetime.strptime(x, '%d/%m/%Y %H:%M:%S')
# data_frame['Date1'].apply(lambda x: datetime.datetime(int(x[6:10]), int(x[3:5]), int(x[0:2]),
# int(x[12:13]), int(x[15:16]), int(x[18:19])))
# data_frame.index = data_frame['Date1']
# data_frame.drop('Date1')
# slower method: data_frame.index = pd.to_datetime(data_frame.index)
if freq == 'intraday':
# assume time series are already in UTC and assign this (can specify other time zones)
data_frame = data_frame.tz_localize(intraday_tz)
# end cutoff date
if cutoff is not None:
if (isinstance(cutoff, str)):
cutoff = parse(cutoff)
data_frame = data_frame.loc[data_frame.index < cutoff]
return data_frame
def find_replace_chars(self, array, to_find, replace_with):
for i in range(0, len(to_find)):
array = [x.replace(to_find[i], replace_with[i]) for x in array]
return array
def convert_csv_data_frame(self, f_name, category, freq, cutoff=None,
dateparse=None):
"""Converts CSV file to HDF5 file
Parameters
----------
f_name : str
File name to be read
category : str
data category of file (used in HDF5 filename)
freq : str
intraday/daily frequency (used in HDF5 filename)
cutoff : DateTime (optional)
filter dates up to here
dateparse : str
date parser to use
"""
logger = LoggerManager().getLogger(__name__)
logger.info("About to read... " + f_name)
data_frame = self.read_csv_data_frame(f_name, freq, cutoff=cutoff,
dateparse=dateparse)
category_f_name = self.create_cache_file_name(category)
self.write_time_series_cache_to_disk(category_f_name, data_frame)
def clean_csv_file(self, f_name):
"""Cleans up CSV file (removing empty characters) before writing back
to disk
Parameters
----------
f_name : str
CSV file to be cleaned
"""
logger = LoggerManager().getLogger(__name__)
with codecs.open(f_name, 'rb', 'utf-8') as file:
data = file.read()
# clean file first if dirty
if data.count('\x00'):
logger.info('Cleaning CSV...')
with codecs.open(f_name + '.tmp', 'w', 'utf-8') as of:
of.write(data.replace('\x00', ''))
shutil.move(f_name + '.tmp', f_name)
def create_cache_file_name(self, filename):
return constants.folder_time_series_data + "/" + filename
# TODO refactor IOEngine so that each database is implemented in a
# subclass of DBEngine
def get_engine(self, engine='hdf5_fixed'):
pass
def sanitize_path(self, path):
"""Will remove unnecessary // from a file path (eg. in the middle)
Parameters
----------
path : str
path to be sanitized
Returns
-------
str
"""
if "s3://" in path:
path = path.replace("s3://", "")
path = path.replace("//", "/")
return "s3://" + path
return path
def read_parquet(self, path: str,
cloud_credentials: dict = None):
"""Reads a Pandas DataFrame from a local or s3 path
Parameters
----------
path : str
Path of Parquet file (can be S3)
cloud_credentials : dict (optional)
Credentials for logging into the cloud
Returns
-------
DataFrame
"""
if cloud_credentials is None:
cloud_credentials = constants.cloud_credentials
if "s3://" in path:
storage_options = self._convert_cred(cloud_credentials,
convert_to_s3fs=True)
return pd.read_parquet(self.sanitize_path(path),
storage_options=storage_options,