-
Notifications
You must be signed in to change notification settings - Fork 0
/
cn_fut_opt.py
3112 lines (2702 loc) · 123 KB
/
cn_fut_opt.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
import os
import requests
import csv
import pandas as pd
import zipfile
import datetime
import numpy as np
import akshare as ak
import bs4
from utils import *
from akshare.futures import cons, receipt
from io import StringIO, BytesIO
import dateutil.relativedelta
from chinamoney import *
from lme import *
from pork import *
from spot import *
from intraday import update_sse_intraday_option_data
from sgx_fut_opt import update_sgx_fut_opt_data
from nasdaq import update_all_nasdaq_etf_option_data, update_all_nasdaq_etf_data
from hkma import update_hkma_data
from hkex_fut_opt import update_hkex_fut_opt_data
from us_rate import update_all_us_rate
from us_debt import update_treasury_auction_data
from fx import update_fx_data
from moa import *
from black import *
from position import update_all_institution_position
from sge import update_all_sge_data
from cfd import *
from vix import *
from fed import *
from jp_rate import *
from lbma import *
import warnings
from akshare.option.cons import (
get_calendar,
convert_date,
DCE_DAILY_OPTION_URL,
SHFE_OPTION_URL,
CZCE_DAILY_OPTION_URL_3,
SHFE_HEADERS,
)
# future_dict = {}
##########################################################################################
######################################## POSITION ########################################
##########################################################################################
# shfe
# symbol rank vol_party_name vol vol_chg long_party_name long_open_interest long_open_interest_chg short_party_name short_open_interest short_open_interest_chg variety
# dce
# rank vol_party_name vol vol_chg long_party_name long_open_interest long_open_interest_chg short_party_name short_open_interest short_open_interest_chg symbol var date
# czce
# rank vol_party_name vol vol_chg long_party_name long_open_interest long_open_interest_chg short_party_name short_open_interest short_open_interest_chg symbol variety
# cffex
# long_open_interest long_open_interest_chg long_party_name rank short_open_interest short_open_interest_chg short_party_name symbol vol vol_chg vol_party_name variety
# 统一
# inst_id
# vol_party_name vol vol_chg long_party_name long_open_interest long_open_interest_chg short_party_name short_open_interest short_open_interest_chg
def create_future_position_file(path):
if not os.path.exists(path):
c1 = ['time']
c2 = ['']
c2_add = ['1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16','17','18','19','20','top5','top10','top15','top20']
c3 = ['']
keys = ['vol_party_name', 'vol', 'vol_chg', 'long_party_name', 'long_open_interest', 'long_open_interest_chg', 'short_party_name', 'short_open_interest', 'short_open_interest_chg']
for i in range(6): # 6个合约
c1.append(str(i+1))
c2.append('inst_id')
c3.append('')
for j in range(len(c2_add)): # 持仓排名 1~20
for _ in range(len(keys)): # keys
c1.append(str(i+1))
c2.append(c2_add[j])
c3 += keys
df = pd.DataFrame(columns=[c1,c2,c3])
df.to_csv(path, encoding='utf-8', index=False)
print('FUTURE POSITION CREATE ' + path)
def get_future_position(exchange, date):
if exchange == 'shfe':
d = ak.get_shfe_rank_table(date=date) # , vars_list=['HC']
if exchange == 'dce':
d = ak.futures_dce_position_rank(date=date) # , vars_list=['I']
if exchange == 'czce':
d = ak.get_czce_rank_table(date=date)
if exchange == 'cffex':
d = ak.get_cffex_rank_table(date=date)
keys = ['vol_party_name', 'vol', 'vol_chg', 'long_party_name', 'long_open_interest', 'long_open_interest_chg', 'short_party_name', 'short_open_interest', 'short_open_interest_chg']
# 每个品种归类
keys_list = list(d.keys())
dd = dict()
for s in keys_list:
if (s[1].isdigit()): #
if not (s[0] in dd):
z = list()
for ss in keys_list:
if ss[0] == s[0] and ss[1].isdigit():
z.append(ss)
dd[s[0]] = z
else:
if not (s[0:2] in dd):
z = list()
for ss in keys_list:
if ss[0:2] == s[0:2]:
z.append(ss)
dd[s[0:2]] = z
ret_dict = {}
null_data = []
# 每个品种
keys_list = list(dd.keys())
for s in keys_list:
tmps = list()
inst_id_list = dd[s]
L = len(inst_id_list)
actual_L = 0
vol20 = list()
for i in range(L):
# czce, dce的数字带逗号
if (exchange == 'czce' or exchange == 'dce'):
d[inst_id_list[i]] = d[inst_id_list[i]].replace(',', '', regex=True)
# 有空值,忽略所有数据
if (d[inst_id_list[i]].iloc[0:20].isnull().any().any() or len(d[inst_id_list[i]].iloc[0:20]) < 20):
# print(inst_id_list[i])
# print('NULLLLLLLLLLLLLLLLLLL')
continue
tmp = d[inst_id_list[i]].iloc[0:20]
tmp_list = tmp[keys].values.flatten().tolist()
tmp_list = [inst_id_list[i]] + tmp_list # inst_id + keys
# czce, dce的数字带逗号
try:
vol = np.array(tmp['vol'], dtype=float)
vol_chg = np.array(tmp['vol_chg'], dtype=float)
long_open_interest = np.array(tmp['long_open_interest'], dtype=float)
long_open_interest_chg = np.array(tmp['long_open_interest_chg'], dtype=float)
short_open_interest = np.array(tmp['short_open_interest'], dtype=float)
short_open_interest_chg = np.array(tmp['short_open_interest_chg'], dtype=float)
except:
continue
# vol
actual_L += 1
vol20.append(np.sum(vol[:20]))
# top5
top5 = ['', np.sum(vol[:5]), np.sum(vol_chg[:5]), '', np.sum(long_open_interest[:5]), np.sum(long_open_interest_chg[:5]), '', np.sum(short_open_interest[:5]), np.sum(short_open_interest_chg[:5])]
tmp_list += top5
# top10
top10 = ['', np.sum(vol[:10]), np.sum(vol_chg[:10]), '', np.sum(long_open_interest[:10]), np.sum(long_open_interest_chg[:10]), '', np.sum(short_open_interest[:10]), np.sum(short_open_interest_chg[:10])]
tmp_list += top10
# top15
top15 = ['', np.sum(vol[:15]), np.sum(vol_chg[:15]), '', np.sum(long_open_interest[:15]), np.sum(long_open_interest_chg[:15]), '', np.sum(short_open_interest[:15]), np.sum(short_open_interest_chg[:15])]
tmp_list += top15
# top20
top20 = ['', np.sum(vol[:20]), np.sum(vol_chg[:20]), '', np.sum(long_open_interest[:20]), np.sum(long_open_interest_chg[:20]), '', np.sum(short_open_interest[:20]), np.sum(short_open_interest_chg[:20])]
tmp_list += top20
tmps.append(tmp_list.copy())
vol20 = np.array(vol20, dtype=float)
order = np.argsort(vol20)[::-1]
date_str = date[0:4]
date_str += '-'
date_str += date[4:6]
date_str += '-'
date_str += date[6:8]
row = [date_str]
if (actual_L > 0):
for i in range(min(actual_L,6)):
row += tmps[order[i]]
if (len(null_data) < 1):
for i in range(len(tmps[0])):
null_data += [None]
# 补数据
for i in range(6 - actual_L):
row += null_data
ret_dict[s] = row
return ret_dict
def get_all_future_position(exchange, start_time):
calendar = cons.get_calendar()
data_time_dt = pd.to_datetime(start_time, format='%Y-%m-%d')
current_time_dt = datetime.datetime.now()
writers = {}
while data_time_dt <= current_time_dt:
print(data_time_dt)
# 获取的数据的时间
data_time_str = data_time_dt.strftime('%Y%m%d')
date = cons.convert_date(data_time_str)
if date.strftime("%Y%m%d") not in calendar:
data_time_dt += pd.Timedelta(days=1)
continue
ret_dict = get_future_position(exchange, data_time_str)
for key in ret_dict:
if not(key in writers):
path = os.path.join(future_position_dir, exchange, key+'.csv')
if os.path.exists(path):
print('FUTURE POSITION APPEND ' + path)
else:
create_future_position_file(path)
f = open(path, 'a', newline='', encoding='utf-8')
writer = csv.writer(f)
writers[key] = writer
if len(ret_dict[key]) > 1:
writers[key].writerow(ret_dict[key])
data_time_dt += pd.Timedelta(days=1)
time.sleep(0.5)
# return
def update_all_future_position(exchange):
print('UPDATE FUTURE POSITION: ', exchange)
if exchange == 'shfe':
path = os.path.join(future_position_dir, exchange, 'au'+'.csv')
if exchange == 'dce':
path = os.path.join(future_position_dir, exchange, 'i'+'.csv')
if exchange == 'czce':
path = os.path.join(future_position_dir, exchange, 'SR'+'.csv')
if exchange == 'cffex':
path = os.path.join(future_position_dir, exchange, 'IC'+'.csv')
# 最后一行的时间
with open(path, 'rb') as f:
f.seek(0, os.SEEK_END)
pos = f.tell() - 1 # 不算最后一个字符'\n'
while pos > 0:
pos -= 1
f.seek(pos, os.SEEK_SET)
if f.read(1) == b'\n':
break
last_line = f.readline().decode().strip()
print('FUTURE POSITION LAST TIME: ', last_line[:10])
data_time_dt = pd.to_datetime(last_line[:10], format='%Y-%m-%d')
data_time_dt += pd.Timedelta(days=1)
data_time_str = data_time_dt.strftime('%Y-%m-%d')
get_all_future_position(exchange, data_time_str)
######## OPTION POSITION ########
def create_option_position_file(path):
if not os.path.exists(path):
c0 = ['time']
c1 = ['time']
c2 = ['time']
c2_add = ['1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16','17','18','19','20','top5','top10','top15','top20']
c3 = ['time']
keys = ['vol_party_name', 'vol', 'vol_chg', 'long_party_name', 'long_open_interest', 'long_open_interest_chg', 'short_party_name', 'short_open_interest', 'short_open_interest_chg']
for i in range(6): # 6个合约
c0.append('C')
c1.append(str(i+1))
c2.append('inst_id')
c3.append('')
for j in range(len(c2_add)): # 持仓排名 1~20
for _ in range(len(keys)): # keys
c0.append('C')
c1.append(str(i+1))
c2.append(c2_add[j])
c3 += keys
c0.append('P')
c1.append(str(i+1))
c2.append('inst_id')
c3.append('')
for j in range(len(c2_add)): # 持仓排名 1~20
for _ in range(len(keys)): # keys
c0.append('P')
c1.append(str(i+1))
c2.append(c2_add[j])
c3 += keys
df = pd.DataFrame(columns=[c0,c1,c2,c3])
df.to_csv(path, encoding='utf-8', index=False)
print('OPTION POSITION CREATE ' + path)
def options_dce_position_rank(date: str = "20160919") -> dict:
"""
大连商品交易所-每日持仓排名-具体合约
http://www.dce.com.cn/dalianshangpin/xqsj/tjsj26/rtj/rcjccpm/index.html
:param date: 指定交易日; e.g., "20200511"
:type date: str
:return: 指定日期的持仓排名数据
:rtype: pandas.DataFrame
"""
calendar = cons.get_calendar()
date = (
cons.convert_date(date) if date is not None else datetime.date.today()
)
if date.strftime("%Y%m%d") not in calendar:
warnings.warn("%s非交易日" % date.strftime("%Y%m%d"))
return {}
url = "http://www.dce.com.cn/publicweb/quotesdata/exportMemberDealPosiQuotesBatchData.html"
headers = {
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
"Accept-Encoding": "gzip, deflate",
"Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
"Cache-Control": "no-cache",
"Connection": "keep-alive",
"Content-Length": "160",
"Content-Type": "application/x-www-form-urlencoded",
"Host": "www.dce.com.cn",
"Origin": "http://www.dce.com.cn",
"Pragma": "no-cache",
"Referer": "http://www.dce.com.cn/publicweb/quotesdata/memberDealPosiQuotes.html",
"Upgrade-Insecure-Requests": "1",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36",
}
payload = {
"memberDealPosiQuotes.variety": "a",
"memberDealPosiQuotes.trade_type": "1",
"contract.contract_id": "a2009",
"contract.variety_id": "a",
"year": date.year,
"month": date.month - 1,
"day": date.day,
"batchExportFlag": "batch",
}
r = requests.post(url, payload, headers=headers)
big_dict = dict()
with zipfile.ZipFile(BytesIO(r.content), "r") as z:
# print(z.namelist())
for i in z.namelist():
file_name = i.encode("cp437").decode("GBK")
if not file_name.startswith(date.strftime("%Y%m%d")):
continue
try:
data = pd.read_table(z.open(i), header=None, sep="\t")
if len(data) < 16: # 处理没有活跃合约的情况
big_dict[file_name.split("_")[1]] = [pd.DataFrame(), pd.DataFrame()]
continue
temp_filter = data[
data.iloc[:, 0].str.find("名次") == 0
].index.tolist()
if (
temp_filter[1] - temp_filter[0] < 5
): # 过滤有无成交量但是有买卖持仓的数据, 如 20201105_c2011_成交量_买持仓_卖持仓排名.txt
big_dict[file_name.split("_")[1]] = [pd.DataFrame(), pd.DataFrame()]
continue
start_list = data[
data.iloc[:, 0].str.find("名次") == 0
].index.tolist()
data_c = data.iloc[
start_list[0] : start_list[3], # 看涨期权
data.columns[data.iloc[start_list[0], :].notnull()],
].copy()
data_c.reset_index(inplace=True, drop=True)
start_list = data_c[
data_c.iloc[:, 0].str.find("名次") == 0
].index.tolist()
end_list = data_c[
data_c.iloc[:, 0].str.find("总计") == 0
].index.tolist()
part_one = data_c[start_list[0] : end_list[0]].iloc[1:, :]
part_two = data_c[start_list[1] : end_list[1]].iloc[1:, :]
part_three = data_c[start_list[2] : end_list[2]].iloc[1:, :]
temp_df_c = pd.concat(
[
part_one.reset_index(drop=True),
part_two.reset_index(drop=True),
part_three.reset_index(drop=True),
],
axis=1,
ignore_index=True,
)
temp_df_c.columns = [
"名次",
"会员简称",
"成交量",
"增减",
"名次",
"会员简称",
"持买单量",
"增减",
"名次",
"会员简称",
"持卖单量",
"增减",
]
temp_df_c["rank"] = range(1, len(temp_df_c) + 1)
del temp_df_c["名次"]
temp_df_c.columns = [
"vol_party_name",
"vol",
"vol_chg",
"long_party_name",
"long_open_interest",
"long_open_interest_chg",
"short_party_name",
"short_open_interest",
"short_open_interest_chg",
"rank",
]
temp_df_c["symbol"] = file_name.split("_")[1]
temp_df_c["variety"] = file_name.split("_")[1][:-4].upper()
temp_df_c = temp_df_c[
[
"long_open_interest",
"long_open_interest_chg",
"long_party_name",
"rank",
"short_open_interest",
"short_open_interest_chg",
"short_party_name",
"vol",
"vol_chg",
"vol_party_name",
"symbol",
"variety",
]
]
start_list = data[
data.iloc[:, 0].str.find("名次") == 0
].index.tolist()
data_p = data.iloc[
start_list[3] : , # 看跌期权
data.columns[data.iloc[start_list[3], :].notnull()],
].copy()
data_p.reset_index(inplace=True, drop=True)
start_list = data_p[
data_p.iloc[:, 0].str.find("名次") == 0
].index.tolist()
end_list = data_p[
data_p.iloc[:, 0].str.find("总计") == 0
].index.tolist()
part_one = data_p[start_list[0] : end_list[0]].iloc[1:, :]
part_two = data_p[start_list[1] : end_list[1]].iloc[1:, :]
part_three = data_p[start_list[2] : end_list[2]].iloc[1:, :]
temp_df_p = pd.concat(
[
part_one.reset_index(drop=True),
part_two.reset_index(drop=True),
part_three.reset_index(drop=True),
],
axis=1,
ignore_index=True,
)
temp_df_p.columns = [
"名次",
"会员简称",
"成交量",
"增减",
"名次",
"会员简称",
"持买单量",
"增减",
"名次",
"会员简称",
"持卖单量",
"增减",
]
temp_df_p["rank"] = range(1, len(temp_df_p) + 1)
del temp_df_p["名次"]
temp_df_p.columns = [
"vol_party_name",
"vol",
"vol_chg",
"long_party_name",
"long_open_interest",
"long_open_interest_chg",
"short_party_name",
"short_open_interest",
"short_open_interest_chg",
"rank",
]
temp_df_p["symbol"] = file_name.split("_")[1]
temp_df_p["variety"] = file_name.split("_")[1][:-4].upper()
temp_df_p = temp_df_p[
[
"long_open_interest",
"long_open_interest_chg",
"long_party_name",
"rank",
"short_open_interest",
"short_open_interest_chg",
"short_party_name",
"vol",
"vol_chg",
"vol_party_name",
"symbol",
"variety",
]
]
# print(temp_df_c)
# print(temp_df_p)
# return
big_dict[file_name.split("_")[1]] = [temp_df_c, temp_df_p]
except UnicodeDecodeError as e:
print('UnicodeDecodeError: ', e)
exit()
# try:
# data = pd.read_table(
# z.open(i),
# header=None,
# sep="\\s+",
# encoding="gb2312",
# skiprows=3,
# )
# except:
# data = pd.read_table(
# z.open(i),
# header=None,
# sep="\\s+",
# encoding="gb2312",
# skiprows=4,
# )
# start_list = data[
# data.iloc[:, 0].str.find("名次") == 0
# ].index.tolist()
# end_list = data[
# data.iloc[:, 0].str.find("总计") == 0
# ].index.tolist()
# part_one = data[start_list[0] : end_list[0]].iloc[1:, :]
# part_two = data[start_list[1] : end_list[1]].iloc[1:, :]
# part_three = data[start_list[2] : end_list[2]].iloc[1:, :]
# temp_df = pd.concat(
# [
# part_one.reset_index(drop=True),
# part_two.reset_index(drop=True),
# part_three.reset_index(drop=True),
# ],
# axis=1,
# ignore_index=True,
# )
# temp_df.columns = [
# "名次",
# "会员简称",
# "成交量",
# "增减",
# "名次",
# "会员简称",
# "持买单量",
# "增减",
# "名次",
# "会员简称",
# "持卖单量",
# "增减",
# ]
# temp_df["rank"] = range(1, len(temp_df) + 1)
# del temp_df["名次"]
# temp_df.columns = [
# "vol_party_name",
# "vol",
# "vol_chg",
# "long_party_name",
# "long_open_interest",
# "long_open_interest_chg",
# "short_party_name",
# "short_open_interest",
# "short_open_interest_chg",
# "rank",
# ]
# temp_df["symbol"] = file_name.split("_")[1]
# temp_df["variety"] = file_name.split("_")[1][:-4].upper()
# temp_df = temp_df[
# [
# "long_open_interest",
# "long_open_interest_chg",
# "long_party_name",
# "rank",
# "short_open_interest",
# "short_open_interest_chg",
# "short_party_name",
# "vol",
# "vol_chg",
# "vol_party_name",
# "symbol",
# "variety",
# ]
# ]
# big_dict[file_name.split("_")[1]] = temp_df
return big_dict
def get_option_position(exchange, date):
if exchange == 'dce':
d = options_dce_position_rank(date=date)
if exchange == 'czce':
d = ak.get_czce_rank_table(date=date)
keys = ['vol_party_name', 'vol', 'vol_chg', 'long_party_name', 'long_open_interest', 'long_open_interest_chg', 'short_party_name', 'short_open_interest', 'short_open_interest_chg']
# 每个品种归类
keys_list = list(d.keys())
dd = dict()
for s in keys_list:
if (s[1].isdigit()): #
if not (s[0] in dd):
z = list()
for ss in keys_list:
if ss[0] == s[0] and ss[1].isdigit():
z.append(ss)
dd[s[0]] = z
else:
if not (s[0:2] in dd):
z = list()
for ss in keys_list:
if ss[0:2] == s[0:2]:
z.append(ss)
dd[s[0:2]] = z
ret_dict = {}
null_data = []
# 每个品种
keys_list = list(dd.keys())
for s in keys_list:
tmps = list()
inst_id_list = dd[s]
L = len(inst_id_list)
actual_L = 0
vol20 = list()
for i in range(L):
# czce, dce的数字带逗号
if (exchange == 'czce' or exchange == 'dce'):
d[inst_id_list[i]][0] = d[inst_id_list[i]][0].replace(',', '', regex=True)
d[inst_id_list[i]][1] = d[inst_id_list[i]][1].replace(',', '', regex=True)
# 有空值,忽略所有数据
if (d[inst_id_list[i]][0].iloc[0:20].isnull().any().any() or len(d[inst_id_list[i]][0].iloc[0:20]) < 20 or
d[inst_id_list[i]][1].iloc[0:20].isnull().any().any() or len(d[inst_id_list[i]][1].iloc[0:20]) < 20):
# print(inst_id_list[i])
# print('NULLLLLLLLLLLLLLLLLLL')
continue
actual_L += 1
for k in range(2): # 0:CALL, 1:PUT
tmp = d[inst_id_list[i]][k].iloc[0:20]
tmp_list = tmp[keys].values.flatten().tolist()
tmp_list = [inst_id_list[i]] + tmp_list # inst_id + keys
vol = np.array(tmp['vol'], dtype=float)
vol_chg = np.array(tmp['vol_chg'], dtype=float)
long_open_interest = np.array(tmp['long_open_interest'], dtype=float)
long_open_interest_chg = np.array(tmp['long_open_interest_chg'], dtype=float)
short_open_interest = np.array(tmp['short_open_interest'], dtype=float)
short_open_interest_chg = np.array(tmp['short_open_interest_chg'], dtype=float)
# vol
if k==0:
vol20.append(np.sum(vol[:20]))
else:
vol20[len(vol20)-1] += np.sum(vol[:20])
# top5
top5 = ['', np.sum(vol[:5]), np.sum(vol_chg[:5]), '', np.sum(long_open_interest[:5]), np.sum(long_open_interest_chg[:5]), '', np.sum(short_open_interest[:5]), np.sum(short_open_interest_chg[:5])]
tmp_list += top5
# top10
top10 = ['', np.sum(vol[:10]), np.sum(vol_chg[:10]), '', np.sum(long_open_interest[:10]), np.sum(long_open_interest_chg[:10]), '', np.sum(short_open_interest[:10]), np.sum(short_open_interest_chg[:10])]
tmp_list += top10
# top15
top15 = ['', np.sum(vol[:15]), np.sum(vol_chg[:15]), '', np.sum(long_open_interest[:15]), np.sum(long_open_interest_chg[:15]), '', np.sum(short_open_interest[:15]), np.sum(short_open_interest_chg[:15])]
tmp_list += top15
# top20
top20 = ['', np.sum(vol[:20]), np.sum(vol_chg[:20]), '', np.sum(long_open_interest[:20]), np.sum(long_open_interest_chg[:20]), '', np.sum(short_open_interest[:20]), np.sum(short_open_interest_chg[:20])]
tmp_list += top20
tmps.append(tmp_list.copy())
date_str = date[0:4]
date_str += '-'
date_str += date[4:6]
date_str += '-'
date_str += date[6:8]
row = [date_str]
vol20 = np.array(vol20, dtype=float)
order = np.argsort(vol20)[::-1]
if (actual_L > 0):
for i in range(min(actual_L,6)):
row += tmps[order[i]*2]
row += tmps[order[i]*2+1]
if (len(null_data) < 1):
for i in range(len(tmps[0])):
null_data += [None]
null_data += [None]
# 补数据
for i in range(6 - actual_L):
row += null_data
ret_dict[s] = row
return ret_dict
def get_all_option_position(exchange, start_time):
calendar = cons.get_calendar()
data_time_dt = pd.to_datetime(start_time, format='%Y-%m-%d')
current_time_dt = datetime.datetime.now()
writers = {}
while data_time_dt <= current_time_dt:
print(data_time_dt)
# 获取的数据的时间
data_time_str = data_time_dt.strftime('%Y%m%d')
date = cons.convert_date(data_time_str)
if date.strftime("%Y%m%d") not in calendar:
data_time_dt += pd.Timedelta(days=1)
continue
ret_dict = get_option_position(exchange, data_time_str)
for key in ret_dict:
if not(key in writers):
path = os.path.join(option_position_dir, exchange, key+'.csv')
if os.path.exists(path):
print('OPTION POSITION APPEND ' + path)
else:
create_option_position_file(path)
f = open(path, 'a', newline='', encoding='utf-8')
writer = csv.writer(f)
writers[key] = writer
if len(ret_dict[key]) > 1:
writers[key].writerow(ret_dict[key])
data_time_dt += pd.Timedelta(days=1)
time.sleep(0.5)
# return
def update_all_option_position(exchange):
print('UPDATE POSITION: ', exchange)
if exchange == 'dce':
path = os.path.join(option_position_dir, exchange, 'i'+'.csv')
if exchange == 'czce':
path = os.path.join(option_position_dir, exchange, 'SR'+'.csv')
# 最后一行的时间
with open(path, 'rb') as f:
f.seek(0, os.SEEK_END)
pos = f.tell() - 1 # 不算最后一个字符'\n'
while pos > 0:
pos -= 1
f.seek(pos, os.SEEK_SET)
if f.read(1) == b'\n':
break
last_line = f.readline().decode().strip()
print('OPTION POSITION LAST TIME: ', last_line[:10])
data_time_dt = pd.to_datetime(last_line[:10], format='%Y-%m-%d')
data_time_dt += pd.Timedelta(days=1)
data_time_str = data_time_dt.strftime('%Y-%m-%d')
get_all_option_position(exchange, data_time_str)
##########################################################################################
###################################### FUTURE PRICE ######################################
##########################################################################################
def create_future_price_file(path):
if not os.path.exists(path):
c1 = ['time','index','index','index']
c1_add = ['c1','c2','c3','c4','c5','c6','c7','c8','c9','dom']
c2 = ['','close','vol','oi']
c2_add = ['inst_id','open','high','low','close','vol','oi','settle']
for i in range(len(c1_add)): # 连续合约 + 主力合约 + 指数合约
for j in range(len(c2_add)): #
c1.append(c1_add[i])
c2.append(c2_add[j])
df = pd.DataFrame(columns=[c1,c2])
df.to_csv(path, encoding='utf-8', index=False)
print('FUTURE PRICE CREATE ' + path)
def get_future_price(exchange, date):
if exchange == 'shfe':
df = ak.get_futures_daily(start_date=date, end_date=date, market="SHFE")
df['symbol'] = df['symbol'].str.lower()
df['variety'] = df['variety'].str.lower()
if exchange == 'dce':
df = ak.get_futures_daily(start_date=date, end_date=date, market="DCE")
df['symbol'] = df['symbol'].str.lower()
df['variety'] = df['variety'].str.lower()
if exchange == 'czce':
df = ak.get_futures_daily(start_date=date, end_date=date, market="CZCE")
if exchange == 'cffex':
df = ak.get_futures_daily(start_date=date, end_date=date, market="CFFEX")
if exchange == 'gfex':
df = ak.get_futures_daily(start_date=date, end_date=date, market="GFEX")
df['symbol'] = df['symbol'].str.lower()
df['variety'] = df['variety'].str.lower()
df.replace('', '0', inplace=True)
#
variety = np.array(df['variety'], dtype=str)
variety_dict = {}
for i in range(len(variety)):
if (not(variety[i] in variety_dict)):
variety_dict[variety[i]] = [i, i]
else:
variety_dict[variety[i]][1] = variety_dict[variety[i]][1] + 1
ret_dict = {}
null_data = [None,None,None,None,None,None,None,None]
date_str = date[0:4]
date_str += '-'
date_str += date[4:6]
date_str += '-'
date_str += date[6:8]
for v in variety_dict:
row = [date_str]
n = variety_dict[v][1] + 1 - variety_dict[v][0]
if (n > 0):
# 指数合约数据
tmp = df.loc[variety_dict[v][0]:variety_dict[v][1], ['symbol','open','high','low','close','volume','open_interest','settle']]
close = np.array(tmp['close'], dtype=float)
volumn = np.array(tmp['volume'], dtype=float)
oi = np.array(tmp['open_interest'], dtype=float)
# 指数合约代码
index_oi = np.sum(oi)
if (index_oi > 0):
index_close = np.sum(close*oi)/np.sum(oi)
index_volumn = np.sum(volumn)
row += [index_close, index_volumn, index_oi]
else:
row += [0, 0, 0]
if (n >= 9):
# 有至少9个合约
row += (tmp.loc[variety_dict[v][0]:variety_dict[v][0]+8]).values.flatten().tolist()
elif (n > 0):
# 不足9个合约
row += (tmp.loc[variety_dict[v][0]:variety_dict[v][0]+n-1]).values.flatten().tolist()
for _ in range(9-n):
row += null_data
# 主力
idx = np.nanargmax(volumn)
row += (tmp.loc[variety_dict[v][0]+idx]).values.flatten().tolist()
ret_dict[v] = row
return ret_dict
def get_all_future_price(exchange, start_time):
calendar = cons.get_calendar()
data_time_dt = pd.to_datetime(start_time, format='%Y-%m-%d')
current_time_dt = datetime.datetime.now()
writers = {}
while data_time_dt <= current_time_dt:
print(data_time_dt)
# 获取的数据的时间
data_time_str = data_time_dt.strftime('%Y%m%d')
date = cons.convert_date(data_time_str)
if date.strftime("%Y%m%d") not in calendar:
data_time_dt += pd.Timedelta(days=1)
continue
ret_dict = get_future_price(exchange, data_time_str)
for key in ret_dict:
if not(key in writers):
path = os.path.join(future_price_dir, exchange, key+'.csv')
if os.path.exists(path):
print('FUTURE PRICE APPEND ' + path)
else:
create_future_price_file(path)
f = open(path, 'a', newline='', encoding='utf-8')
writer = csv.writer(f)
writers[key] = writer
if len(ret_dict[key]) > 10:
writers[key].writerow(ret_dict[key])
data_time_dt += pd.Timedelta(days=1)
time.sleep(0.5)
# return
def update_all_future_price(exchange):
print('UPDATE FUTURE PRICE: ', exchange)
if exchange == 'shfe':
path = os.path.join(future_price_dir, exchange, 'au'+'.csv')
if exchange == 'dce':
path = os.path.join(future_price_dir, exchange, 'i'+'.csv')
if exchange == 'czce':
path = os.path.join(future_price_dir, exchange, 'SR'+'.csv')
if exchange == 'cffex':
path = os.path.join(future_price_dir, exchange, 'IC'+'.csv')
if exchange == 'gfex':
path = os.path.join(future_price_dir, exchange, 'si'+'.csv')
# 最后一行的时间
with open(path, 'rb') as f:
f.seek(0, os.SEEK_END)
pos = f.tell() - 1 # 不算最后一个字符'\n'
while pos > 0:
pos -= 1
f.seek(pos, os.SEEK_SET)
if f.read(1) == b'\n':
break
last_line = f.readline().decode().strip()
print('FUTURE PRICE LAST TIME: ', last_line[:10])
data_time_dt = pd.to_datetime(last_line[:10], format='%Y-%m-%d')
data_time_dt += pd.Timedelta(days=1)
data_time_str = data_time_dt.strftime('%Y-%m-%d')
get_all_future_price(exchange, data_time_str)
##########################################################################################
####################################### SPOT PRICE #######################################
##########################################################################################
def create_spot_price_file(path):
if not os.path.exists(path):
c1 = ['time', 'spot_price', 'near_contract', 'near_contract_price',
'dominant_contract', 'dominant_contract_price', 'near_basis',
'dom_basis', 'near_basis_rate', 'dom_basis_rate']
df = pd.DataFrame(columns=c1)
df.to_csv(path, encoding='utf-8', index=False)
print('SPOT PRICE CREATE ' + path)
def get_spot_price(date):
df = ak.futures_spot_price(date=date)
symbol = np.array(df['symbol'], dtype=str)
df = df.loc[:, ['spot_price', 'near_contract', 'near_contract_price',
'dominant_contract', 'dominant_contract_price', 'near_basis',
'dom_basis', 'near_basis_rate', 'dom_basis_rate']]
ret_dict = {}
date_str = date[0:4]
date_str += '-'
date_str += date[4:6]
date_str += '-'
date_str += date[6:8]
for i in range(len(symbol)):
row = [date_str]
row += (df.loc[i]).values.flatten().tolist()
s = symbol[i].lower()
if (s in exchange_dict['shfe']):
inst_id = s
exchange = 'shfe'
elif (symbol[i] in exchange_dict['cffex']):
inst_id = symbol[i]
exchange = 'cffex'
elif (s in exchange_dict['dce']):
inst_id = s
exchange = 'dce'
elif (symbol[i] in exchange_dict['czce']):
inst_id = symbol[i]
exchange = 'czce'
elif (symbol[i] in exchange_dict['gfex']):
inst_id = s
exchange = 'gfex'
else:
continue
if (s == 'si'):
row[2] = row[2].lower()
row[4] = row[4].lower()
ret_dict[inst_id] = [exchange, row]
return ret_dict
def get_all_future_spot_price(start_time):
calendar = cons.get_calendar()