/
universal.py
2762 lines (2451 loc) · 96.3 KB
/
universal.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
# -*- coding: utf-8 -*-
"""
modules for universal fetcher that gives historical daily data and realtime data
for almost everything in the market
"""
import os
import sys
import time
import datetime as dt
import numpy as np
import pandas as pd
import logging
import inspect
from bs4 import BeautifulSoup
from functools import wraps, lru_cache
from uuid import uuid4
from sqlalchemy import exc
from dateutil.relativedelta import relativedelta
try:
from jqdatasdk import (
get_index_weights,
query,
get_fundamentals,
valuation,
get_query_count,
finance,
get_index_stocks,
macro,
get_price,
)
# 本地导入
except ImportError:
try:
from jqdata import finance, macro # 云平台导入
except ImportError:
pass
from xalpha.info import basicinfo, fundinfo, mfundinfo, get_fund_holdings
from xalpha.indicator import indicator
from xalpha.cons import (
rget,
rpost,
rget_json,
rpost_json,
tz_bj,
last_onday,
region_trans,
today_obj,
_float,
)
from xalpha.provider import data_source
from xalpha.exceptions import DataPossiblyWrong, ParserFailure
pd.options.mode.chained_assignment = None # turn off setwith copy warning
thismodule = sys.modules[__name__]
xamodule = sys.modules["xalpha"]
logger = logging.getLogger(__name__)
def tomorrow_ts():
dto = dt.datetime.now() + dt.timedelta(1)
return dto.timestamp()
def has_weekday(start, end):
for d in pd.date_range(start, end):
if d.weekday() < 5:
return True
return False
def ts2pdts(ts):
dto = dt.datetime.fromtimestamp(ts / 1000, tz=tz_bj).replace(tzinfo=None)
return dto.replace(
hour=0, minute=0, second=0, microsecond=0
) # 雪球美股数据时间戳是美国0点,按北京时区换回时间后,把时分秒扔掉就重合了
def decouple_code(code):
"""
decompose SH600000.A into SH600000, after
:param code:
:return: Tuple
"""
if len(code[1:].split(".")) > 1: # .SPI in US stock!
type_ = code.split(".")[-1]
code = ".".join(code.split(".")[:-1])
if type_.startswith("b") or type_.startswith("B"):
type_ = "before"
elif type_.startswith("a") or type_.startswith("A"):
type_ = "after"
elif type_.startswith("n") or type_.startswith("N"):
type_ = "normal"
else:
logger.warning(
"unrecoginzed flag for adjusted factor %s, use default" % type_
)
type_ = "before"
else:
type_ = "before"
return code, type_
def lru_cache_time(ttl=None, maxsize=None):
"""
TTL support on lru_cache
:param ttl: float or int, seconds
:param maxsize: int, maxsize for lru_cache
:return:
"""
def wrapper(func):
# Lazy function that makes sure the lru_cache() invalidate after X secs
@lru_cache(maxsize)
def time_aware(_ttl, *args, **kwargs):
return func(*args, **kwargs)
setattr(thismodule, func.__name__ + "_ttl", time_aware)
@wraps(func)
def newfunc(*args, **kwargs):
ttl_hash = round(time.time() / ttl)
f_ttl = getattr(thismodule, func.__name__ + "_ttl")
return f_ttl(ttl_hash, *args, **kwargs)
return newfunc
return wrapper
# TODO: 缓存 token 的合适时间尺度
@lru_cache_time(ttl=300)
def get_token():
"""
获取雪球的验权 token,匿名也可获取,而且似乎永远恒定(大时间范围内会改变)
:return:
"""
r = rget("https://xueqiu.com", headers={"user-agent": "Mozilla"})
return r.cookies["xq_a_token"]
def get_historical_fromxq(code, count, type_="before", full=False):
"""
:param code:
:param count:
:param type_: str. normal, before, after
:param full:
:return:
"""
url = "https://stock.xueqiu.com/v5/stock/chart/kline.json?symbol={code}&begin={tomorrow}&period=day&type={type_}&count=-{count}"
if full:
url += "&indicator=kline,pe,pb,ps,pcf,market_capital,agt,ggt,balance"
# pe 是 TTM 数据
r = rget_json(
url.format(
code=code, tomorrow=int(tomorrow_ts() * 1000), count=count, type_=type_
),
cookies={"xq_a_token": get_token()},
headers={"user-agent": "Mozilla/5.0"},
)
df = pd.DataFrame(data=r["data"]["item"], columns=r["data"]["column"])
df["date"] = (df["timestamp"]).apply(ts2pdts) # reset hours to zero
return df
@lru_cache()
def get_industry_fromxq(code):
"""
part of symbols has empty industry information
:param code:
:return: dict
"""
url = (
"https://xueqiu.com/stock/industry/stockList.json?code=%s&type=1&size=100"
% code
)
r = rget_json(url, cookies={"xq_a_token": get_token()})
return r
def get_historical_fromcninvesting(curr_id, st_date, end_date, app=False):
data = {
"curr_id": curr_id,
# "smlID": smlID, # ? but seems to be fixed with curr_id, it turns out it doesn't matter
"st_date": st_date, # %Y/%m/%d
"end_date": end_date,
"interval_sec": "Daily",
"sort_col": "date",
"sort_ord": "DESC",
"action": "historical_data",
}
if not app: # fetch from web api
r = rpost(
"https://cn.investing.com/instruments/HistoricalDataAjax",
data=data,
headers={
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_4)\
AppleWebKit/537.36 (KHTML, like Gecko)",
"Host": "cn.investing.com",
"X-Requested-With": "XMLHttpRequest",
},
)
else: # fetch from app api
r = rpost(
"https://cnappapi.investing.com/instruments/HistoricalDataAjax",
data=data,
headers={
"Accept": "*/*",
"Accept-Encoding": "gzip",
"Accept-Language": "zh-cn",
"Cache-Control": "no-cache",
"Connection": "keep-alive",
"User-Agent": "Investing.China/0.0.3 CFNetwork/1121.2.2 Darwin/19.3.0",
"ccode": "CN",
#'ccode_time': '1585551041.986028',
"x-app-ver": "117",
"x-meta-ver": "14",
"x-os": "ios",
"x-uuid": str(uuid4()),
"Host": "cn.investing.com",
"X-Requested-With": "XMLHttpRequest",
},
)
s = BeautifulSoup(r.text, "lxml")
dfdict = {}
cols = []
for col in s.find_all("th"):
dfdict[str(col.contents[0])] = []
cols.append(str(col.contents[0]))
num_cols = len(cols)
for i, td in enumerate(s.find_all("td")[:-5]):
if cols[i % num_cols] == "日期":
dfdict[cols[i % num_cols]].append(
dt.datetime.strptime(str(td.string), "%Y年%m月%d日")
)
else:
dfdict[cols[i % num_cols]].append(str(td.string))
return pd.DataFrame(dfdict)
def prettify(df):
_map = {
"日期": "date",
"收盘": "close",
"开盘": "open",
"高": "high",
"低": "low",
"涨跌幅": "percent",
"交易量": "volume",
}
df.rename(_map, axis=1, inplace=True)
if len(df) > 1 and df.iloc[1]["date"] < df.iloc[0]["date"]:
df = df[::-1]
# df = df[["date", "open", "close", "high", "low", "percent"]]
df1 = df[["date"]]
for k in ["open", "close", "high", "low", "volume"]:
if k in df.columns:
df1[k] = df[k].apply(_float)
df1["percent"] = df["percent"]
return df1
def dstr2dobj(dstr):
if len(dstr.split("/")) > 1:
d_obj = dt.datetime.strptime(dstr, "%Y/%m/%d")
elif len(dstr.split(".")) > 1:
d_obj = dt.datetime.strptime(dstr, "%Y.%m.%d")
elif len(dstr.split("-")) > 1:
d_obj = dt.datetime.strptime(dstr, "%Y-%m-%d")
else:
d_obj = dt.datetime.strptime(dstr, "%Y%m%d")
return d_obj
@lru_cache(maxsize=1024)
def get_investing_id(suburl, app=False):
if not app:
url = "https://cn.investing.com"
else:
url = "https://cnappapi.investing.com"
if not suburl.startswith("/"):
url += "/"
url += suburl
if not app:
headers = {
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_4) AppleWebKit/537.36"
}
else:
headers = {
"Accept": "*/*",
"Accept-Encoding": "gzip",
"Accept-Language": "zh-cn",
"Cache-Control": "no-cache",
"Connection": "keep-alive",
"User-Agent": "Investing.China/0.0.3 CFNetwork/1121.2.2 Darwin/19.3.0",
"ccode": "CN",
#'ccode_time': '1585551041.986028',
"x-app-ver": "117",
"x-meta-ver": "14",
"x-os": "ios",
"x-uuid": str(uuid4()),
"Host": "cn.investing.com",
"X-Requested-With": "XMLHttpRequest",
}
r = rget(
url,
headers=headers,
)
s = BeautifulSoup(r.text, "lxml")
pid = s.find("span", id="last_last")["class"][-1].split("-")[1]
return pid
def _variate_ua():
last = 20 + np.random.randint(20)
ua = []
ua.append(
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_4) AppleWebKit/537.36 (KHTML, like Gecko)"
)
ua.append(
"Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1"
)
choice = np.random.randint(2)
return ua[choice][:last]
@lru_cache_time(ttl=120, maxsize=128)
def get_rmb(start=None, end=None, prev=360, currency="USD/CNY"):
"""
获取人民币汇率中间价, 该 API 官网数据源,稳定性很差
:param start:
:param end:
:param prev:
:param currency:
:return: pd.DataFrame
"""
bl = ["USD", "EUR", "100JPY", "HKD", "GBP", "AUD", "NZD", "SGD", "CHF", "CAD"]
al = [
"MYR",
"RUB",
"ZAR",
"KRW",
"AED",
"SAR",
"HUF",
"PLN",
"DKK",
"SEK",
"NOK",
"TRY",
"MXN",
"THB",
]
is_inverse = False
if (currency[:3] in al) or (currency[4:] in bl):
is_inverse = True
currency = currency[4:] + "/" + currency[:3]
url = "http://www.chinamoney.com.cn/ags/ms/cm-u-bk-ccpr/CcprHisNew?startDate={start_str}&endDate={end_str}¤cy={currency}&pageNum=1&pageSize=30"
if not end:
end_obj = today_obj()
else:
end_obj = dstr2dobj(end)
if not start:
start_obj = end_obj - dt.timedelta(prev)
else:
start_obj = dstr2dobj(start)
start_str = start_obj.strftime("%Y-%m-%d")
end_str = end_obj.strftime("%Y-%m-%d")
count = (end_obj - start_obj).days + 1
rl = []
# API 很奇怪,需要经常变 UA 才好用
headers = {
"Referer": "http://www.chinamoney.com.cn/chinese/bkccpr/",
"Origin": "http://www.chinamoney.com.cn",
"Host": "www.chinamoney.com.cn",
"X-Requested-With": "XMLHttpRequest",
}
segs = 30
if count <= segs:
headers.update({"user-agent": _variate_ua()})
r = rpost_json(
url.format(start_str=start_str, end_str=end_str, currency=currency),
headers=headers,
)
rl.extend(r["records"])
else: # data more than 1 year cannot be fetched once due to API limitation
sepo_obj = end_obj
sepn_obj = sepo_obj - dt.timedelta(segs)
# sep0_obj = end_obj - dt.timedelta(361)
while sepn_obj > start_obj: # [sepn sepo]
headers.update({"user-agent": _variate_ua()})
r = rpost_json(
url.format(
start_str=sepn_obj.strftime("%Y-%m-%d"),
end_str=sepo_obj.strftime("%Y-%m-%d"),
currency=currency,
),
headers=headers,
)
rl.extend(r["records"])
sepo_obj = sepn_obj - dt.timedelta(1)
sepn_obj = sepo_obj - dt.timedelta(segs)
headers.update({"user-agent": _variate_ua()})
r = rpost_json(
url.format(
start_str=start_obj.strftime("%Y-%m-%d"),
end_str=sepo_obj.strftime("%Y-%m-%d"),
currency=currency,
),
headers=headers,
)
rl.extend(r["records"])
data = {"date": [], "close": []}
for d in rl:
data["date"].append(pd.Timestamp(d["date"]))
data["close"].append(d["values"][0])
df = pd.DataFrame(data)
df = df[::-1]
df["close"] = pd.to_numeric(df["close"])
if is_inverse:
df["close"] = 1 / df["close"]
return df
def get_fund(code):
# 随意设置非空 path,防止嵌套缓存到 fundinfo
if code[0] == "F":
if code.startswith("F96"):
return get_historical_from_ttjj_oversea(code)
else:
df = fundinfo(code[1:], path="nobackend", priceonly=True).price
elif code[0] == "T":
df = fundinfo(code[1:], path="nobackend", priceonly=True).price
df["netvalue"] = df["totvalue"]
elif code[0] == "M":
df = mfundinfo(code[1:], path="nobackend").price
else:
raise ParserFailure("Unknown fund code %s" % code)
df["close"] = df["netvalue"]
return df[["date", "close"]]
def get_historical_from_ttjj_oversea(code, start=None, end=None):
if code.startswith("F"):
code = code[1:]
pagesize = (
dt.datetime.strptime(end, "%Y%m%d") - dt.datetime.strptime(start, "%Y%m%d")
).days + 1
r = rget_json(
"http://overseas.1234567.com.cn/overseasapi/OpenApiHander.ashx?api=HKFDApi&m=MethodJZ&hkfcode={hkfcode}&action=2&pageindex=0&pagesize={pagesize}&date1={startdash}&date2={enddash}&callback=".format(
hkfcode=get_hkfcode(code),
pagesize=pagesize,
startdash=start[:4] + "-" + start[4:6] + "-" + start[6:],
enddash=end[:4] + "-" + end[4:6] + "-" + end[6:],
)
)
datalist = {"date": [], "close": []}
for dd in r["Data"]:
datalist["date"].append(pd.to_datetime(dd["PDATE"]))
datalist["close"].append(dd["NAV"])
df = pd.DataFrame(datalist)
df = df[df["date"] <= end]
df = df[df["date"] >= start]
df = df.sort_values("date", ascending=True)
return df
def get_portfolio_fromttjj(code, start=None, end=None):
startobj = dt.datetime.strptime(start, "%Y%m%d")
endobj = dt.datetime.strptime(end, "%Y%m%d")
if (endobj - startobj).days < 90:
return None # note start is always 1.1 4.1 7.1 10.1 in incremental updates
if code.startswith("F"):
code = code[1:]
r = rget("http://fundf10.eastmoney.com/zcpz_{code}.html".format(code=code))
s = BeautifulSoup(r.text, "lxml")
table = s.find("table", class_="tzxq")
df = pd.read_html(str(table))[0]
df["date"] = pd.to_datetime(df["报告期"])
df["stock_ratio"] = df["股票占净比"].replace("---", "0%").apply(lambda s: _float(s[:-1]))
df["bond_ratio"] = df["债券占净比"].replace("---", "0%").apply(lambda s: _float(s[:-1]))
df["cash_ratio"] = df["现金占净比"].replace("---", "0%").apply(lambda s: _float(s[:-1]))
# df["dr_ratio"] = df["存托凭证占净比"].replace("---", "0%").apply(lambda s: xa.cons._float(s[:-1]))
df["assets"] = df["净资产(亿元)"]
df = df[::-1]
return df[["date", "stock_ratio", "bond_ratio", "cash_ratio", "assets"]]
# this is the most elegant approach to dispatch get_daily, the definition can be such simple
# you actually don't need to bother on start end blah, everything is taken care of by ``cahcedio``
@data_source("jq")
def get_fundshare_byjq(code, **kws):
code = _inverse_convert_code(code)
df = finance.run_query(
query(finance.FUND_SHARE_DAILY)
.filter(finance.FUND_SHARE_DAILY.code == code)
.filter(finance.FUND_SHARE_DAILY.date >= kws["start"])
.filter(finance.FUND_SHARE_DAILY.date <= kws["end"])
.order_by(finance.FUND_SHARE_DAILY.date)
)
df["date"] = pd.to_datetime(df["date"])
df = df[["date", "shares"]]
return df
@lru_cache(maxsize=1024)
def get_futu_id(code):
r = rget("https://www.futunn.com/stock/{code}".format(code=code))
sind = r.text.find("securityId")
futuid = r.text[sind : sind + 30].split("=")[1].split(";")[0].strip(" ").strip("'")
sind = r.text.find("marketType")
market = r.text[sind : sind + 30].split("=")[1].split(";")[0].strip().strip("''")
return futuid, market
def get_futu_historical(code, start=None, end=None):
fid, market = get_futu_id(code)
r = rget(
"https://www.futunn.com/new-quote/kline?security_id={fid}&type=2&market_type={market}".format(
fid=fid, market=market
)
)
df = pd.DataFrame(r.json()["data"]["list"])
df["date"] = df["k"].map(
lambda s: dt.datetime.fromtimestamp(s)
.replace(hour=0, minute=0, second=0, microsecond=0)
.replace(tzinfo=None)
)
df["open"] = df["o"] / 1000
df["close"] = df["c"] / 1000
df["high"] = df["h"] / 1000
df["low"] = df["l"] / 1000
df["volume"] = df["v"]
df = df.drop(["k", "t", "o", "c", "h", "l", "v"], axis=1)
return df
def get_historical_fromsp(code, start=None, end=None, region="www", **kws):
"""
标普官网数据源
:param code:
:param start:
:param end:
:param kws:
:return:
"""
if code.startswith("SP"):
code = code[2:]
if len(code.split(".")) > 1:
col = code.split(".")[1]
code = code.split(".")[0]
else:
col = "1"
start_obj = dt.datetime.strptime(start, "%Y%m%d")
fromnow = (today_obj() - start_obj).days
if fromnow < 300:
flag = "one"
elif fromnow < 1000:
flag = "three"
else:
flag = "ten"
url = "https://{region}.spindices.com/idsexport/file.xls?\
selectedModule=PerformanceGraphView&selectedSubModule=Graph\
&yearFlag={flag}YearFlag&indexId={code}".format(
region=region, flag=flag, code=code
)
r = rget(
url,
headers={
"sec-fetch-dest": "document",
"sec-fetch-mode": "navigate",
"sec-fetch-site": "same-origin",
"sec-fetch-user": "?1",
"upgrade-insecure-requests": "1",
},
)
df = pd.read_excel(r.content, engine="xlrd")
# print(df.iloc[:10])
df = df.iloc[6:]
df = df.dropna()
df["close"] = df["Unnamed: " + col]
df["date"] = pd.to_datetime(df["Unnamed: 0"])
df = df[["date", "close"]]
return df
def get_historical_frombb(code, start=None, end=None, **kws):
"""
https://www.bloomberg.com/ 数据源, 试验性支持。
似乎有很严格的 IP 封禁措施, 且最新数据更新滞后,且国内会被 reset,似乎难以支持 T-1 净值预测。强烈建议从英为或雅虎能找到的标的,不要用彭博源,该 API 只能作为 last resort。
:param code:
:param start:
:param end:
:param kws:
:return:
"""
if code.startswith("BB-"):
code = code[3:]
# end_obj = dt.datetime.strptime(end, "%Y%m%d")
start_obj = dt.datetime.strptime(start, "%Y%m%d")
fromnow = (today_obj() - start_obj).days
if fromnow < 20:
years = "1_MONTH"
elif fromnow < 300:
years = "1_YEAR"
else:
years = "5_YEAR"
url = "https://www.bloomberg.com/markets2/api/history/{code}/PX_LAST?\
timeframe={years}&period=daily&volumePeriod=daily".format(
years=years, code=code
)
r = rget_json(
url,
headers={
"user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_4) AppleWebKit/537.36 (KHTML, like Gecko)",
"referer": "https://www.bloomberg.com/quote/{code}".format(code=code),
"sec-fetch-dest": "empty",
"sec-fetch-mode": "cors",
"sec-fetch-site": "same-origin",
"accept": "*/*",
},
)
df = pd.DataFrame(r[0]["price"])
df["close"] = df["value"]
df["date"] = pd.to_datetime(df["dateTime"])
df = df[["date", "close"]]
return df
def get_historical_fromft(code, start, end, _type="indices"):
"""
finance times 数据
:param code:
:param start:
:param end:
:return:
"""
if not code.isdigit():
code = get_ft_id(code, _type=_type)
start = start.replace("/", "").replace("-", "")
end = end.replace("/", "").replace("-", "")
start = start[:4] + "/" + start[4:6] + "/" + start[6:]
end = end[:4] + "/" + end[4:6] + "/" + end[6:]
url = "https://markets.ft.com/data/equities/ajax/\
get-historical-prices?startDate={start}&endDate={end}&symbol={code}".format(
code=code, start=start, end=end
)
r = rget_json(url, headers={"user-agent": "Mozilla/5.0"})
b = BeautifulSoup(r["html"], "lxml")
data = {"date": [], "open": [], "close": [], "high": [], "low": []}
for i, td in enumerate(b.findAll("td")):
if i % 6 == 0:
s = td.find("span").string.split(",")[1:]
s = ",".join(s)
data["date"].append(dt.datetime.strptime(s, " %B %d, %Y"))
elif i % 6 == 1:
data["open"].append(_float(td.string))
elif i % 6 == 2:
data["high"].append(_float(td.string))
elif i % 6 == 3:
data["low"].append(_float(td.string))
elif i % 6 == 4:
data["close"].append(_float(td.string))
df = pd.DataFrame(data)
df = df.iloc[::-1]
return df
def get_historical_fromyh(code, start=None, end=None):
"""
雅虎财经数据源,支持数据丰富,不限于美股。但存在部分历史数据缺失 NAN 或者周末进入交易日的现象,可能数据需要进一步清洗和处理。
:param code:
:param start:
:param end:
:return:
"""
if code.startswith("YH-"):
code = code[3:]
start_obj = dt.datetime.strptime(start, "%Y%m%d")
fromnow = (today_obj() - start_obj).days
if fromnow < 20:
range_ = "1mo"
elif fromnow < 50:
range_ = "3mo"
elif fromnow < 150:
range_ = "6mo"
elif fromnow < 300:
range_ = "1y"
elif fromnow < 600:
range_ = "2y"
elif fromnow < 1500:
range_ = "5y"
else:
range_ = "10y"
url = "https://query1.finance.yahoo.com/v8\
/finance/chart/{code}?region=US&lang=en-US&includePrePost=false\
&interval=1d&range={range_}&corsDomain=finance.yahoo.com&.tsrc=finance".format(
code=code, range_=range_
)
# 该 API 似乎也支持起止时间选择参数,period1=1427500800&period2=1585353600
# 也可直接从历史数据页面爬取: https://finance.yahoo.com/quote/CSGOLD.SW/history?period1=1427500800&period2=1585353600&interval=1d&filter=history&frequency=1d
r = rget_json(url)
data = {}
datel = []
for t in r["chart"]["result"][0]["timestamp"]:
t = dt.datetime.fromtimestamp(t)
if t.second != 0:
t -= dt.timedelta(hours=8)
datel.append(t.replace(tzinfo=None, hour=0, minute=0, second=0, microsecond=0))
data["date"] = datel
for k in ["close", "open", "high", "low"]:
data[k] = r["chart"]["result"][0]["indicators"]["quote"][0][k]
df = pd.DataFrame(data)
return df
def get_historical_fromzzindex(code, start, end=None):
"""
中证指数源
:param code:
:param start:
:param end:
:return:
"""
if code.startswith("ZZ"):
code = code[2:]
start_obj = dt.datetime.strptime(start, "%Y%m%d")
fromnow = (today_obj() - start_obj).days
# if fromnow < 20:
# flag = "1%E4%B8%AA%E6%9C%88"
# elif fromnow < 60:
# flag = "3%E4%B8%AA%E6%9C%88" # 个月
# elif fromnow < 200:
# flag = "1%E5%B9%B4" # 年
# else:
# flag = "5%E5%B9%B4"
r = rget_json(
"https://www.csindex.com.cn/csindex-home/perf/index-perf?indexCode={code}&startDate={start}&endDate={end}".format(
code=code, start=start, end=end
),
headers={
"Host": "www.csindex.com.cn",
"Referer": "http://www.csindex.com.cn/",
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_4) AppleWebKit/537.36",
"X-Requested-With": "XMLHttpRequest",
"Accept": "application/json, text/javascript, */*; q=0.01",
},
)
df = pd.DataFrame(r["data"])
df["date"] = pd.to_datetime(df["tradeDate"])
df["close"] = df["close"].apply(_float)
return df[["date", "close"]]
def get_historical_fromgzindex(code, start, end):
"""
国证指数源
:param code:
:param start:
:param end:
:return:
"""
if code.startswith("GZ"):
code = code[2:]
start = start[:4] + "-" + start[4:6] + "-" + start[6:]
end = end[:4] + "-" + end[4:6] + "-" + end[6:]
params = {
"indexCode": code,
"startDate": start,
"endDate": end,
"frequency": "Day",
}
r = rget_json(
"http://hq.cnindex.com.cn/market/market/getIndexDailyDataWithDataFormat",
params=params,
)
df = pd.DataFrame(r["data"]["data"], columns=r["data"]["item"])
df["date"] = pd.to_datetime(df["timestamp"])
df = df[["date", "close", "open", "low", "high", "percent", "amount", "volume"]]
# TODO: 是否有这些列不全的国证指数?
df = df[::-1]
return df
def get_historical_fromhzindex(code, start, end):
"""
华证指数源
:param code:
:param start:
:param end:
:return:
"""
if code.startswith("HZ"):
code = code[2:]
r = rget_json(
"https://www.chindices.com/index/values.val?code={code}".format(code=code)
)
df = pd.DataFrame(r["data"])
df["date"] = pd.to_datetime(df["date"])
df = df[["date", "price", "pctChange"]]
df.rename(columns={"price": "close", "pctChange": "percent"}, inplace=True)
df = df[::-1]
return df
def get_historical_fromesunny(code, start=None, end=None):
"""
易盛商品指数
:param code: eg. ESCI000201
:param start: just placeholder
:param end: just placeholder
:return:
"""
# code
if code.startswith("ESCI"):
code = code[4:] + ".ESCI"
r = rget(
"https://www.esunny.com.cn/chartES/csv/shareday/day_易盛指数_{code}.es".format(
code=code
)
)
data = []
for l in r.text.split("\n"):
row = [s.strip() for s in l.split("|")] # 开 高 低 收 结
if len(row) > 1:
data.append(row[:7])
df = pd.DataFrame(
data, columns=["date", "open", "high", "low", "close", "settlement", "amount"]
)
df["date"] = pd.to_datetime(df["date"])
for c in ["open", "high", "low", "close", "settlement", "amount"]:
df[c] = df[c].apply(_float)
return df
def get_historical_fromycharts(code, start, end, category, metric):
params = {
"securities": "include:true,id:{code},,".format(code=code),
"calcs": "include:true,id:{metric},,".format(metric=metric),
"startDate": start, # %m/%d/%Y
"endDate": end, # %m/%d/%Y
"zoom": "custom",
}
r = rget_json(
"https://ycharts.com/charts/fund_data.json",
params=params,
headers={
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_4)\
AppleWebKit/537.36 (KHTML, like Gecko)",
"Host": "ycharts.com",
"X-Requested-With": "XMLHttpRequest",
"Referer": "https://ycharts.com/{category}/{code}/chart/".format(
category=category, code=code
),
"Sec-Fetch-Mode": "cors",
"Sec-Fetch-Site": "same-origin",
},
)
df = pd.DataFrame(
data=r["chart_data"][0][0]["raw_data"], columns=["timestamp", "close"]
)
df["date"] = (df["timestamp"]).apply(ts2pdts)
return df[["date", "close"]]
@lru_cache()
def get_bond_rates(rating, date=None):
"""
获取各评级企业债的不同久期的预期利率
:param rating: str. eg AAA, AA-, N for 中国国债
:param date: %Y-%m-%d
:return:
"""
rating = rating.strip()
rating_uid = {
"N": "2c9081e50a2f9606010a3068cae70001", # 国债
"AAA": "2c9081e50a2f9606010a309f4af50111",
"AAA-": "8a8b2ca045e879bf014607ebef677f8e",
"AA+": "2c908188138b62cd01139a2ee6b51e25",
"AA": "2c90818812b319130112c279222836c3",
"AA-": "8a8b2ca045e879bf014607f9982c7fc0",
"A+": "2c9081e91b55cc84011be40946ca0925",
"A": "2c9081e91e6a3313011e6d438a58000d",
"A-": "8a8b2ca04142df6a014148ca880f3046",
"A": "2c9081e91e6a3313011e6d438a58000d",
"BBB+": "2c9081e91ea160e5011eab1f116c1a59",
"BBB": "8a8b2ca0455847ac0145650780ad68fb",
"BB": "8a8b2ca0455847ac0145650ba23b68ff",
"B": "8a8b2ca0455847ac0145650c3d726901",
}
# 上边字典不全,非常欢迎贡献 :)
def _fetch(date):
r = rpost(
"https://yield.chinabond.com.cn/cbweb-mn/yc/searchYc?\
xyzSelect=txy&&workTimes={date}&&dxbj=0&&qxll=0,&&yqqxN=N&&yqqxK=K&&\
ycDefIds={uid}&&wrjxCBFlag=0&&locale=zh_CN".format(
uid=rating_uid.get(rating, rating), date=date
),
)
return r
if not date:
date = dt.datetime.today().strftime("%Y-%m-%d")
r = _fetch(date)
while len(r.text.strip()) < 20: # 当天没有数据,非交易日
date = last_onday(date).strftime("%Y-%m-%d")
r = _fetch(date)
l = r.json()[0]["seriesData"]
l = [t for t in l if t[1]]
df = pd.DataFrame(l, columns=["year", "rate"])
return df
def get_bond_rates_range(rating, duration=3, freq="W-FRI", start=None, end=None):
l = []
if rating.startswith("B-"):
rating = rating[2:]
rs = rating.split(".")
if len(rs) > 1:
duration = float(rs[1])
rating = rs[0]
for d in pd.date_range(start, end, freq=freq):
df = get_bond_rates(rating, d.strftime("%Y-%m-%d"))
l.append([d, df[df["year"] <= duration].iloc[-1]["rate"]])
return pd.DataFrame(l, columns=["date", "close"])
@data_source("jq")
def get_macro(table, start, end, datecol="stat_year"):
df = macro.run_query(
query(getattr(macro, table))
.filter(getattr(getattr(macro, table), datecol) >= start)
.filter(getattr(getattr(macro, table), datecol) <= end)
.order_by(getattr(getattr(macro, table), datecol))
)
df[datecol] = pd.to_datetime(df[datecol])
df["date"] = df[datecol]
return df
def set_handler(method="daily", f=None):
"""
为 ``get_daily``, ``get_bar`` 或 ``get_rt`` 设置 hook,优先按照函数 f 进行处理,若返回 None,再按一般情形处理
:param method: str. daily, rt, bar
:param f: func, default None.
:return: None
"""
setattr(thismodule, "get_" + method + "_handler", f)
def _get_daily(
code, start=None, end=None, prev=365, _from=None, wrapper=True, handler=True, **kws
):
"""
universal fetcher for daily historical data of literally everything has a value in market.
数据来源包括但不限于天天基金,雪球,英为财情,外汇局官网,聚宽,标普官网,bloomberg,雅虎财经,ycharts等。
:param code: str.
1. 对于沪深市场的股票,指数,ETF,LOF 场内基金,可转债和债券,直接使用其代码,主要开头需要包括 SH 或者 SZ。如果数字代码之后接 .A .B .N 分别代表后复权,前复权和不复权数据,不加后缀默认前复权。港股美股同理。
2. 对于香港市场的股票,指数,使用其数字代码,同时开头要添加 HK。
3. 对于美国市场的股票,指数,ETF 等,直接使用其字母缩写代码即可。
4. 对于人民币中间价数据,使用 "USD/CNY" 的形式,具体可能的值可在 http://www.chinamoney.com.cn/chinese/bkccpr/ 历史数据的横栏查询,注意日元需要用 100JPY/CNY.
5. 对于所有可以在 cn.investing.com 网站查到的金融产品,其代码可以是该网站对应的统一代码,或者是网址部分,比如 DAX 30 的概览页面为 https://cn.investing.com/indices/germany-30,那么对应代码即为 "indices/germany-30"。也可去网页 inspect 手动查找其内部代码(一般不需要自己做,推荐直接使用网页url作为 code 变量值),手动 inspect 加粗的实时价格,其对应的网页 span class 中的 pid 的数值即为内部代码。
6. 对于国内发行的基金,使用基金代码,同时开头添加 F。若想考虑分红使用累计净值,则开头添加 T。