-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.py
1978 lines (1681 loc) · 68.4 KB
/
utils.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
from asyncio.windows_events import NULL
import os
import time
import math
import math as m
import requests
import scipy.stats as ss
import numpy as np
import pandas as pd
import datetime
import calendar
from bokeh.io import output_file, show
from bokeh.layouts import column, row, gridplot, layout
from bokeh.plotting import figure
from bokeh.models import LinearAxis, Range1d, VBar, DatetimeTickFormatter
from scipy.stats import linregress
cur_dir = os.path.dirname(__file__)
data_dir = os.path.join(cur_dir, 'data')
cme_data_dir = os.path.join(data_dir, 'cme_daily_bulletin')
black_dir = os.path.join(data_dir, 'black')
future_position_dir = os.path.join(data_dir, 'future_position')
option_position_dir = os.path.join(data_dir, 'option_position')
future_price_dir = os.path.join(data_dir, 'future_price')
option_price_dir = os.path.join(data_dir, 'option_price')
lme_price_dir = os.path.join(future_price_dir, 'lme')
msci_dir = os.path.join(data_dir, 'msci')
fx_dir = os.path.join(data_dir, 'fx')
cfd_dir = os.path.join(data_dir, 'cfd')
spot_dir = os.path.join(data_dir, 'spot')
hkma_dir = os.path.join(data_dir, 'hkma')
interest_rate_dir = os.path.join(data_dir, 'interest_rate')
pboc_dir = os.path.join(data_dir, 'pboc')
btc_dir = os.path.join(data_dir, 'btc')
nbs_dir = os.path.join(data_dir, 'nbs')
sge_dir = os.path.join(data_dir, 'sge')
treasury_auction_dir = os.path.join(data_dir, 'treasury_auction')
fed_dir = os.path.join(data_dir, 'fed')
safe_dir = os.path.join(data_dir, 'safe')
lg_bond_dir = os.path.join(data_dir, 'lg_bond')
lbma_dir = os.path.join(data_dir, 'lbma')
exchange_dict = {'cffex':["IH", "IF", "IC", "IM", "TS", "TF", "T", "TL"],
'shfe':["cu", "au", "ag", "zn", "al", "ao", "pb", "ru", "br", "rb", "fu", "hc", "bu", "ni", "sn", "sp", "ss", "sc", "nr", "lu", "bc"],
'dce':["a", "b", "c", "cs", "i", "j", "jd", "jm", "l", "m", "p", "pp", "v", "y", "eg", "eb", "pg", "lh"],
'czce':['PX','SH', "CF", "CY", "SR", "TA", "OI", "MA", "FG", "RM", "SF", "SM", "AP", "CJ", "UR", "SA", "PF", "PK"],
'gfex':["si", "SI", "lc", "LC"],
}
exchange_option_dict = {'cffex':["IH", "IF", "IM"],
'shfe':["cu", "au", "ag", "zn", "al", "ru", "br", "rb", "sc"],
'dce':["a", "b", "c", "i", "l", "m", "p", "pp", "v", "y", "eg", "eb", "pg"],
'czce':['PX', 'SH', "CF", "SR", "TA", "OI", "MA", "RM", "PK", 'AP', 'PF', 'SA', 'SM', 'SF', 'UR'],
'gfex':["si", "lc"],
}
# 20种颜色
many_colors = ['orange','blue','purple','crimson','darkgreen','khaki','deeppink',
'cyan','darkgray','tomato','turquoise','yellow','yellowgreen','midnightblue','black',
'teal','cornsilk','red','gold']
month_dict = {'JAN':'01','FEB':'02','MAR':'03','APR':'04','MAY':'05','JUN':'06',
'JUL':'07','AUG':'08','SEP':'09','OCT':'10','NOV':'11','DEC':'12'}
character_month_dict = {'F':'01', 'G':'02', 'H':'03', 'J':'04', 'K':'05', 'M':'06',
'N':'07', 'Q':'08', 'U':'09', 'V':'10', 'X':'11', 'Z':'12'}
TOOLS="crosshair,pan,reset,wheel_zoom,box_zoom,save"
# TOOLS="hover,crosshair,pan,reset,wheel_zoom,box_zoom,save"
def chinese_to_english(chinese_var: str):
"""
映射期货品种中文名称和英文缩写
:param chinese_var: 期货品种中文名称
:return: 对应的英文缩写
"""
chinese_list = [
'对二甲苯',
'烧碱',
"橡胶",
"天然橡胶",
"石油沥青",
"沥青",
"沥青仓库",
"沥青(仓库)",
"沥青厂库",
"沥青(厂库)",
"热轧卷板",
"热轧板卷",
"燃料油",
"白银",
"线材",
"螺纹钢",
"铅",
"铜",
"铝",
"锌",
"黄金",
"钯金",
"锡",
"镍",
"纸浆",
"豆一",
"大豆",
"豆二",
"胶合板",
"玉米",
"玉米淀粉",
"聚乙烯",
"LLDPE",
"LDPE",
"豆粕",
"豆油",
"大豆油",
"棕榈油",
"纤维板",
"鸡蛋",
"聚氯乙烯",
"PVC",
"聚丙烯",
"PP",
"焦炭",
"焦煤",
"铁矿石",
"乙二醇",
"强麦",
"强筋小麦",
" 强筋小麦",
"硬冬白麦",
"普麦",
"硬白小麦",
"硬白小麦()",
"皮棉",
"棉花",
"一号棉",
"白糖",
"PTA",
"菜籽油",
"菜油",
"早籼稻",
"早籼",
"甲醇",
"柴油",
"玻璃",
"油菜籽",
"菜籽",
"菜籽粕",
"菜粕",
"动力煤",
"粳稻",
"晚籼稻",
"晚籼",
"硅铁",
"锰硅",
"硬麦",
"棉纱",
"苹果",
"原油",
"中质含硫原油",
"尿素",
"20号胶",
"苯乙烯",
"不锈钢",
"粳米",
"20号胶20",
"红枣",
"不锈钢仓库",
"纯碱",
"液化石油气",
"低硫燃料油",
"纸浆仓库",
"石油沥青厂库",
"石油沥青仓库",
"螺纹钢仓库",
"螺纹钢厂库",
"纸浆厂库",
"低硫燃料油仓库",
"低硫燃料油厂库",
"短纤",
'涤纶短纤',
'生猪',
'花生',
'工业硅',
'碳酸锂',
]
english_list = [
'PX',
'SH',
"ru",
"ru",
"bu",
"bu",
"bu",
"bu",
"bu",
"bu",
"hc",
"hc",
"fu",
"ag",
"wr",
"rb",
"pb",
"cu",
"al",
"zn",
"au",
"au",
"sn",
"ni",
"sp",
"a",
"a",
"b",
"bb",
"c",
"cs",
"l",
"l",
"l",
"m",
"y",
"y",
"p",
"fb",
"jd",
"v",
"v",
"pp",
"pp",
"j",
"jm",
"i",
"eg",
"WH",
"WH",
"WH",
"PM",
"PM",
"PM",
"PM",
"CF",
"CF",
"CF",
"SR",
"TA",
"OI",
"OI",
"RI",
"ER",
"MA",
"MA",
"FG",
"RS",
"RS",
"RM",
"RM",
"ZC",
"JR",
"LR",
"LR",
"SF",
"SM",
"WT",
"CY",
"AP",
"sc",
"sc",
"UR",
"NR",
"eb",
"ss",
"RR",
"NR",
"CJ",
"ss",
"SA",
"pg",
"lu",
"sp",
"bu",
"bu",
"rb",
"rb",
"sp",
"lu",
"lu",
"PF",
"PF",
"lh",
"PK",
"si",
"lc",
]
pos = chinese_list.index(chinese_var)
return english_list[pos]
def read_csv_data(path, cols):
df = pd.read_csv(path)
t = pd.DatetimeIndex(pd.to_datetime(df['time'], format='%Y-%m-%d'))
d = {}
for col in cols:
d[col] = np.array(df[col], dtype=float)
return t, d
########### FRED ##########
def update_fred_data(name_code, directory, earlist_time=None, time_format='%Y-%m-%d'):
#
api_key = None
if api_key is None:
return
se = requests.session()
URL = 'https://api.stlouisfed.org/fred/series/observations?series_id={}&observation_start={}&api_key={}&file_type=json'
if earlist_time is None:
earlist_time = '1990-01-01'
for name in name_code:
print(name)
path = os.path.join(directory, name+'.csv')
if os.path.exists(path):
old_df = pd.read_csv(path)
start_time = old_df.loc[len(old_df)-1, 'time']
cols = old_df.columns.tolist()
else:
old_df = pd.DataFrame()
start_time = earlist_time
cols = []
start_time_dt = pd.to_datetime(start_time, format='%Y-%m-%d') - pd.Timedelta(days=14)
start_time = start_time_dt.strftime('%Y-%m-%d')
codes = name_code[name]
df = pd.DataFrame()
new_df = pd.DataFrame()
for i in range(len(codes)):
code = codes[i][0]
name = codes[i][1]
while (1):
try:
if name in cols:
url = URL.format(code, start_time, api_key)
print(name, start_time + '-')
else:
url = URL.format(code, earlist_time, api_key)
print(name, earlist_time + '-')
r = se.get(url, timeout=10)
data_json = r.json()
break
except Exception as e:
print(e)
time.sleep(10)
temp_df = pd.DataFrame(data_json['observations'])
temp_df.rename(columns={'date':'time', 'value':name}, inplace=True)
temp_df = temp_df[['time', name]]
temp_df.replace('.', np.nan, inplace=True)
if name in cols:
if (df.empty):
df = temp_df.copy()
else:
df = pd.merge(df, temp_df, on='time', how='outer')
else:
if (new_df.empty):
new_df = temp_df.copy()
else:
new_df = pd.merge(new_df, temp_df, on='time', how='outer')
#####
if (len(df) > 0) and (len(new_df) == 0):
old_df = pd.concat([old_df, df], axis=0)
old_df.drop_duplicates(subset=['time'], keep='last', inplace=True)
old_df['time'] = old_df['time'].apply(lambda x:pd.to_datetime(x, format=time_format))
old_df.sort_values(by = 'time', inplace=True)
old_df['time'] = old_df['time'].apply(lambda x:datetime.datetime.strftime(x,time_format))
old_df.to_csv(path, encoding='utf-8', index=False)
if (len(df) > 0) and (len(new_df) > 0):
old_df = pd.concat([old_df, df], axis=0)
old_df.drop_duplicates(subset=['time'], keep='last', inplace=True)
old_df = pd.merge(old_df, new_df, on='time', how='outer')
old_df['time'] = old_df['time'].apply(lambda x:pd.to_datetime(x, format=time_format))
old_df.sort_values(by = 'time', inplace=True)
old_df['time'] = old_df['time'].apply(lambda x:datetime.datetime.strftime(x,time_format))
old_df.to_csv(path, encoding='utf-8', index=False)
if (len(df) == 0) and (len(new_df) > 0):
new_df.to_csv(path, encoding='utf-8', index=False)
########### FRED ##########
########### OPTION ##########
def column_index_price(data, price):
L = len(data)
# data[idx1] < 0.25
# data[idx2] > 0.25
_max = 999999
_min = -1
idx1 = -1
idx2 = -1
for i in range(L):
if np.isnan(data[i]):
continue
if (data[i] <= 0.0):
continue
if (data[i] <= price and data[i] > _min):
idx1 = i
_min = data[i]
if (data[i] >= price and data[i] < _max):
idx2 = i
_max = data[i]
return idx1, idx2, _min, _max
def column_index_delta(data, delta):
L = len(data)
# data[idx1] < 0.25
# data[idx2] > 0.25
_max = 1
_min = -1
idx1 = -1
idx2 = -1
for i in range(L):
if np.isnan(data[i]):
continue
if (data[i] == 0.0):
continue
if (data[i] <= delta and data[i] > _min):
idx1 = i
_min = data[i]
if (data[i] >= delta and data[i] < _max):
idx2 = i
_max = data[i]
return idx1, idx2, _min, _max
def call_bsm(S0, K, r, T, sqrt_T, Otype, sig):
d1 = ((m.log(S0/K)) + (r+ (sig*sig)/2)*T)/(sig*sqrt_T)
d2 = d1 - sig*sqrt_T
if (Otype == "C"):
price = S0*(ss.norm.cdf(d1)) \
- K*(m.exp(-r*T))*(ss.norm.cdf(d2))
return (price)
elif (Otype == "P"):
price = -S0*(ss.norm.cdf(-d1))\
+ K*(m.exp(-r*T))*(ss.norm.cdf(-d2))
return price
def vega(S0, K, r, T, sqrt_T, sig):
d1 = ((m.log(S0/K)) + (r+ (sig*sig)/2)*T)/(sig*sqrt_T)
vega = S0*(ss.norm.pdf(d1))*sqrt_T
return vega
def implied_volatility(S0, K, T, r, price, Otype):
e = 1e-3
x0 = 1
sqrt_T = m.sqrt(T)
def newtons_method(S0, K, T, sqrt_T, r, price, Otype, x0, e):
k=0
delta = call_bsm(S0, K, r, T, sqrt_T, Otype, x0) - price
while delta > e:
k=k+1
if (k > 30):
return np.nan
_vega = vega(S0, K, r, T, sqrt_T, x0)
if (_vega == 0.0):
return np.nan
x0 = (x0 - (call_bsm(S0, K, r, T, sqrt_T, Otype, x0) - price)/_vega)
delta = abs(call_bsm(S0, K, r, T, sqrt_T, Otype, x0) - price)
return x0
iv = newtons_method(S0, K, T, sqrt_T, r, price, Otype, x0, e)
return iv
def calculate_greeks(S0, K, T, r, price, Otype):
if (np.isnan(S0) or np.isnan(K) or np.isnan(price) or S0==0.0 or price==0.0):
return [np.nan, np.nan]
if (Otype == 'C' and S0/K > 1.25):
return [0, 0]
if (Otype == 'P' and K/S0 > 1.25):
return [0, 0]
if (T < 0.25/365):
return [np.nan, np.nan]
sqrt_T = m.sqrt(T)
# print(S0, K, T, r, price, Otype)
# imp_vol
iv = implied_volatility(S0, K, T, r, price, Otype)
d1 = ((m.log(S0/K)) + (r + (iv*iv)/2)*T)/(iv*sqrt_T)
# delta
if Otype == 'C':
delta = ss.norm.cdf(d1)
else:
delta = ss.norm.cdf(d1) - 1
return [round(iv,5), round(delta,4)]
###############################
def get_last_line_time(path, data_name, earlist_time, time_length, time_format):
if os.path.exists(path):
# 最后一行的时间
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()
try:
last_line_dt = pd.to_datetime(last_line[:time_length], format=time_format)
start_time = last_line_dt.strftime(time_format)
except:
start_time = earlist_time
print(data_name + ' UPDATE ' + path + ' ' + start_time)
else:
print(data_name + ' CREATE ' + path)
start_time = earlist_time
return start_time
# 统计局城市月度数据
def get_cs_price_change_count(df, name, thres=100.0):
hi_count = []
eq_count = []
lo_count = []
for i in range(len(df)):
# 环比上涨、持平、下跌城市个数
change = np.array(df.loc[i, pd.IndexSlice[:, name]])
hi = len(np.where(change > thres)[0])
eq = len(np.where(change == thres)[0])
lo = len(np.where(change < thres)[0])
hi_count.append(hi)
eq_count.append(eq)
lo_count.append(lo)
hi_count = np.array(hi_count)
eq_count = np.array(eq_count)
lo_count = np.array(lo_count)
return hi_count, eq_count, lo_count
# 同比
#TODO
def yoy(time, data):
idx = 0
L = len(time)
t2 = time[-1]
t1 = t2 - pd.Timedelta(days=365)
for i in range(L):
if time[i] >= t1:
idx = i
break
# print(idx)
if ((t2 - time[idx]) >= pd.Timedelta(days=370)) or ((t2 - time[idx]) <= pd.Timedelta(days=360)):
return NULL, NULL
new_time = time[L-idx-1:]
new_data = data[L-idx-1:] / data[0:idx+1] - 1
return new_time, new_data
# 同比
def yoy_for_monthly_data(time, data):
idx = 0
L = len(time)
t2 = time[-1]
t1 = datetime.datetime(t2.year-1, t2.month, t2.day)
for i in range(L):
if time[i] == t1:
idx = i
break
if (idx == 0):
print('算不了同比')
return NULL, NULL
new_time = time[L-idx-1:]
new_data = data[L-idx-1:] / data[0:idx+1] - 1
return new_time, new_data
# 线性插值
def interpolate_nan(time, data):
t = time[-1] - time[0]
L = t.days
new_time = pd.date_range(start=time[0], end=time[-1])
x = np.linspace(0, L, L+1)
idx = np.where(np.isnan(data)==False)[0]
idx2 = np.zeros((len(idx)))
for i in range(len(idx)):
idx2[i] = np.where(new_time == time[idx[i]])[0]
new_data = np.interp(x, idx2, data[idx])
return new_time, new_data
def interpolate_season_to_month(time, data):
new_time = np.empty((3*len(time)-2), dtype=type(time))
new_data = np.empty((3*len(time)-2), dtype=type(data))
for i in range(len(time)-1):
# 时间
new_time[i*3+0] = time[i]
t = time[i] + pd.Timedelta(days=15)
days_num = calendar.monthrange(t.year, t.month)[1] # 获取当前月有多少天
new_time[i*3+1] = new_time[i*3+0] + pd.Timedelta(days=days_num)
t = time[i] + pd.Timedelta(days=45)
days_num = calendar.monthrange(t.year, t.month)[1] # 获取当前月有多少天
new_time[i*3+2] = new_time[i*3+1] + pd.Timedelta(days=days_num)
# 数据
new_data[i*3+0] = data[i]
new_data[i*3+1] = 2/3 * data[i] + 1/3 * data[i+1]
new_data[i*3+2] = 1/3 * data[i] + 2/3 * data[i+1]
new_time[-1] = time[-1]
new_data[-1] = data[-1]
return pd.DatetimeIndex(new_time), new_data
def yyyymm_to_yyyymmdd(time):
new_time = np.empty((len(time)), dtype=type(time))
for i in range(len(time)):
days_num = calendar.monthrange(time[i].year, time[i].month)[1] # 获取当前月有多少天
new_time[i] = time[i] + pd.Timedelta(days=(days_num-1))
return new_time
def get_last_friday(year, month):
last_day = calendar.monthrange(year, month)[-1]
dt = datetime.datetime(year=year, month=month, day=last_day)
while (1):
weekday = dt.weekday()
if weekday == 4: # friday
break
dt = dt - pd.Timedelta(days=1)
return datetime.datetime(year=dt.year, month=dt.month, day=dt.day)
def get_month_last_day(year, month):
last_day = calendar.monthrange(year, month)[-1]
month_lasy_day_dt = datetime.datetime(year=year, month=month, day=last_day)
return month_lasy_day_dt
def get_pre_month_last_day(year, month):
if month == 1:
last_day = calendar.monthrange(year-1, 12)[-1]
pre_month_lasy_day_dt = datetime.datetime(year=year-1, month=12, day=last_day)
else:
last_day = calendar.monthrange(year, month-1)[-1]
pre_month_lasy_day_dt = datetime.datetime(year=year, month=month-1, day=last_day)
return pre_month_lasy_day_dt
# 截取时间从 start 到 end 的数据
def get_period_data(time, data, start, end='2099-01-01', remove_nan=False, format='%Y-%m-%d'):
start_time = pd.to_datetime(start, format=format)
end_time = pd.to_datetime(end, format=format)
if len(time) == 0:
return np.zeros(1), np.zeros(1)
if remove_nan == False:
idx = np.where((start_time <= time) & (time <= end_time))[0]
return time[idx], data[idx]
else:
idx = np.where((start_time <= time) & (time <= end_time))[0]
t = time[idx]
d = data[idx]
idx = np.logical_not(np.isnan(d))
return t[idx], d[idx]
def moving_average(time, data, T):
weights = np.ones(T)/T
new_data = np.convolve(data, weights)[T-1:-T+1]
new_time = time[T-1:]
return new_time, new_data
def moving_std(time, data, T):
L = len(time)
new_data = np.empty((L), dtype=float)
for i in range(T-1, L):
new_data[i] = np.std(data[i-T+1:i])
new_time = time[T-1:]
new_data = new_data[T-1:]
return new_time, new_data
def compare_two_data(datas, start_time='2010-01-01', end_time='2100-01-01'):
datas_ = [[[datas[0]], [datas[1]], ''],]
fig_list = plot_many_figure(datas_, max_height=400, start_time=start_time, end_time=end_time, ret=True)
# 散点图
fig2 = plot_circle(datas, start_time=start_time, end_time=end_time, ret=True)
figs = fig_list + [fig2]
show(column(figs))
def compare_two_option_data(datas, start_time, end_time='2100-01-01'):
datas_ = [[[datas[0]], [datas[1]], ''],
[[datas[2]], [datas[3]], ''],]
fig_list = plot_many_figure(datas_, max_height=250, start_time=start_time, end_time=end_time, ret=True)
# 散点图
fig2 = plot_circle([datas[0], datas[1]], start_time=start_time, end_time=end_time, ret=True)
fig3 = plot_circle([datas[2], datas[3]], start_time=start_time, end_time=end_time, ret=True)
l = layout([[fig_list[0]], [fig_list[1]], [fig2,fig3]])
show(l)
def get_full_strike_price(df):
col = df.columns.tolist()
put_strike = [(col[i][1]) for i in range(len(col)) if col[i][0] == 'P']
# call_strike = [(col[i][1]) for i in range(len(col)) if col[i][0] == 'C']
res = []
for i in put_strike:
if i not in res:
res.append(i)
put_strike = np.array(res, dtype=float)
return put_strike
def plot_future_correlation(exchange1, variety1, exchange2, variety2, start_time='2022-01-01', end_time='2099-01-01'):
path1 = os.path.join(future_price_dir, exchange1, variety1+'.csv')
df1 = pd.read_csv(path1, header=[0,1])
t1 = pd.DatetimeIndex(pd.to_datetime(df1['time']['Unnamed: 0_level_1'], format='%Y-%m-%d'))
price1 = np.array(df1['c2']['close'], dtype=float)
w = np.where(price1 > 1)[0]
t1 = t1[w]
price1 = price1[w]
path2 = os.path.join(future_price_dir, exchange2, variety2+'.csv')
df2 = pd.read_csv(path2, header=[0,1])
t2 = pd.DatetimeIndex(pd.to_datetime(df2['time']['Unnamed: 0_level_1'], format='%Y-%m-%d'))
price2 = np.array(df2['c2']['close'], dtype=float)
w = np.where(price2 > 1)[0]
t2 = t2[w]
price2 = price2[w]
t1, price1 = get_period_data(t1, price1, start_time, end_time)
t2, price2 = get_period_data(t2, price2, start_time, end_time)
idx1 = np.isin(t1, t2)
idx2 = np.isin(t2, t1)
t1 = t1[idx1]
price1 = price1[idx1]
t2 = t2[idx2]
price2 = price2[idx2]
n = 250
slope, intercept, r, _, _ = linregress(price1[-n:], price2[-n:])
fig1 = figure(frame_width=650, frame_height=650)
fig1.circle(x=price1[-n:], y=price2[-n:], color="purple", legend_label='近一年'+', x = '+variety1+', y = '+variety2+', y = '+str(round(slope,3))+'*x +' + str(round(intercept,3))+', r^2 = ' + str(round(r*r,3)))
yy = price1[-n:] * slope + intercept
fig1.line(x=price1[-n:], y=yy, color="black")
fig1.legend.location='top_left'
slope, intercept, r, _, _ = linregress(price1[-n*2:], price2[-n*2:])
fig2 = figure(frame_width=650, frame_height=650)
fig2.circle(x=price1[-n*2:], y=price2[-n*2:], color="purple", legend_label='近两年'+', x = '+variety1+', y = '+variety2+', y = '+str(round(slope,3))+'*x +' + str(round(intercept,3))+', r^2 = ' + str(round(r*r,3)))
yy = price1[-n*2:] * slope + intercept
fig2.line(x=price1[-n*2:], y=yy, color="black")
fig2.legend.location='top_left'
show(row(fig1,fig2))
pass
def plot_metal_stock(variety, name):
path = os.path.join(data_dir, 'lme_stock'+'.csv')
lme_df = pd.read_csv(path)
t1 = pd.DatetimeIndex(pd.to_datetime(lme_df['time'], format='%Y-%m-%d'))
lme_stock0 = np.array(lme_df[name+'-库存'], dtype=float)
lme_stock1 = np.array(lme_df[name+'-注册仓单'], dtype=float)
lme_stock2 = np.array(lme_df[name+'-注销仓单'], dtype=float)
path = os.path.join(future_price_dir, 'shfe', variety+'_stock'+'.csv')
stock_df = pd.read_csv(path)
t2 = pd.DatetimeIndex(pd.to_datetime(stock_df['time'], format='%Y-%m-%d'))
shfe_stock0 = np.array(stock_df['小计'], dtype=float)
shfe_stock1 = np.array(stock_df['期货'], dtype=float)
t3, stock_all = data_add(t1, lme_stock0, t2, shfe_stock1)
path = path = os.path.join(lme_price_dir, variety+'.csv')
df = pd.read_csv(path)
t0 = pd.DatetimeIndex(pd.to_datetime(df['time'], format='%Y-%m-%d'))
cash_bid = np.array(df['cash_bid'], dtype=float)
cash_ask = np.array(df['cash_ask'], dtype=float)
M3_bid = np.array(df['3M_bid'], dtype=float)
M3_ask = np.array(df['3M_ask'], dtype=float)
diff_03 = (cash_bid + cash_ask - M3_bid - M3_ask)/2
datas = [[[[t0, cash_bid, name + ' cash bid',''],
[t0, cash_ask, name + ' cash ask',''],
[t0, M3_bid, name + ' 3M bid',''],
[t0, M3_ask, name + ' 3M ask',''],],[],''],
[[[t0, diff_03, name + ' 0-3价差',''],
],[],''],
[[[t3, stock_all,'SHFE+LME 库存',''],
],[],''],
[[[t2,shfe_stock0,name+' 库存小计',''],
[t2,shfe_stock1,name+' 库存期货',''],
],[],''],
[[[t1,lme_stock0,'LME '+name+'-库存',''],
[t1,lme_stock1,'LME '+name+'-注册仓单',''],
[t1,lme_stock2,'LME '+name+'-注销仓单',''],
],[],''],
]
plot_many_figure(datas, max_height=800)
def plot_exchange_stock(exchange, variety):
path1 = os.path.join(future_price_dir, exchange, variety+'_stock'+'.csv')
if not(os.path.exists(path1)):
return
stock_df = pd.read_csv(path1)
t1 = pd.DatetimeIndex(pd.to_datetime(stock_df['time'], format='%Y-%m-%d'))
stock0 = np.array(stock_df['小计'], dtype=float)
stock1 = np.array(stock_df['期货'], dtype=float)
path2 = os.path.join(future_price_dir, exchange, variety+'.csv')
fut_df = pd.read_csv(path2, header=[0,1])
t2 = pd.DatetimeIndex(pd.to_datetime(fut_df['time']['Unnamed: 0_level_1'], format='%Y-%m-%d'))
dominant_contract_price = np.array(fut_df['index']['close'])
datas = [[[[t2, dominant_contract_price, variety+' 指数',''],
],[],''],
[[[t1, stock0,'库存小计',''],[t1, stock1,'库存期货',''],
],[],''],
]
plot_many_figure(datas)
# def plot_mean_std(t1, data1, name1, t2, data2, name2, T, start_time='2000-01-01', end_time='2099-01-01'):
def plot_mean_std(datas1, datas2, T, max_height=425, start_time='2000-01-01', end_time='2099-01-01', ret=False):
time.sleep(0.25)
L1 = len(datas1)
fig_list = list()
for i in range(L1):
if (i==0):
fig_list.append(figure(frame_width=1400, frame_height=max_height//L1, tools=TOOLS, x_axis_type = "datetime"))
else:
fig_list.append(figure(frame_width=1400, frame_height=max_height//L1, tools=TOOLS, x_range=fig_list[0].x_range, x_axis_type = "datetime"))
t11, data11 = get_period_data(datas1[i][0], datas1[i][1], start_time, end_time, remove_nan=True)
t3, mean = moving_average(t11, data11, T=T)
t3, std = moving_std(t11, data11, T=T)
fig_list[i].y_range = Range1d(np.nanmin(data11) - abs(np.nanmin(data11))*0.05, np.nanmax(data11) + abs(np.nanmax(data11))*0.05)
fig_list[i].line(t11, data11, line_width=2, line_color='black', legend_label=datas1[i][2])
fig_list[i].line(t3, mean+2*std, line_width=2, color='orange', line_dash='dashed', legend_label='+2std')
fig_list[i].line(t3, mean+1*std, line_width=2, color='yellow', line_dash='dashed', legend_label='+1std')
fig_list[i].line(t3, mean+0*std, line_width=2, color='gray', line_dash='dashed', legend_label='mean')
fig_list[i].line(t3, mean-1*std, line_width=2, color='lightblue', line_dash='dashed', legend_label='-1std')
fig_list[i].line(t3, mean-2*std, line_width=2, color='blue', line_dash='dashed', legend_label='-2std')
fig_list[i].xaxis[0].ticker.desired_num_ticks = 20
fig_list[i].legend.location='top_left'
L2 = len(datas2)
fig2_list = list()
for i in range(L2):
fig2_list.append(figure(frame_width=1400, frame_height=200, tools=TOOLS, x_range=fig_list[0].x_range, x_axis_type = "datetime", y_axis_location="right"))
t22, data22 = get_period_data(datas2[i][0], datas2[i][1], start_time, end_time, remove_nan=True)
fig2_list[i].line(t22, data22, line_width=2, line_color='black', legend_label=datas2[i][2])
fig2_list[i].xaxis[0].ticker.desired_num_ticks = 20
fig2_list[i].legend.location='top_left'
fig_list = fig_list + fig2_list
if ret == False:
show(column(fig_list))
else:
return fig_list
def plot_one_figure(datas, title=None, start_time='2000-01-01', end_time='2099-01-01'):
time.sleep(0.5)
L = len(datas)
z0_list = list()
fig = figure(frame_width=1400, frame_height=680, tools=TOOLS, title=title, x_axis_type = "datetime")
for i in range(L):
z0_list.append(get_period_data(datas[i][0], datas[i][1], start_time, end_time, remove_nan=True))
fig.line(z0_list[i][0], z0_list[i][1], line_width=2, line_color=many_colors[i], legend_label=datas[i][2])
fig.xaxis[0].ticker.desired_num_ticks = 20
fig.legend.click_policy="hide"
fig.legend.location='top_left'
show(fig)
# def parse_string(s):
# parsed_dict = {}
# w1 = s.find('style=')
# if (w1 >= 0):
# w2 = s[w1:].find(',')
# if (w2 >= 0):
# r = s[w1+6:w2]
# else:
# r = s[w1+6:]
# parsed_dict['style'] = r
# w1 = s.find('color=')
# if (w1 >= 0):
# w2 = s[w1:].find(',')
# if (w2 >= 0):
# r = s[w1+6:w2]
# else:
# r = s[w1+6:]
# parsed_dict['color'] = r
# w1 = s.find('width=')
# if (w1 >= 0):
# w2 = s[w1:].find(',')
# if (w2 >= 0):
# r = s[w1+6:w2]
# else:
# r = s[w1+6:]
# parsed_dict['width'] = r
# w1 = s.find('visible=')
# if (w1 >= 0):
# w2 = s[w1:].find(',')
# if (w2 >= 0):
# r = s[w1+8:w2]
# else:
# r = s[w1+8:]
# if r == 'True':
# r = True
# else:
# r = False
# parsed_dict['visible'] = r
# return parsed_dict
def parse_string(s):
s = s.strip()
ss = s.split(',')
parsed_dict = {}
for opt in ss:
z = opt.split('=')
if len(z) == 2:
if z[0] == 'visible':
if z[1] == 'True':
z[1] = True
else:
z[1] = False
parsed_dict[z[0]] = z[1]
return parsed_dict
def list_min_max(z):
_min = 999999999
_max = -999999999
for i in range(len(z)):
try:
tmp = np.nanmax(z[i][1])