Repository navigation
Expand file tree
/
Copy pathxtdata.py
More file actions
2605 lines (2151 loc) · 79.9 KB
/
Copy pathxtdata.py
File metadata and controls
2605 lines (2151 loc) · 79.9 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
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
#coding:utf-8
import os, sys
import time
import traceback
import json
import datetime as dt
from . import xtbson as bson
from . import xtutil
__all__ = [
'subscribe_quote'
, 'subscribe_whole_quote'
, 'unsubscribe_quote'
, 'run'
, 'get_market_data'
, 'get_local_data'
, 'get_full_tick'
, 'get_divid_factors'
, 'get_l2_quote'
, 'get_l2_order'
, 'get_l2_transaction'
, 'download_history_data'
, 'get_financial_data'
, 'download_financial_data'
, 'get_instrument_detail'
, 'get_instrument_type'
, 'get_trading_dates'
, 'get_sector_list'
, 'get_stock_list_in_sector'
, 'download_sector_data'
, 'add_sector'
, 'remove_sector'
, 'get_index_weight'
, 'download_index_weight'
, 'get_holidays'
, 'get_trading_calendar'
, 'get_trading_time'
, 'get_etf_info'
, 'download_etf_info'
, 'get_main_contract'
, 'download_history_contracts'
, 'download_cb_data'
, 'get_cb_info'
, 'create_sector_folder'
, 'create_sector'
, 'remove_stock_from_sector'
, 'reset_sector'
, 'get_period_list'
, 'download_his_st_data'
]
def try_except(func):
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except Exception:
exc_type, exc_instance, exc_traceback = sys.exc_info()
formatted_traceback = ''.join(traceback.format_tb(exc_traceback))
message = '\n{0} raise {1}:{2}'.format(
formatted_traceback,
exc_type.__name__,
exc_instance
)
# raise exc_type(message)
# print(message)
return None
return wrapper
### config
debug_mode = 0
default_data_dir = '../userdata_mini/datadir'
data_dir = default_data_dir
enable_hello = True
### connection
__client = None
__client_last_spec = ('', None)
__hk_broke_info = {}
__download_version = None
def connect(ip = '', port = None, remember_if_success = True):
global __client
global data_dir
global __download_version
if __client:
if __client.is_connected():
return __client
__client.shutdown()
__client = None
data_dir = default_data_dir
from . import xtconn
if not ip:
ip = 'localhost'
if port:
server_list = [f'{ip}:{port}']
__client = xtconn.connect_any(server_list)
else:
server_list = xtconn.scan_available_server()
default_addr = 'localhost:58610'
if not default_addr in server_list:
server_list.append(default_addr)
__client = xtconn.connect_any(server_list)
if not __client or not __client.is_connected():
raise Exception("无法连接xtquant服务,请检查QMT-投研版或QMT-极简版是否开启")
if remember_if_success:
global __client_last_spec
__client_last_spec = (ip, port)
data_dir = __client.get_data_dir()
if data_dir == "":
data_dir = os.path.join(__client.get_app_dir(), default_data_dir)
data_dir = os.path.abspath(data_dir)
try:
__download_version = __bsoncall_common(
__client.commonControl, 'getapiversion', {}
).get('downloadversion', None)
except:
pass
hello()
return __client
def reconnect(ip = '', port = None, remember_if_success = True):
global __client
global data_dir
if __client:
__client.shutdown()
__client = None
data_dir = default_data_dir
return connect(ip, port, remember_if_success)
def get_client():
global __client
if not __client or not __client.is_connected():
global __client_last_spec
ip, port = __client_last_spec
__client = connect(ip, port, False)
return __client
def hello():
global __client
global enable_hello
if not enable_hello:
return
server_info = None
peer_addr = None
data_dir = None
try:
server_info = bson.BSON.decode(__client.get_server_tag())
peer_addr = __client.get_peer_addr()
data_dir = __client.get_data_dir()
except Exception as e:
pass
print(
f'''***** xtdata连接成功 *****
服务信息: {server_info}
服务地址: {peer_addr}
数据路径: {data_dir}
设置xtdata.enable_hello = False可隐藏此消息
'''
)
return
__meta_field_list = {}
def get_field_list(metaid):
global __meta_field_list
if not __meta_field_list:
x = open(os.path.join(os.path.dirname(__file__), 'config', 'metaInfo.json'), 'r', encoding="utf-8").read()
metainfo = eval(x)
for meta in metainfo:
filed_dict = {}
metadetail = metainfo.get(str(meta), {})
filed = metadetail.get('fields', {})
for key in filed:
filed_dict[key] = filed[key].get('desc', key)
filed_dict['G'] = 'time'
filed_dict['S'] = 'stock'
__meta_field_list[meta] = filed_dict
return __meta_field_list.get(str(metaid), {})
### utils
def create_array(shape, dtype_tuple, capsule, size):
import numpy as np
import ctypes
ctypes.pythonapi.PyCapsule_GetPointer.restype = ctypes.POINTER(ctypes.c_char)
ctypes.pythonapi.PyCapsule_GetPointer.argtypes = [ctypes.py_object, ctypes.c_char_p]
buff = ctypes.pythonapi.PyCapsule_GetPointer(capsule, None)
base_type = size * buff._type_
for dim in shape[::-1]:
base_type = dim * base_type
p_arr_type = ctypes.POINTER(base_type)
obj = ctypes.cast(buff, p_arr_type).contents
obj._base = capsule
return np.ndarray(shape = shape, dtype = np.dtype(dtype_tuple), buffer = obj)
from .xtdatacenter import register_create_nparray
register_create_nparray(create_array)
def __bsoncall_common(interface, func, param):
return bson.BSON.decode(interface(func, bson.BSON.encode(param)))
### function
def get_stock_list_in_sector(sector_name):
'''
获取板块成份股,支持客户端左侧板块列表中任意的板块,包括自定义板块
:param sector_name: (str)板块名称
:return: list
'''
client = get_client()
for illegalstr in ['\\', '/', ':', '*', '?', '"', '<', '>', '|']:
sector_name = sector_name.replace(illegalstr, '')
return client.get_stock_list_in_sector(sector_name, 0)
def get_index_weight(index_code):
'''
获取某只股票在某指数中的绝对权重
:param index_code: (str)指数名称
:return: dict
'''
client = get_client()
return client.get_weight_in_index(index_code)
def get_financial_data(stock_list, table_list=[], start_time='', end_time='', report_type='report_time'):
'''
获取财务数据
:param stock_list: (list)合约代码列表
:param table_list: (list)报表名称列表
:param start_time: (str)起始时间
:param end_time: (str)结束时间
:param report_type: (str) 时段筛选方式 'announce_time' / 'report_time'
:return:
field: list[str]
date: list[int]
stock: list[str]
value: list[list[float]]
'''
client = get_client()
all_table = {
'Balance' : 'ASHAREBALANCESHEET'
, 'Income' : 'ASHAREINCOME'
, 'CashFlow
BD0
39; : 'ASHARECASHFLOW'
, 'Capital' : 'CAPITALSTRUCTURE'
, 'HolderNum' : 'SHAREHOLDER'
, 'Top10Holder' : 'TOP10HOLDER'
, 'Top10FlowHolder' : 'TOP10FLOWHOLDER'
, 'PershareIndex' : 'PERSHAREINDEX'
}
if not table_list:
table_list = list(all_table.keys())
all_table_upper = {table.upper() : all_table[table] for table in all_table}
req_list = []
names = {}
for table in table_list:
req_table = all_table_upper.get(table.upper(), table)
req_list.append(req_table)
names[req_table] = table
data = {}
sl_len = 20
stock_list2 = [stock_list[i : i + sl_len] for i in range(0, len(stock_list), sl_len)]
for sl in stock_list2:
data2 = client.get_financial_data(sl, req_list, start_time, end_time, report_type)
for s in data2:
data[s] = data2[s]
import time
import math
def conv_date(data, key, key2):
if key in data:
tmp_data = data[key]
if math.isnan(tmp_data):
if key2 not in data or math.isnan(data[key2]):
data[key] = ''
else:
tmp_data = data[key2]
data[key] = time.strftime('%Y%m%d', time.localtime(tmp_data / 1000))
return
result = {}
import pandas as pd
for stock in data:
stock_data = data[stock]
result[stock] = {}
for table in stock_data:
table_data = stock_data[table]
for row_data in table_data:
conv_date(row_data, 'm_anntime', 'm_timetag')
conv_date(row_data, 'm_timetag', '')
conv_date(row_data, 'declareDate', '')
conv_date(row_data, 'endDate', '')
result[stock][names[table]] = pd.DataFrame(table_data)
return result
def get_market_data_ori(
field_list = [], stock_list = [], period = '1d'
, start_time = '', end_time = '', count = -1
, dividend_type = 'none', fill_data = True, enable_read_from_server = True
, data_dir = ''
):
client = get_client()
enable_read_from_local = period in {'1m', '5m', '15m', '30m', '60m', '1h', '1d', 'tick', '1w', '1mon', '1q', '1hy', '1y'}
global debug_mode
return client.get_market_data3(field_list, stock_list, period, start_time, end_time, count, dividend_type, fill_data, 'v2', enable_read_from_local, enable_read_from_server, debug_mode, data_dir)
def get_market_data(
field_list = [], stock_list = [], period = '1d'
, start_time = '', end_time = '', count = -1
, dividend_type = 'none', fill_data = True
):
'''
获取历史行情数据
:param field_list: 行情数据字段列表,[]为全部字段
K线可选字段:
"time" #时间戳
"open" #开盘价
"high" #最高价
"low" #最低价
"close" #收盘价
"volume" #成交量
"amount" #成交额
"settle" #今结算
"openInterest" #持仓量
分笔可选字段:
"time" #时间戳
"lastPrice" #最新价
"open" #开盘价
"high" #最高价
"low" #最低价
"lastClose" #前收盘价
"amount" #成交总额
"volume" #成交总量
"pvolume" #原始成交总量
"stockStatus" #证券状态
"openInt" #持仓量
"lastSettlementPrice" #前结算
"askPrice1", "askPrice2", "askPrice3", "askPrice4", "askPrice5" #卖一价~卖五价
"bidPrice1", "bidPrice2", "bidPrice3", "bidPrice4", "bidPrice5" #买一价~买五价
"askVol1", "askVol2", "askVol3", "askVol4", "askVol5" #卖一量~卖五量
"bidVol1", "bidVol2", "bidVol3", "bidVol4", "bidVol5" #买一量~买五量
:param stock_list: 股票代码 "000001.SZ"
:param period: 周期 分笔"tick" 分钟线"1m"/"5m"/"15m" 日线"1d"
Level2行情快照"l2quote" Level2行情快照补充"l2quoteaux" Level2逐笔委托"l2order" Level2逐笔成交"l2transaction" Level2大单统计"l2transactioncount" Level2委买委卖队列"l2orderqueue"
Level1逐笔成交统计一分钟“transactioncount1m” Level1逐笔成交统计日线“transactioncount1d”
期货仓单“warehousereceipt” 期货席位“futureholderrank” 互动问答“interactiveqa”
:param start_time: 起始时间 "20200101" "20200101093000"
:param end_time: 结束时间 "20201231" "20201231150000"
:param count: 数量 -1全部/n: 从结束时间向前数n个
:param dividend_type: 除权类型"none" "front" "back" "front_ratio" "back_ratio"
:param fill_data: 对齐时间戳时是否填充数据,仅对K线有效,分笔周期不对齐时间戳
为True时,以缺失数据的前一条数据填充
open、high、low、close 为前一条数据的close
amount、volume为0
settle、openInterest 和前一条数据相同
为False时,缺失数据所有字段填NaN
:return: 数据集,分笔数据和K线数据格式不同
period为'tick'时:{stock1 : value1, stock2 : value2, ...}
stock1, stock2, ... : 合约代码
value1, value2, ... : np.ndarray 数据列表,按time增序排列
period为其他K线周期时:{field1 : value1, field2 : value2, ...}
field1, field2, ... : 数据字段
value1, value2, ... : pd.DataFrame 字段对应的数据,各字段维度相同,index为stock_list,columns为time_list
'''
if period in {'1m', '5m', '15m', '30m', '60m', '1h', '1d', '1w', '1mon', '1q', '1hy', '1y'}:
import pandas as pd
index, data = get_market_data_ori(field_list, stock_list, period, start_time, end_time, count, dividend_type, fill_data)
result = {}
for field in data:
result[field] = pd.DataFrame(data[field], index = index[0], columns = index[1])
return result
return get_market_data_ori(field_list, stock_list, period, start_time, end_time, count, dividend_type, fill_data)
def get_market_data_ex_ori(
field_list = [], stock_list = [], period = '1d'
, start_time = '', end_time = '', count = -1
, dividend_type = 'none', fill_data = True, enable_read_from_server = True
, data_dir = ''
):
client = get_client()
enable_read_from_local = period in {'1m', '5m', '15m', '30m', '60m', '1h', '1d', 'tick', '1w', '1mon', '1q', '1hy', '1y'}
global debug_mode
return client.get_market_data3(field_list, stock_list, period, start_time, end_time, count, dividend_type, fill_data, 'v3', enable_read_from_local, enable_read_from_server, debug_mode, data_dir)
def get_market_data_ex(
field_list = [], stock_list = [], period = '1d'
, start_time = '', end_time = '', count = -1
, dividend_type = 'none', fill_data = True
):
if period == 'hkbrokerqueue' or period == 'hkbrokerqueue2' or period == (1820, 0):
showbrokename = period == 'hkbrokerqueue2'
return get_broker_queue_data(stock_list, start_time, end_time, count, showbrokename)
period = _get_tuple_period(period) or period
if isinstance(period, tuple):
return _get_market_data_ex_tuple_period(field_list, stock_list, period, start_time, end_time, count, dividend_type, fill_data)
if period in {'1m', '5m', '15m', '30m', '60m', '1h', '1d', '1w', '1mon', '1q', '1hy', '1y'}:
return _get_market_data_ex_ori_221207(field_list, stock_list, period, start_time, end_time, count, dividend_type, fill_data)
import pandas as pd
result = {}
ifield = 'time'
query_field_list = field_list if (not field_list) or (ifield in field_list) else [ifield] + field_list
ori_data = get_market_data_ex_ori(query_field_list, stock_list, period, start_time, end_time, count, dividend_type, fill_data)
if not ori_data:
return result
fl = field_list
stime_fmt = '%Y%m%d' if period == '1d' else '%Y%m%d%H%M%S'
if fl:
fl2 = fl if ifield in fl else [ifield] + fl
for s in ori_data:
sdata = pd.DataFrame(ori_data[s], columns = fl2)
sdata2 = sdata[fl]
sdata2.index = [timetag_to_datetime(t, stime_fmt) for t in sdata[ifield]]
result[s] = sdata2
else:
needconvert, metaid = _needconvert_period(period)
if needconvert:
convert_field_list = get_field_list(metaid)
for s in ori_data:
odata = ori_data[s]
if convert_field_list:
convert_data_list = []
for data in odata:
convert_data = _convert_component_info(data, convert_field_list)
convert_data_list.append(convert_data)
odata = convert_data_list
sdata = pd.DataFrame(odata)
sdata.index = [timetag_to_datetime(t, stime_fmt) for t in sdata[ifield]]
result[s] = sdata
else:
for s in ori_data:
sdata = pd.DataFrame(ori_data[s])
sdata.index = [timetag_to_datetime(t, stime_fmt) for t in sdata[ifield]]
result[s] = sdata
return result
def _get_market_data_ex_ori_221207(
field_list = [], stock_list = [], period = '1d'
, start_time = '', end_time = '', count = -1
, dividend_type = 'none', fill_data = True, enable_read_from_server = True
, data_dir = ''
):
import numpy as np
import pandas as pd
client = get_client()
enable_read_from_local = period in {'1m', '5m', '15m', '30m', '60m', '1h', '1d', 'tick', '1w', '1mon', '1q', '1hy', '1y'}
global debug_mode
ret = client.get_market_data3(field_list, stock_list, period, start_time, end_time, count, dividend_type, fill_data, 'v4', enable_read_from_local,
enable_read_from_server, debug_mode, data_dir)
result = {}
for stock, index, npdatas in ret:
data = {field: np.frombuffer(b, fi) for field, fi, b in npdatas}
result[stock] = pd.DataFrame(data=data, index=index)
return result
def _get_market_data_ex_221207(
field_list = [], stock_list = [], period = '1d'
, start_time = '', end_time = '', count = -1
, dividend_type = 'none', fill_data = True, enable_read_from_server = True
):
ifield = 'time'
query_field_list = field_list if (not field_list) or (ifield in field_list) else [ifield] + field_list
if period in {'1m', '5m', '15m', '30m', '60m', '1h', '1d', '1w', '1mon', '1q', '1hy', '1y'}:
ori_data = _get_market_data_ex_ori_221207(query_field_list, stock_list, period, start_time, end_time, count, dividend_type, fill_data, enable_read_from_server)
else:
ori_data = get_market_data_ex_ori(query_field_list, stock_list, period, start_time, end_time, count, dividend_type, fill_data, enable_read_from_server)
import pandas as pd
result = {}
fl = field_list
if fl:
fl2 = fl if ifield in fl else [ifield] + fl
for s in ori_data:
sdata = pd.DataFrame(ori_data[s], columns = fl2)
sdata2 = sdata[fl]
sdata2.index = pd.to_datetime((sdata[ifield] + 28800000) * 1000000)
result[s] = sdata2
else:
for s in ori_data:
sdata = pd.DataFrame(ori_data[s])
sdata.index = pd.to_datetime((sdata[ifield] + 28800000) * 1000000)
result[s] = sdata
return result
get_market_data3 = _get_market_data_ex_221207
def _get_data_file_path(stocklist, period, date = '20380119'):
if isinstance(period, tuple):
metaid, periodNum = period
periodstr = ''
else:
periodstr = period
metaid = -1
periodNum = -1
data = {
'stocklist': stocklist
, 'period': periodstr
, 'metaid':metaid
, 'periodNum':periodNum
, 'date':date
}
client = get_client()
path_result = __bsoncall_common(
client.commonControl, 'getdatafilepath'
, data
)
return path_result.get('result', {})
__TUPLE_PERIODS = {
'warehousereceipt' : (4015,86400000)
, 'futureholderrank' : (5008,86400000)
, 'interactiveqa' : (7011, 86400000)
, 'northfinancechange1m' : (3006, 60000)
, 'northfinancechange1d' : (3006, 86400000)
, 'dividendplaninfo' : (2025, 86401000)
, 'etfredemptionlist' : (2004, 86401000)
, 'stoppricedata' : (9506, 86400000)
, 'historymaincontract' : (5004, 86400000)
, 'brokerqueue' : (1820,0)
, 'brokerqueue2' : (1820,0)
, 'brokerinfo' : (2038,86401000)
, 'delistchangebond' : (4020, 86401000)
, 'replacechangebond' : (4021, 86401000)
, 'optionhistorycontract' : (9502, 86400000)
, 'etfiopv1m' :(4011, 60000)
, 'etfiopv1d' :(4011, 86400000)
}
__STR_PERIODS = {
(3001,60000) : '1m'
, (3001,300000) : '5m'
, (3001,900000) : '15m'
, (3001,1800000) : '30m'
, (3001,3600000) : '60m'
, (3001,3600000) : '1h'
, (3001,86400000) : '1d'
}
def _needconvert_period(period):
datas = {
'snapshotindex' : 3004
, 'etfiopv' : 4011
}
return period in datas, datas.get(period, -1)
def _get_tuple_period(period):
if isinstance(period, tuple):
return __STR_PERIODS.get(period, None)
else:
return __TUPLE_PERIODS.get(period, None)
def _get_market_data_ex_tuple_period_ori(
stock_list = [], period = ()
, start_time = '', end_time = ''
, count = -1
):
client = get_client()
data_path_dict = _get_data_file_path(stock_list, period)
import pandas as pd
ori_data = {}
for stockcode in data_path_dict:
file_name = data_path_dict[stockcode]
data_list = bson.BSON.decode(client.read_local_data(file_name, start_time, end_time, count)).get('result')
ori_data[stockcode] = data_list
return ori_data
def _convert_component_info(data, convert_field_list):
if not isinstance(data, dict):
return data
new_data = {}
for key, value in data.items():
name = convert_field_list.get(key, key)
if isinstance(value, dict):
new_data[name] = _convert_component_info(value, convert_field_list)
elif isinstance(value, list):
new_data[name] = [_convert_component_info(item, convert_field_list) for item in value]
else:
new_data[name] = value
return new_data
def _get_market_data_ex_tuple_period(
field_list = [], stock_list = [], period = '1d'
, start_time = '', end_time = '', count = -1
, dividend_type = 'none', fill_data = True, enable_read_from_server = True
):
if not isinstance(period, tuple):
return {}
all_data = _get_market_data_ex_tuple_period_ori(stock_list, period, start_time, end_time, count)
metaid, periodNum = period
convert_field_list = get_field_list(metaid)
import pandas as pd
ori_data = {}
for stockcode,data_list in all_data.items():
if convert_field_list:
convert_data_list = []
for data in data_list:
convert_data = _convert_component_info(data, convert_field_list)
convert_data_list.append(convert_data)
data_list = convert_data_list
ori_data[stockcode] = pd.DataFrame(data_list)
return ori_data
def get_data_dir():
cl = get_client()
return os.path.abspath(cl.get_data_dir())
def get_local_data(field_list=[], stock_list=[], period='1d', start_time='', end_time='', count=-1,
dividend_type='none', fill_data=True, data_dir=None):
if data_dir == None:
data_dir = ''
if period in {'1m', '5m', '15m', '30m', '60m', '1h', '1d', '1w', '1mon', '1q', '1hy', '1y'}:
return _get_market_data_ex_ori_221207(field_list, stock_list, period, start_time, end_time, count,
dividend_type, fill_data, False, data_dir)
import pandas as pd
result = {}
ifield = 'time'
query_field_list = field_list if (not field_list) or (ifield in field_list) else [ifield] + field_list
ori_data = get_market_data_ex_ori(query_field_list, stock_list, period, start_time, end_time, count, dividend_type,
fill_data, False, data_dir)
if not ori_data:
return result
fl = field_list
stime_fmt = '%Y%m%d' if period == '1d' else '%Y%m%d%H%M%S'
if fl:
fl2 = fl if ifield in fl else [ifield] + fl
for s in ori_data:
sdata = pd.DataFrame(ori_data[s], columns = fl2)
sdata2 = sdata[fl]
sdata2.index = [timetag_to_datetime(t, stime_fmt) for t in sdata[ifield]]
result[s] = sdata2
else:
for s in ori_data:
sdata = pd.DataFrame(ori_data[s])
sdata.index = [timetag_to_datetime(t, stime_fmt) for t in sdata[ifield]]
result[s] = sdata
return result
def get_l2_quote(field_list=[], stock_code='', start_time='', end_time='', count=-1):
'''
level2实时行情
'''
global debug_mode
client = get_client()
datas = client.get_market_data3(field_list, [stock_code], 'l2quote', start_time, end_time, count, 'none', False, '', False, True, debug_mode, '')
if datas:
return datas[stock_code]
return None
def get_l2_order(field_list=[], stock_code='', start_time='', end_time='', count=-1):
'''
level2逐笔委托
'''
global debug_mode
client = get_client()
datas = client.get_market_data3(field_list, [stock_code], 'l2order', start_time, end_time, count, 'none', False, '', False, True, debug_mode, '')
if datas:
return datas[stock_code]
return None
def get_l2_transaction(field_list=[], stock_code='', start_time='', end_time='', count=-1):
'''
level2逐笔成交
'''
global debug_mode
client = get_client()
datas = client.get_market_data3(field_list, [stock_code], 'l2transaction', start_time, end_time, count, 'none', False, '', False, True, debug_mode, '')
if datas:
return datas[stock_code]
return None
def get_divid_factors(stock_code, start_time='', end_time=''):
'''
获取除权除息日及对应的权息
:param stock_code: (str)股票代码
:param date: (str)日期
:return: pd.DataFrame 数据集
'''
client = get_client()
datas = client.get_divid_factors(stock_code, start_time, end_time)
import pandas as pd
datas = pd.DataFrame(datas).T
return datas
@try_except
def getDividFactors(stock_code, date):
client = get_client()
resData = client.get_divid_factors(stock_code, date)
res = {resData[i]: [resData[i + 1][j] for j in
range(0, len(resData[i + 1]), 1)] for i in range(0, len(resData), 2)}
if isinstance(res, dict):
for k, v in res.items():
if isinstance(v, list) and len(v) > 5:
v[5] = int(v[5])
return res
def get_main_contract(code_market):
'''
获取当前期货主力合约
:param code_market: (str)股票代码
:return: str
'''
client = get_client()
return client.get_main_contract(code_market)
def datetime_to_timetag(datetime, format = "%Y%m%d%H%M%S"):
if len(datetime) == 8:
format = "%Y%m%d"
timetag = time.mktime(time.strptime(datetime, format))
return timetag * 1000
def timetag_to_datetime(timetag, format):
'''
将毫秒时间转换成日期时间
:param timetag: (int)时间戳毫秒数
:param format: (str)时间格式
:return: str
'''
return timetagToDateTime(timetag, format)
@try_except
def timetagToDateTime(timetag, format):
import time
timetag = timetag / 1000
time_local = time.localtime(timetag)
return time.strftime(format, time_local)
def get_trading_dates(market, start_time='', end_time='', count=-1):
'''
根据市场获取交易日列表
: param market: 市场代码 e.g. 'SH','SZ','IF','DF','SF','ZF'等
: param start_time: 起始时间 '20200101'
: param end_time: 结束时间 '20201231'
: param count: 数据个数,-1为全部数据
:return list(long) 毫秒数的时间戳列表
'''
client = get_client()
datas = client.get_trading_dates_by_market(market, start_time, end_time, count)
return datas
def get_full_tick(code_list):
'''
获取盘口tick数据
:param code_list: (list)stock.market组成的股票代码列表
:return: dict
{'stock.market': {dict}}
'''
client = get_client()
resp_json = client.get_full_tick(code_list)
return json.loads(resp_json)
def subscribe_callback_wrapper(callback):
import traceback
def subscribe_callback(datas):
try:
if type(datas) == bytes:
datas = bson.BSON.decode(datas)
if callback:
callback(datas)
except:
print('subscribe callback error:', callback)
traceback.print_exc()
return subscribe_callback
def subscribe_callback_wrapper_1820(callback):
import traceback
def subscribe_callback(datas):
try:
if type(datas) == bytes:
datas = bson.BSON.decode(datas)
datas = _covert_hk_broke_data(datas)
if callback:
callback(datas)
except:
print('subscribe callback error:', callback)
traceback.print_exc()
return subscribe_callback
def subscribe_callback_wrapper_convert(callback, metaid):
import traceback
convert_field_list = get_field_list(metaid)
def subscribe_callback(datas):
try:
if type(datas) == bytes:
datas = bson.BSON.decode(datas)
if convert_field_list:
for s in datas:
sdata = datas[s]
convert_data_list = []
for data in sdata:
convert_data = _convert_component_info(data, convert_field_list)
convert_data_list.append(convert_data)
datas[s] = convert_data_list
if callback:
callback(datas)
except:
print('subscribe callback error:', callback)
traceback.print_exc()
return subscribe_callback
def subscribe_quote(stock_code, period='1d', start_time='', end_time='', count=0, callback=None):
'''
订阅股票行情数据
:param stock_code: 股票代码 e.g. "000001.SZ"
:param start_time: 开始时间,格式YYYYMMDD/YYYYMMDDhhmmss/YYYYMMDDhhmmss.milli,e.g."20200427" "20200427093000" "20200427093000.000"
若取某日全量历史数据,时间需要具体到秒,e.g."20200427093000"
:param end_time: 结束时间 同“开始时间”
:param count: 数量 -1全部/n: 从结束时间向前数n个
:param period: 周期 分笔"tick" 分钟线"1m"/"5m" 日线"1d"
:param callback:
订阅回调函数onSubscribe(datas)
:param datas: {stock : [data1, data2, ...]} 数据字典
:return: int 订阅序号
'''
if callback:
needconvert, metaid = _needconvert_period(period)
if needconvert:
callback = subscribe_callback_wrapper_convert(callback, metaid)
elif period == 'brokerqueue2':
callback = subscribe_callback_wrapper_1820(callback)
else:
callback = subscribe_callback_wrapper(callback)
period = _get_tuple_period(period) or period
if isinstance(period, tuple):
metaid, periodNum = period
meta = {'stockCode': stock_code, 'period': period, 'metaid': metaid, 'periodnum': periodNum}
else:
meta = {'stockCode': stock_code, 'period': period, 'metaid': -1, 'periodnum': -1}
region = {'startTime': start_time, 'endTime': end_time, 'count': count}
client = get_client()
return client.subscribe_quote(bson.BSON.encode(meta), bson.BSON.encode(region), callback)
def subscribe_l2thousand(stock_code, gear_num = 0, callback = None):
'''
订阅千档盘口
'''
if callback:
callback = subscribe_callback_wrapper(callback)
meta = {'stockCode': stock_code, 'period': 'l2thousand', 'metaid': -1, 'periodnum': -1}
region = {'thousandGearNum': gear_num, 'thousandDetailGear': 0, 'thousandDetailNum': 0}
client = get_client()
return client.subscribe_quote(bson.BSON.encode(meta), bson.BSON.encode(region), callback)
def subscribe_l2thousand_queue(
stock_code, callback = None
, gear = None
, price = None
):
'''
根据档位或价格订阅千档
stock_code: 股票代码 e.g. "000001.SZ"
callback:
订阅回调函数onSubscribe(datas)
gear: 按档位订阅 eg.
price: 单个价格:float, 价格范围:eg.[8.66, 8.88], 一组价格list
return: int 订阅序号
例:
def on_data(datas):
for stock_code in datas:
print(stock_code, datas[stock_code])
subscribe_l2thousand_queue(‘000001.SZ’, callback = on_data, gear = 3)#订阅买卖3档数据
subscribe_l2thousand_queue(‘000001.SZ’, callback = on_data, price = (8.68, 8.88))#订阅[8.68, 8.88]价格区间的数据
'''
if callback:
callback = subscribe_callback_wrapper(callback)
if gear is not None and price is not None:
raise Exception('不能同时订阅档位和价格!')
if gear is None:
gear = 0
if price is not None:
if isinstance(price, float):
price = [int(price * 10000)]
elif isinstance(price, tuple):
sprice, eprice = price
price = [i for i in range(int(sprice * 10000), int((eprice + 0.01) * 10000), int(0.01 * 10000))]
else:
price = [i * 10000 for i in price]
price.sort()
meta = {'stockCode': stock_code, 'isSubscribeByType': True, 'gear': gear, 'price': price, 'period': 'l2thousand',
'metaid': -1, 'periodnum': -1}
region = {'thousandDetailGear': 1000, 'thousandDetailNum': 1000}