/
toolbox.py
1952 lines (1761 loc) · 70.4 KB
/
toolbox.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 Object oriented toolbox which wrappers get_daily and some more
"""
import re
import sys
import datetime as dt
import numpy as np
import pandas as pd
from collections import deque
from functools import wraps, lru_cache
import logging
from scipy import stats
from bs4 import BeautifulSoup
from xalpha.cons import (
opendate,
yesterday,
next_onday,
last_onday,
scale_dict,
tz_bj,
holidays,
xnpv,
xirr,
rget,
rpost,
)
from xalpha.info import get_fund_holdings
from xalpha.universal import (
get_rt,
get_bar,
ttjjcode,
get_bond_rates,
_convert_code,
_inverse_convert_code,
fetch_backend,
save_backend,
)
import xalpha.universal as xu ## 为了 set_backend 可以动态改变此模块的 get_daily
from xalpha.exceptions import ParserFailure, DateMismatch, NonAccurate
thismodule = sys.modules[__name__]
logger = logging.getLogger(__name__)
def _set_holdings(module):
for name in [
"no_trading_days",
"holdings",
"currency_info",
"market_info",
"futures_info",
"alt_info",
"gap_info",
]:
setattr(thismodule, name, getattr(module, name, {}))
def set_holdings(module=None):
"""
导入外部 holdings.py 数据文件用来预测基金净值
:param module: mod. import holdings
:return: None.
"""
if not module:
try:
from xalpha import holdings
_set_holdings(holdings)
print("holdings.py is found and loaded within xalpha dir")
except ImportError:
# print("no holdings.py is found") # may cause confusing for general users
from xalpha import cons
_set_holdings(cons)
else:
_set_holdings(module)
print("external holdings.py is loaded")
set_holdings()
def _set_display_notebook():
"""
Initialize DataTable mode for pandas DataFrame represenation.
"""
from IPython.core.display import display, Javascript
display(
Javascript(
"""
require.config({
paths: {
DT: '//cdn.datatables.net/1.10.20/js/jquery.dataTables.min',
}
});
$('head').append('<link rel="stylesheet" type="text/css" href="//cdn.datatables.net/1.10.20/css/jquery.dataTables.min.css">');
$('head').append('<style> td, th {{text-align: center;}}</style>')
"""
)
)
def _repr_datatable_(self):
# create table DOM
script = f"$(element).html(`{self.to_html(index=False)}`);\n"
# execute jQuery to turn table into DataTable
script += """
require(["DT"], function(DT) {$(document).ready( () => {
// Turn existing table into datatable
$(element).find("table.dataframe").DataTable({'scrollX': '100%'});
})
});
"""
return script
pd.DataFrame._repr_javascript_ = _repr_datatable_
def set_display(env=""):
"""
开关 DataFrame 的显示模式,仅 Jupyter Notebook 有效。
:param env: str, default "". If env="notebook", pd.DataFrame will be shown in fantastic web language
:return:
"""
if not env:
try:
delattr(pd.DataFrame, "_repr_javascript_")
except AttributeError:
pass
elif env in ["notebook", "jupyter", "ipython"]:
_set_display_notebook()
else:
raise ParserFailure("unknown env %s" % env)
def PEBHistory(code, start=None, end=None, **kwargs):
"""
历史估值分析工具箱
:param code: str.
1. SH000***, SZ399***, 指数历史估值情况,第一原理计算,需要聚宽数据源
2. F******, 基金历史估值情况,根据股票持仓,第一原理计算
3. 8*****, 申万行业估值数据,需要聚宽数据源
4. 沪深港美股票代码,个股历史估值数据
:param start: str, %Y%m%d, 默认起点随着标的类型不同而不同
:param end: str, 仅限于 debug,强烈不建议设定,默认到昨天
:return: some object of PEBHistory class
"""
if code.startswith("SH000") or code.startswith("SZ399"):
return IndexPEBHistory(code, start, end, **kwargs)
elif code.startswith("F"):
return FundPEBHistory(code, start, end, **kwargs)
elif code.startswith("8"):
return SWPEBHistory(code, start, end, **kwargs)
else:
return StockPEBHistory(code, start, end, **kwargs)
class IndexPEBHistory:
"""
对于指数历史 PE PB 的封装类
"""
indexs = {
"000016.XSHG": ("上证50", "2012-01-01"),
"000300.XSHG": ("沪深300", "2012-01-01"),
"000905.XSHG": ("中证500", "2012-01-01"),
"000922.XSHG": ("中证红利", "2012-01-01"),
"000925.XSHG": ("基本面50", "2012-01-01"),
"399006.XSHE": ("创业板指", "2012-01-01"),
"000992.XSHG": ("全指金融", "2012-01-01"),
"000991.XSHG": ("全指医药", "2012-01-01"),
"399932.XSHE": ("中证消费", "2012-01-01"),
"000831.XSHG": ("500低波", "2013-01-01"),
"000827.XSHG": ("中证环保", "2013-01-01"),
"000978.XSHG": ("医药100", "2012-01-01"),
"399324.XSHE": ("深证红利", "2012-01-01"),
"399971.XSHE": ("中证传媒", "2014-07-01"),
"000807.XSHG": ("食品饮料", "2013-01-01"),
"000931.XSHG": ("中证可选", "2012-01-01"),
"399812.XSHE": ("养老产业", "2016-01-01"),
"000852.XSHG": ("中证1000", "2015-01-01"),
}
# 聚宽数据源支持的指数列表: https://www.joinquant.com/indexData
def __init__(self, code, start=None, end=None, **kwargs):
"""
:param code: str. 形式可以是 399971.XSHE 或者 SH000931
:param start: Optional[str]. %Y-%m-%d, 估值历史计算的起始日。
:param end: Dont use, only for debug
"""
yesterday_str = (dt.datetime.now() - dt.timedelta(days=1)).strftime("%Y-%m-%d")
if len(code.split(".")) == 2:
self.code = code
self.scode = _convert_code(code)
else:
self.scode = code
self.code = _inverse_convert_code(self.scode)
if self.code in self.indexs:
self.name = self.indexs[self.code][0]
if not start:
start = self.indexs[self.code][1]
else:
try:
self.name = get_rt(self.scode)["name"]
except:
self.name = self.scode
if not start:
start = "2012-01-01" # 可能会出问题,对应指数还未有数据
self.start = start
if not end:
end = yesterday_str
self.df = xu.get_daily("peb-" + self.scode, start=self.start, end=end, **kwargs)
self.ratio = None
self.title = "指数"
self._gen_percentile()
def _gen_percentile(self):
self.pep = [
round(i, 3) for i in np.nanpercentile(self.df.pe, np.arange(0, 110, 10))
]
try:
self.pbp = [
round(i, 3) for i in np.nanpercentile(self.df.pb, np.arange(0, 110, 10))
]
except TypeError:
df = self.df.fillna(1)
self.pbp = [
round(i, 3) for i in np.nanpercentile(df.pb, np.arange(0, 110, 10))
]
def percentile(self):
"""
打印 PE PB 的历史十分位对应值
:return:
"""
print("PE 历史分位:\n")
print(*zip(np.arange(0, 110, 10), self.pep), sep="\n")
print("\nPB 历史分位:\n")
print(*zip(np.arange(0, 110, 10), self.pbp), sep="\n")
def v(self, y="pe"):
"""
pe 或 pb 历史可视化
:param y: Optional[str]. "pe" (defualt) or "pb"
:return:
"""
return self.df.plot(x="date", y=y)
def fluctuation(self):
if not self.ratio:
d = self.df.iloc[-1]["date"]
oprice = xu.get_daily(
code=self.scode, end=d.strftime("%Y%m%d"), prev=20
).iloc[-1]["close"]
nprice = get_rt(self.scode)["current"]
self.ratio = nprice / oprice
return self.ratio
def current(self, y="pe"):
"""
返回实时的 pe 或 pb 绝对值估计。
:param y: Optional[str]. "pe" (defualt) or "pb"
:return: float.
"""
try:
return round(self.df.iloc[-1][y] * self.fluctuation(), 3)
except TypeError:
return np.nan
def current_percentile(self, y="pe"):
"""
返回实时的 pe 或 pb 历史百分位估计
:param y: Optional[str]. "pe" (defualt) or "pb"
:return: float.
"""
df = self.df
d = len(df)
u = len(df[df[y] < self.current(y)])
return round(u / d * 100, 2)
def summary(self, return_tuple=False):
"""
打印现在估值的全部分析信息。
:return:
"""
result = (
(
self.current("pe"),
self.current_percentile("pe"),
max(
round(
(self.current("pe") - self.pep[0]) / self.current("pe") * 100, 1
),
0,
),
),
(
self.current("pb"),
self.current_percentile("pb"),
max(
round(
(self.current("pb") - self.pbp[0]) / self.current("pb") * 100, 1
),
0,
),
),
)
print("%s%s估值情况\n" % (self.title, self.name))
# if dt.datetime.strptime(self.start, "%Y-%m-%d") > dt.datetime(2015, 1, 1):
# print("(历史数据较少,仅供参考)\n")
print("现在 PE 绝对值 %s, 相对分位 %s%%,距离最低点 %s %%\n" % result[0])
print("现在 PB 绝对值 %s, 相对分位 %s%%,距离最低点 %s %%\n" % result[1])
if return_tuple:
return result
class StockPEBHistory(IndexPEBHistory):
"""
个股历史估值封装
"""
def __init__(self, code, start=None, end=None, **kwargs):
"""
:param code: 801180 申万行业指数
:param start:
:param end:
"""
self.code = code
self.scode = code
if not end:
end = (dt.datetime.now() - dt.timedelta(days=1)).strftime("%Y-%m-%d")
if not start:
start = "2012-01-01"
self.start = start
self.df = xu.get_daily("peb-" + code, start=start, end=end, **kwargs)
self.name = get_rt(code)["name"]
self.ratio = 1
self.title = "个股"
self._gen_percentile()
class FundPEBHistory(IndexPEBHistory):
"""
基金历史估值封装
"""
def __init__(self, code, start=None, end=None, **kwargs):
self.code = code
self.scode = code
if not end:
end = (dt.datetime.now() - dt.timedelta(days=1)).strftime("%Y-%m-%d")
if not start:
start = "2016-01-01" # 基金历史通常比较短
self.start = start
self.df = xu.get_daily("peb-" + code, start=start, end=end, **kwargs)
self.name = get_rt(code)["name"]
self.title = "基金"
self.ratio = None
self._gen_percentile()
class SWPEBHistory(IndexPEBHistory):
"""
申万行业历史估值封装。
申万一级行业指数列表:
https://www.hysec.com/hyzq/hy/detail/detail.jsp?menu=4&classid=00000003001200130002&firClassid=000300120013&twoClassid=0003001200130002&threeClassid=0003001200130002&infoId=3046547
二三级行业指数也支持
"""
index1 = [
"801740",
"801020",
"801110",
"801200",
"801160",
"801010",
"801120",
"801230",
"801750",
"801050",
"801890",
"801170",
"801710",
"801130",
"801180",
"801760",
"801040",
"801780",
"801880",
"801140",
"801720",
"801080",
"801790",
"801030",
"801730",
"801210",
"801770",
"801150",
]
def __init__(self, code, start=None, end=None, **kwargs):
"""
:param code: 801180 申万行业指数
:param start:
:param end:
"""
self.code = code
self.scode = code
if not end:
end = (dt.datetime.now() - dt.timedelta(days=1)).strftime("%Y-%m-%d")
if not start:
start = "2012-01-01"
self.start = start
self.df = xu.get_daily("sw-" + code, start=start, end=end, **kwargs)
self.name = self.df.iloc[0]["name"]
self.ratio = 1
self.title = "申万行业指数"
self._gen_percentile()
class TEBHistory:
"""
指数总盈利和总净资产变化的分析工具箱
"""
def __init__(self, code, start=None, end=None, **kwargs):
"""
:param code: str. 指数代码,eg. SH000016
:param start:
:param end:
"""
df = xu.get_daily("teb-" + code, start=start, end=end, **kwargs)
df["e"] = pd.to_numeric(df["e"])
df["b"] = pd.to_numeric(df["b"])
df["lnb"] = df["b"].apply(lambda s: np.log(s))
df["lne"] = df["e"].apply(lambda s: np.log(s))
df["roe"] = df["e"] / df["b"] * 100
df["date_count"] = (df["date"] - df["date"].iloc[0]).apply(
lambda s: int(s.days)
)
self.df = df
self.fit(verbose=False)
def fit(self, verbose=True):
"""
fit exponential trying find annualized increase
:param verbose: if True (default), print debug info of linear regression
:return:
"""
df = self.df
slope_b, intercept_b, r_b, p_b, std_err_b = stats.linregress(
df["date_count"], df["lnb"]
)
slope_e, intercept_e, r_e, p_e, std_err_e = stats.linregress(
df["date_count"], df["lne"]
)
if verbose:
print("B fit", slope_b, intercept_b, r_b, p_b, std_err_b)
print("E fit", slope_e, intercept_e, r_e, p_e, std_err_e)
self.slope_b = slope_b
self.intercept_b = intercept_b
self.slope_e = slope_e
self.intercept_e = intercept_e
def result(self):
"""
:return: Dict[str, float]. 返回指数总净资产和净利润的年均增速
(拟合平滑意义,而非期末除以期初再开方,更好减少时间段两端极端情形的干扰)
"""
return {
"b_increase_percent": round((np.exp(365 * self.slope_b) - 1) * 100, 2),
"e_increase_percent": round((np.exp(365 * self.slope_e) - 1) * 100, 2),
}
def v(self, y="lne"):
"""
总资产或总利润与拟合曲线的可视化
:param y: str. one of lne, lnb, e, b, roe
:return:
"""
df = self.df
if y == "roe":
return df.plot(x="date", y="roe")
fitx = np.arange(0, df.iloc[-1]["date_count"], 10)
if y == "lne":
fity = self.intercept_e + self.slope_e * fitx
elif y == "lnb":
fity = self.intercept_b + self.slope_b * fitx
elif y == "e":
fity = np.exp(self.intercept_e + self.slope_e * fitx)
elif y == "b":
fity = np.exp(self.intercept_b + self.slope_b * fitx)
else:
raise ParserFailure("Unrecogized y %s" % y)
ax = df.plot(x="date_count", y=y)
ax.plot(fitx, fity)
return ax
class Compare:
"""
将不同金融产品同起点归一化比较
"""
def __init__(
self, *codes, start="20200101", end=yesterday(), col="close", normalize=True
):
"""
:param codes: Union[str, tuple], 格式与 :func:`xalpha.universal.get_daily` 相同,若需要汇率转换,需要用 tuple,第二个元素形如 "USD"
:param start: %Y%m%d
:param end: %Y%m%d, default yesterday
:param col: str, default close. The column to be compared.
:param normalize: bool, default True. 是否将对比价格按起点时间归一。
"""
totdf = pd.DataFrame()
codelist = []
for c in codes:
if isinstance(c, tuple):
code = c[0]
currency = c[1]
else:
code = c
currency = "CNY" # 标的不做汇率调整
codelist.append(code)
df = xu.get_daily(code, start=start, end=end)
df = df[df.date.isin(opendate)]
currency_code = _get_currency_code(currency)
if currency_code:
cdf = xu.get_daily(currency_code, start=start, end=end)
cdf = cdf[cdf["date"].isin(opendate)]
df = df.merge(right=cdf, on="date", suffixes=("_x", "_y"))
df[col] = df[col + "_x"] * df[col + "_y"]
if normalize:
df[code] = df[col] / df.iloc[0][col]
else:
df[code] = df[col]
df = df.reset_index()
df = df[["date", code]]
if "date" not in totdf.columns:
totdf = df
else:
totdf = totdf.merge(on="date", right=df)
self.totdf = totdf
self.codes = codelist
def v(self):
"""
显示日线可视化
:return:
"""
return self.totdf.plot(x="date", y=self.codes)
def corr(self):
"""
打印相关系数矩阵
:return: pd.DataFrame
"""
return self.totdf.iloc[:, 1:].pct_change().corr()
class OverPriced:
"""
ETF 或 LOF 历史折溢价情况分析
"""
def __init__(self, code, start=None, end=None, prev=None):
"""
:param code: str. eg SH501018, SZ160416
:param start: date range format is the same as xa.get_daily
:param end:
:param prev:
"""
self.code = code
df1 = xu.get_daily("F" + self.code[2:], start=start, end=end, prev=prev)
df2 = xu.get_daily(self.code, start=start, end=end, prev=prev)
df1 = df1.merge(df2, on="date", suffixes=("_F", "_" + code[:2]))
df1["diff_rate"] = (
(df1["close_" + code[:2]] - df1["close_F"]) / df1["close_F"] * 100
)
self.df = df1
def v(self, hline=None):
"""
:param hline: Union[float, List[float]], several horizental lines for assistance
:return:
"""
ax = self.df.plot(x="date", y="diff_rate")
if hline:
if isinstance(hline, float):
ax.axhline(hline, c="red")
else:
for h in hline:
ax.axhline(h, c="red")
return ax
#########################
# cb value estimation #
#########################
def BlackScholes(S, K, t, v, r=0.02, CallPutFlag="C"):
"""
BS option pricing calculator
:param S: current stock price
:param K: stricking price
:param t: Time until option exercise (years to maturity)
:param r: risk-free interest rate (by year)
:param v: Variance(volitility) of annual increase
:param CallPutFlag: "C" or "P", default call option
:return:
"""
# function modified from https://github.com/boyac/pyOptionPricing
def CND(X):
return stats.norm.cdf(X)
d1 = (np.log(S / K) + (r + (v ** 2) / 2) * t) / (v * np.sqrt(t))
d2 = d1 - v * np.sqrt(t)
if CallPutFlag in ["c", "C"]:
return S * CND(d1) - K * np.exp(-r * t) * CND(d2) # call option
elif CallPutFlag in ["p", "P"]:
return K * np.exp(-r * t) * CND(-d2) - S * CND(-d1) # put option
else:
raise ValueError("Unknown CallPutFlag %s" % CallPutFlag)
def cb_bond_value(issue_date, rlist, rate=0.03, date=None, tax=1.0):
"""
可转债债券价值计算器
:param issue_date: str. 发行日期
:param rlist: List[float], 每年度的利息百分点,比如 0.4,0.6等,最后加上最后返回的值(不含最后一年利息),比如 104
:param rate: float,现金流折算利率,应取同久期同信用等级的企业债利率,参考 https://yield.chinabond.com.cn/
:param date: 默认今天,计算债券价值基于的时间
:param tax: float,税率,1.0 表示不算税后,0.8 为计算税后利息,一般不需要设置成0.8,因为区别不大
:return:
"""
if rlist[-1] < 100:
logger.warning(
"the format of rlist must contain the final return more than 100 without interest of that year"
)
issue_date = issue_date.replace("-", "").replace("/", "")
issue_date_obj = dt.datetime.strptime(issue_date, "%Y%m%d")
if date is None:
date_obj = dt.datetime.today()
else:
date = date.replace("-", "").replace("/", "")
date_obj = dt.datetime.strptime(date, "%Y%m%d")
cf = [(date_obj, 0)]
passed = (date_obj - issue_date_obj).days // 365
for i, r in enumerate(rlist[:-1]):
if i >= passed:
cf.append((issue_date_obj + dt.timedelta(days=(i + 1) * 365), r * tax))
cf.append((issue_date_obj + dt.timedelta(days=(len(rlist) - 1) * 365), rlist[-1]))
return xnpv(rate, cf)
def cb_ytm(issue_date, rlist, cp, date=None, tax=1.0, guess=0.01):
"""
可转债到期收益率计算器
:param issue_date: 发行日期
:param rlist: 计息及赎回列表
:param cp: 可转债现价
:param date: 参考日期
:param tax: 计税 1 vs 0.8 税后 YTM
:param guess: YTM 估计初始值
:return:
"""
if rlist[-1] < 100:
logger.warning(
"the format of rlist must contain the final return more than 100 without interest of that year"
)
issue_date = issue_date.replace("-", "").replace("/", "")
issue_date_obj = dt.datetime.strptime(issue_date, "%Y%m%d")
if date is None:
date_obj = dt.datetime.today()
else:
date = date.replace("-", "").replace("/", "")
date_obj = dt.datetime.strptime(date, "%Y%m%d")
cf = [(date_obj, -cp)]
passed = (date_obj - issue_date_obj).days // 365
for i, r in enumerate(rlist[:-1]):
if i >= passed:
cf.append((issue_date_obj + dt.timedelta(days=(i + 1) * 365), r * tax))
# 关于赎回利息计算: https://www.jisilu.cn/?/question/339
# https://www.jisilu.cn/question/5807
# 富投网的算法:将最后一年超出100的部分,全部按照20%计税,
# 关于到期或回售部分的利息,最新进展: https://www.jisilu.cn/question/389264
cf.append((issue_date_obj + dt.timedelta(days=(len(rlist) - 1) * 365), rlist[-1]))
try:
return xirr(cf, guess=guess)
except RuntimeError:
return
class CBCalculator:
"""
可转债内在价值,简单计算器,期权价值与债券价值估算
"""
def __init__(
self,
code,
bondrate=None,
riskfreerate=None,
volatility=None,
name=None,
zgj=None,
):
"""
:param code: str. 转债代码,包含 SH 或 SZ 字头
:param bondrate: Optional[float]. 评估所用的债券折现率,默认使用中证企业债对应信用评级对应久期的利率
:param riskfreerate: Optioal[float]. 评估期权价值所用的无风险利率,默认使用国债对应久期的年利率。
:param volatility: Optional[float]. 正股波动性百分点,默认在一个范围浮动加上历史波动率的小幅修正。
:param name: str. 对于历史回测,可以直接提供 str,免得多次 get_rt 获取 name
:param zgj: float. 手动设置转股价,适用于想要考虑转股价调整因素进行历史估值的高阶用户
"""
# 应该注意到该模型除了当天外,其他时间估计会利用现在的转股价,对于以前下修过转股价的转债历史价值估计有问题
self.code = code
self.refbondrate = bondrate
self.bondrate = self.refbondrate
self.refriskfreerate = riskfreerate
self.riskfreerate = self.refriskfreerate
self.refvolatility = volatility
self.volatility = self.refvolatility
self.name = name
r = rget("https://www.jisilu.cn/data/convert_bond_detail/" + code[2:])
r.encoding = "utf-8"
b = BeautifulSoup(r.text, "lxml")
self.rlist = [
float(re.search(r"[\D]*([\d]*.?[\d]*)[\s]*[\%]", s).group(1))
for s in re.split("、|,", b.select("td[id=cpn_desc]")[0].string)
]
td_redeem_price = b.select("td[id=redeem_price]")[0]
if td_redeem_price.span:
redeem_price = float(
re.match(
r"\S+,合计到期赎回价(\d\d\d\.\d\d)元", td_redeem_price.span["title"]
).group(1)
)
logger.info(
"{}: redeem_price {} obtained from superscript".format(
code, redeem_price
)
)
else:
redeem_price = float(td_redeem_price.string)
self.rlist.append(redeem_price)
self.rlist[-1] -= self.rlist[-2] # 最后一年不含息返多少
stock_nm_div = b.find("div", class_="stock_nm")
self.scode = stock_nm_div.find("a", href=True)["href"].split("/")[-1]
# self.scode = (
# b.select("td[class=jisilu_nav]")[0].contents[1].text.split("-")[1].strip()
# )
self.scode = ttjjcode(self.scode) # 标准化股票代码
if not zgj:
self.zgj = float(b.select("td[id=convert_price]")[0].string) # 转股价
else:
self.zgj = zgj
self.rating = b.select("td[id=rating_cd]")[0].string.strip()
self.enddate = b.select("td[id=maturity_dt]")[0].string
self.zhanbi = b.select("td[id=convert_amt_ratio2]")[0].string.strip()
self.shares = float(b.select("td[id=curr_iss_amt]")[0].string.strip())
def process_byday(self, date=None):
if not date:
self.date_obj = dt.datetime.today()
else:
self.date_obj = dt.datetime.strptime(
date.replace("-", "").replace("/", ""), "%Y%m%d"
)
if not date:
rt = get_rt(self.code)
self.name = rt["name"]
self.cbp = rt["current"] # 转债价
self.stockp = get_rt(self.scode)["current"] # 股票价
else:
try:
if not self.name:
rt = get_rt(self.code)
self.name = rt["name"]
except:
self.name = "unknown"
df = xu.get_daily(self.code, prev=100, end=self.date_obj.strftime("%Y%m%d"))
self.cbp = df.iloc[-1]["close"]
df = xu.get_daily(
self.scode, prev=100, end=self.date_obj.strftime("%Y%m%d")
)
self.stockp = df.iloc[-1]["close"]
df = xu.get_daily(self.scode, prev=360, end=self.date_obj.strftime("%Y%m%d"))
self.history_volatility = np.std(
np.log(df["close"] / df.shift(1)["close"])
) * np.sqrt(244)
if not self.refvolatility:
self.volatility = 0.17
if self.rating in ["A-", "A", "A+"] or self.rating.startswith("B"):
self.volatility = 0.25
elif self.rating in ["AA-"]:
self.volatility = 0.2
elif self.rating in ["AA"]:
self.volatility = 0.19
elif self.rating in ["AA+"]:
self.volatility = 0.18
if self.history_volatility < 0.2:
self.volatility -= 0.01
elif self.history_volatility > 0.7:
self.volatility += 0.05
elif self.history_volatility > 0.6:
self.volatility += 0.035
elif self.history_volatility > 0.5:
self.volatility += 0.02
elif self.history_volatility > 0.4:
self.volatility += 0.01
self.years = len(self.rlist) - 1
syear = int(self.enddate.split("-")[0]) - self.years
self.issuedate = str(syear) + self.enddate[4:]
self.days = (
dt.datetime.strptime(self.enddate, "%Y-%m-%d") - self.date_obj
).days
if not self.refbondrate:
ratestable = get_bond_rates(self.rating, self.date_obj.strftime("%Y-%m-%d"))
if self.rating in ["A", "A+", "AA-"] or self.rating.startswith("B"):
## AA 到 AA- 似乎是利率跳高的一个坎
cutoff = 3 # changed from 2 by considering more credit risk
else:
cutoff = 4
if self.days / 365 > cutoff:
# 过长久期的到期收益率,容易造成估值偏离,虽然理论上是对的
# 考虑到国内可转债市场信用风险较低,不应过分低估低信用债的债券价值
self.bondrate = (
ratestable[ratestable["year"] <= cutoff].iloc[-1]["rate"] / 100
)
else:
self.bondrate = (
ratestable[ratestable["year"] >= self.days / 365].iloc[0]["rate"]
/ 100
)
if not self.refriskfreerate:
ratestable = get_bond_rates("N", self.date_obj.strftime("%Y-%m-%d"))
if self.days / 365 > 5:
self.riskfreerate = (
ratestable[ratestable["year"] <= 5].iloc[-1]["rate"] / 100
)
else:
self.riskfreerate = (
ratestable[ratestable["year"] >= self.days / 365].iloc[0]["rate"]
/ 100
)
def analyse(self, date=None):
self.process_byday(date=date)
d = {
"stockcode": self.scode,
"cbcode": self.code,
"name": self.name,
"enddate": self.enddate,
"interest": self.rlist,
"zgj": self.zgj,
"stockprice": self.stockp,
"cbprice": self.cbp,
"rating": self.rating,
"bondrate": self.bondrate,
"predicted_volatility": self.volatility,
"historical_volatility": self.history_volatility,
"riskfreerate": self.riskfreerate,
"years": self.days / 365,
"issuedate": self.issuedate,
"date": self.date_obj.strftime("%Y-%m-%d"),
"zhanbi": self.zhanbi,
"remaining": self.shares,
}
d["bond_value"] = cb_bond_value(self.issuedate, self.rlist, self.bondrate)
d["ytm_wo_tax"] = cb_ytm(self.issuedate, self.rlist, self.cbp)
d["ytm_wi_tax"] = cb_ytm(self.issuedate, self.rlist, self.cbp, tax=0.8)
d["option_value"] = (
BlackScholes(
self.stockp,
self.zgj,
self.days / 365,
self.volatility,
self.riskfreerate,
CallPutFlag="C",
)
* 100
/ self.zgj
)
# 经验上看,下修强赎回售及美式期权行为等其他带来的期权价值大约有1到4元的增益:
# 以0.015 为无风险利率和 0.15-0.18 为波动率估计范围的情形下
# 实在没有必要为了这几块钱上复杂工具估值,因为无风险利率几十个bp的改变,就足以导致更大的波动,看个热闹就行了
# 可转债估值只能是模糊的正确
d["tot_value"] = d["bond_value"] + d["option_value"]
d["premium"] = (self.cbp / d["tot_value"] - 1) * 100
return d
#########################
# netvalue prediction #
#########################
@lru_cache(maxsize=512)
def get_currency(code):
"""
通过代码获取计价货币的函数
:param code:
:return:
"""
# 强制需要自带 cache,否则在回测 table 时,info 里没有的代码将很灾难。。。
# only works for HKD JPY USD GBP CNY EUR, not very general when data source gets diverse more
try:
if code in currency_info:
return currency_info[code]
elif (code.startswith("F") or code.startswith("M")) and code[1:].isdigit():
return "CNY"
elif code.startswith("FT-") and len(code.split(":")) > 2:
# be careful! FT-ABC:IOM has no currency information!
return code.split(":")[-1]
elif code.startswith("HK") and code[2:].isdigit():
return "HKD"
currency = get_rt(code)["currency"]
if currency is None:
currency = "CNY"
elif currency == "JPY":
currency = "100JPY"
except (TypeError, AttributeError, ValueError):
logger.warning("set currency of %s as default CNY" % code)
currency = "CNY"
return currency
def _get_currency_code(c):
if c == "CNY":
return # None
if c == "JPY":
return "100JPY/CNY"
zjjl = [
"USD",
"EUR",
"100JPY",
"HKD",
"GBP",
"AUD",
"NZD",
"SGD",
"CHF",
"CAD",
"MYR",
"RUB",
"ZAR",
"KRW",
"AED",
"SAR",
"HUF",
"PLN",
"DKK",
"SEK",
"NOK",
"TRY",
"MXN",
"THB",