siat 3.10.132__py3-none-any.whl → 3.10.133__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (218) hide show
  1. siat/__init__.py +0 -0
  2. siat/allin.py +0 -0
  3. siat/assets_liquidity.py +0 -0
  4. siat/beta_adjustment.py +0 -0
  5. siat/beta_adjustment_china.py +0 -0
  6. siat/blockchain.py +0 -0
  7. siat/bond.py +0 -0
  8. siat/bond_base.py +0 -0
  9. siat/bond_china.py +0 -0
  10. siat/bond_zh_sina.py +0 -0
  11. siat/capm_beta.py +0 -0
  12. siat/capm_beta2.py +0 -0
  13. siat/compare_cross.py +0 -0
  14. siat/copyrights.py +0 -0
  15. siat/cryptocurrency.py +0 -0
  16. siat/economy.py +0 -0
  17. siat/economy2.py +0 -0
  18. siat/esg.py +0 -0
  19. siat/event_study.py +0 -0
  20. siat/exchange_bond_china.pickle +0 -0
  21. siat/fama_french.py +0 -0
  22. siat/fin_stmt2_yahoo.py +0 -0
  23. siat/financial_base.py +0 -0
  24. siat/financial_statements.py +0 -0
  25. siat/financials.py +0 -0
  26. siat/financials2.py +0 -0
  27. siat/financials_china.py +0 -0
  28. siat/financials_china2.py +0 -0
  29. siat/fund.py +0 -0
  30. siat/fund_china.pickle +0 -0
  31. siat/fund_china.py +0 -0
  32. siat/future_china.py +0 -0
  33. siat/google_authenticator.py +0 -0
  34. siat/grafix.py +0 -0
  35. siat/holding_risk.py +0 -0
  36. siat/luchy_draw.py +0 -0
  37. siat/market_china.py +0 -0
  38. siat/markowitz.py +0 -0
  39. siat/markowitz2.py +0 -0
  40. siat/markowitz2_20250704.py +0 -0
  41. siat/markowitz2_20250705.py +0 -0
  42. siat/markowitz_simple.py +0 -0
  43. siat/ml_cases.py +0 -0
  44. siat/ml_cases_example.py +0 -0
  45. siat/option_china.py +0 -0
  46. siat/option_pricing.py +0 -0
  47. siat/other_indexes.py +0 -0
  48. siat/risk_adjusted_return.py +0 -0
  49. siat/risk_adjusted_return2.py +0 -0
  50. siat/risk_evaluation.py +0 -0
  51. siat/risk_free_rate.py +0 -0
  52. siat/sector_china.py +0 -0
  53. siat/security_price2.py +0 -0
  54. siat/security_prices.py +40 -2
  55. siat/security_trend.py +0 -0
  56. siat/security_trend2.py +0 -0
  57. siat/stock.py +0 -0
  58. siat/stock_advice_linear.py +0 -0
  59. siat/stock_base.py +0 -0
  60. siat/stock_china.py +0 -0
  61. siat/stock_info.pickle +0 -0
  62. siat/stock_prices_kneighbors.py +0 -0
  63. siat/stock_prices_linear.py +0 -0
  64. siat/stock_profile.py +0 -0
  65. siat/stock_technical.py +0 -0
  66. siat/stooq.py +0 -0
  67. siat/transaction.py +0 -0
  68. siat/translate.py +0 -0
  69. siat/valuation.py +0 -0
  70. siat/valuation_china.py +0 -0
  71. siat/var_model_validation.py +0 -0
  72. siat/yf_name.py +0 -0
  73. {siat-3.10.132.dist-info/licenses → siat-3.10.133.dist-info}/LICENSE +0 -0
  74. {siat-3.10.132.dist-info → siat-3.10.133.dist-info}/METADATA +232 -235
  75. siat-3.10.133.dist-info/RECORD +78 -0
  76. {siat-3.10.132.dist-info → siat-3.10.133.dist-info}/WHEEL +1 -1
  77. {siat-3.10.132.dist-info → siat-3.10.133.dist-info}/top_level.txt +0 -1
  78. build/lib/build/lib/siat/__init__.py +0 -75
  79. build/lib/build/lib/siat/allin.py +0 -137
  80. build/lib/build/lib/siat/assets_liquidity.py +0 -915
  81. build/lib/build/lib/siat/beta_adjustment.py +0 -1058
  82. build/lib/build/lib/siat/beta_adjustment_china.py +0 -548
  83. build/lib/build/lib/siat/blockchain.py +0 -143
  84. build/lib/build/lib/siat/bond.py +0 -2900
  85. build/lib/build/lib/siat/bond_base.py +0 -992
  86. build/lib/build/lib/siat/bond_china.py +0 -100
  87. build/lib/build/lib/siat/bond_zh_sina.py +0 -143
  88. build/lib/build/lib/siat/capm_beta.py +0 -783
  89. build/lib/build/lib/siat/capm_beta2.py +0 -887
  90. build/lib/build/lib/siat/common.py +0 -5360
  91. build/lib/build/lib/siat/compare_cross.py +0 -642
  92. build/lib/build/lib/siat/copyrights.py +0 -18
  93. build/lib/build/lib/siat/cryptocurrency.py +0 -667
  94. build/lib/build/lib/siat/economy.py +0 -1471
  95. build/lib/build/lib/siat/economy2.py +0 -1853
  96. build/lib/build/lib/siat/esg.py +0 -536
  97. build/lib/build/lib/siat/event_study.py +0 -815
  98. build/lib/build/lib/siat/fama_french.py +0 -1521
  99. build/lib/build/lib/siat/fin_stmt2_yahoo.py +0 -982
  100. build/lib/build/lib/siat/financial_base.py +0 -1160
  101. build/lib/build/lib/siat/financial_statements.py +0 -598
  102. build/lib/build/lib/siat/financials.py +0 -2339
  103. build/lib/build/lib/siat/financials2.py +0 -1278
  104. build/lib/build/lib/siat/financials_china.py +0 -4433
  105. build/lib/build/lib/siat/financials_china2.py +0 -2212
  106. build/lib/build/lib/siat/fund.py +0 -629
  107. build/lib/build/lib/siat/fund_china.py +0 -3307
  108. build/lib/build/lib/siat/future_china.py +0 -551
  109. build/lib/build/lib/siat/google_authenticator.py +0 -47
  110. build/lib/build/lib/siat/grafix.py +0 -3636
  111. build/lib/build/lib/siat/holding_risk.py +0 -867
  112. build/lib/build/lib/siat/luchy_draw.py +0 -638
  113. build/lib/build/lib/siat/market_china.py +0 -1168
  114. build/lib/build/lib/siat/markowitz.py +0 -2363
  115. build/lib/build/lib/siat/markowitz2.py +0 -3150
  116. build/lib/build/lib/siat/markowitz2_20250704.py +0 -2969
  117. build/lib/build/lib/siat/markowitz2_20250705.py +0 -3158
  118. build/lib/build/lib/siat/markowitz_simple.py +0 -373
  119. build/lib/build/lib/siat/ml_cases.py +0 -2291
  120. build/lib/build/lib/siat/ml_cases_example.py +0 -60
  121. build/lib/build/lib/siat/option_china.py +0 -3069
  122. build/lib/build/lib/siat/option_pricing.py +0 -1925
  123. build/lib/build/lib/siat/other_indexes.py +0 -409
  124. build/lib/build/lib/siat/risk_adjusted_return.py +0 -1576
  125. build/lib/build/lib/siat/risk_adjusted_return2.py +0 -1900
  126. build/lib/build/lib/siat/risk_evaluation.py +0 -2218
  127. build/lib/build/lib/siat/risk_free_rate.py +0 -351
  128. build/lib/build/lib/siat/sector_china.py +0 -4140
  129. build/lib/build/lib/siat/security_price2.py +0 -727
  130. build/lib/build/lib/siat/security_prices.py +0 -3408
  131. build/lib/build/lib/siat/security_trend.py +0 -402
  132. build/lib/build/lib/siat/security_trend2.py +0 -646
  133. build/lib/build/lib/siat/stock.py +0 -4284
  134. build/lib/build/lib/siat/stock_advice_linear.py +0 -934
  135. build/lib/build/lib/siat/stock_base.py +0 -26
  136. build/lib/build/lib/siat/stock_china.py +0 -2095
  137. build/lib/build/lib/siat/stock_prices_kneighbors.py +0 -910
  138. build/lib/build/lib/siat/stock_prices_linear.py +0 -386
  139. build/lib/build/lib/siat/stock_profile.py +0 -707
  140. build/lib/build/lib/siat/stock_technical.py +0 -3305
  141. build/lib/build/lib/siat/stooq.py +0 -74
  142. build/lib/build/lib/siat/transaction.py +0 -347
  143. build/lib/build/lib/siat/translate.py +0 -5183
  144. build/lib/build/lib/siat/valuation.py +0 -1378
  145. build/lib/build/lib/siat/valuation_china.py +0 -2076
  146. build/lib/build/lib/siat/var_model_validation.py +0 -444
  147. build/lib/build/lib/siat/yf_name.py +0 -811
  148. build/lib/siat/__init__.py +0 -75
  149. build/lib/siat/allin.py +0 -137
  150. build/lib/siat/assets_liquidity.py +0 -915
  151. build/lib/siat/beta_adjustment.py +0 -1058
  152. build/lib/siat/beta_adjustment_china.py +0 -548
  153. build/lib/siat/blockchain.py +0 -143
  154. build/lib/siat/bond.py +0 -2900
  155. build/lib/siat/bond_base.py +0 -992
  156. build/lib/siat/bond_china.py +0 -100
  157. build/lib/siat/bond_zh_sina.py +0 -143
  158. build/lib/siat/capm_beta.py +0 -783
  159. build/lib/siat/capm_beta2.py +0 -887
  160. build/lib/siat/common.py +0 -5360
  161. build/lib/siat/compare_cross.py +0 -642
  162. build/lib/siat/copyrights.py +0 -18
  163. build/lib/siat/cryptocurrency.py +0 -667
  164. build/lib/siat/economy.py +0 -1471
  165. build/lib/siat/economy2.py +0 -1853
  166. build/lib/siat/esg.py +0 -536
  167. build/lib/siat/event_study.py +0 -815
  168. build/lib/siat/fama_french.py +0 -1521
  169. build/lib/siat/fin_stmt2_yahoo.py +0 -982
  170. build/lib/siat/financial_base.py +0 -1160
  171. build/lib/siat/financial_statements.py +0 -598
  172. build/lib/siat/financials.py +0 -2339
  173. build/lib/siat/financials2.py +0 -1278
  174. build/lib/siat/financials_china.py +0 -4433
  175. build/lib/siat/financials_china2.py +0 -2212
  176. build/lib/siat/fund.py +0 -629
  177. build/lib/siat/fund_china.py +0 -3307
  178. build/lib/siat/future_china.py +0 -551
  179. build/lib/siat/google_authenticator.py +0 -47
  180. build/lib/siat/grafix.py +0 -3636
  181. build/lib/siat/holding_risk.py +0 -867
  182. build/lib/siat/luchy_draw.py +0 -638
  183. build/lib/siat/market_china.py +0 -1168
  184. build/lib/siat/markowitz.py +0 -2363
  185. build/lib/siat/markowitz2.py +0 -3150
  186. build/lib/siat/markowitz2_20250704.py +0 -2969
  187. build/lib/siat/markowitz2_20250705.py +0 -3158
  188. build/lib/siat/markowitz_simple.py +0 -373
  189. build/lib/siat/ml_cases.py +0 -2291
  190. build/lib/siat/ml_cases_example.py +0 -60
  191. build/lib/siat/option_china.py +0 -3069
  192. build/lib/siat/option_pricing.py +0 -1925
  193. build/lib/siat/other_indexes.py +0 -409
  194. build/lib/siat/risk_adjusted_return.py +0 -1576
  195. build/lib/siat/risk_adjusted_return2.py +0 -1900
  196. build/lib/siat/risk_evaluation.py +0 -2218
  197. build/lib/siat/risk_free_rate.py +0 -351
  198. build/lib/siat/sector_china.py +0 -4140
  199. build/lib/siat/security_price2.py +0 -727
  200. build/lib/siat/security_prices.py +0 -3408
  201. build/lib/siat/security_trend.py +0 -402
  202. build/lib/siat/security_trend2.py +0 -646
  203. build/lib/siat/stock.py +0 -4284
  204. build/lib/siat/stock_advice_linear.py +0 -934
  205. build/lib/siat/stock_base.py +0 -26
  206. build/lib/siat/stock_china.py +0 -2095
  207. build/lib/siat/stock_prices_kneighbors.py +0 -910
  208. build/lib/siat/stock_prices_linear.py +0 -386
  209. build/lib/siat/stock_profile.py +0 -707
  210. build/lib/siat/stock_technical.py +0 -3305
  211. build/lib/siat/stooq.py +0 -74
  212. build/lib/siat/transaction.py +0 -347
  213. build/lib/siat/translate.py +0 -5183
  214. build/lib/siat/valuation.py +0 -1378
  215. build/lib/siat/valuation_china.py +0 -2076
  216. build/lib/siat/var_model_validation.py +0 -444
  217. build/lib/siat/yf_name.py +0 -811
  218. siat-3.10.132.dist-info/RECORD +0 -218
@@ -1,444 +0,0 @@
1
- # -*- coding: utf-8 -*-
2
- """
3
- 本模块功能:检验VaR(在险价值)模型计算结果的有效性
4
- 所属工具包:证券投资分析工具SIAT
5
- SIAT:Security Investment Analysis Tool
6
- 创建日期:2019年7月16日
7
- 最新修订日期:2019年8月19日
8
- 作者:王德宏 (WANG Dehong, Peter)
9
- 作者单位:北京外国语大学国际商学院
10
- 作者邮件:wdehong2000@163.com
11
- 版权所有:王德宏
12
- 用途限制:仅限研究与教学使用,不可商用!商用需要额外授权。
13
- 特别声明:作者不对使用本工具进行证券投资导致的任何损益负责!
14
- """
15
-
16
- #==============================================================================
17
- #统一屏蔽一般性警告
18
- import warnings; warnings.filterwarnings("ignore")
19
- from siat.common import *
20
- from siat.translate import *
21
- from siat.security_prices import *
22
- from siat.security_price2 import *
23
- #==============================================================================
24
- #==============================================================================
25
- def calc_ret(price_series,groupsize=1):
26
- """
27
- 功能:计算日收益率,根据分组大小,计算组内累计收益率
28
- 输入参数:价格序列数据框,分组大小(默认为1,即不分组)
29
- 输出:带分组的收益率序列,数据框
30
- """
31
-
32
- #仅用于测试
33
- #price_series=get_price(['AAPL'],[1],'2019-1-1','2019-8-18')
34
- #groupsize=3
35
-
36
- #计算日收益率
37
- import pandas as pd
38
- #rets=pd.DataFrame(price_series['Value'].pct_change())
39
- rets=pd.DataFrame(price_series['Close'].pct_change())
40
-
41
- import numpy as np
42
- if groupsize >1:
43
- group=np.arange(1,groupsize)
44
- colname=rets.columns.to_list()[0]
45
- for i in group:
46
- #print(i)
47
- newcol="Shift"+i.astype('str')
48
- rets[newcol]=rets[colname].shift(i)
49
- rets=rets.dropna()
50
- rets['Ret']=rets.apply(lambda row:np.product(1+row),axis=1)-1
51
-
52
- #ret_group=pd.DataFrame(rets['Ret'])
53
- ret_group=rets['Ret']
54
- return ret_group
55
-
56
-
57
- if __name__ =="__main__":
58
- p=get_prices_portfolio(['AAPL','MSFT'],[1,1],'2019-1-1','2019-8-18')
59
- rg=calc_ret(p,5)
60
-
61
-
62
- #==============================================================================
63
- def VaR_normal_standard(position,ret_series,future_days=1,alpha=0.99):
64
-
65
- """
66
- 标准正太法VaR基本算法
67
- 输入参数:当前持有头寸金额,收益率序列(非百分比),未来持有时间(天),置信度
68
- 输出参数:VaR(金额,单位与当前头寸的金额单位相同),负数
69
- """
70
- import numpy as np
71
- from scipy import stats
72
-
73
- #注意:这里z为负数
74
- z=stats.norm.ppf(1-alpha)
75
- miu_daily=np.mean(ret_series)
76
- #print("DEBUG: miu_daily",miu_daily)
77
- miu_days=np.power(miu_daily+1,future_days)-1
78
- sigma_daily=np.std(ret_series)
79
- #print("DEBUG: sigma_daily",sigma_daily)
80
- sigma_days=np.sqrt(future_days)*sigma_daily
81
-
82
- ratio=miu_days+z*sigma_days
83
- #print("DEBUG: ratio",ratio)
84
- #损失份额最多100%全损
85
- if np.abs(ratio) > 1.0: ratio=-1.0
86
- VaR_days=position*ratio
87
- return -abs(VaR_days)
88
-
89
-
90
- if __name__ == "__main__":
91
- price=get_prices_portfolio(['AAPL'],[1],'2019-1-1','2019-8-8')
92
- position=price['Close'][-1]
93
- ret=calc_ret(price)
94
- VaR=VaR_normal_standard(position,ret)
95
- #==============================================================================
96
- def VaR_normal_modified(position,ret_series,future_days=1,alpha=0.99):
97
- """
98
- 功能:VaR基本算法,修正正态法
99
- #输入参数:持有头寸金额,日收益率序列,未来持有日期,置信度
100
- #输出参数:VaR(金额)
101
- """
102
- from scipy import stats
103
- import numpy as np
104
-
105
- z=np.abs(stats.norm.ppf(1-alpha))
106
- S=stats.skew(ret_series)
107
- K=stats.kurtosis(ret_series)
108
-
109
- t1=1/6*(np.power(z,2)-1)*S
110
- t2=1/24*(np.power(z,3)-3*z)*K
111
- t3=1/36*(2*np.power(z,3)-5*z)*np.power(S,2)
112
- t=z+t1+t2-t3
113
-
114
- miu_daily=np.mean(ret_series)
115
- miu_days=np.power(miu_daily+1,future_days)-1
116
- sigma_daily=np.std(ret_series)
117
- sigma_days=np.sqrt(future_days)*sigma_daily
118
-
119
- #最多100%全损
120
- ratio=miu_days+t*sigma_days
121
- if np.abs(ratio) > 1.0: ratio=-1.0
122
- VaR_days=position*ratio
123
- return -abs(VaR_days)
124
- #==============================================================================
125
- def VaR_historical_1d(position,ret_series,alpha=0.99):
126
- """
127
- 功能:计算VaR基本算法,历史模拟法,持有1天
128
- 输入参数:持有头寸金额,历史日收益率序列,置信度
129
- 输出:持有一天的VaR(金额)
130
- """
131
- import numpy as np
132
- n=len(ret_series)
133
- t=int(n*(1-alpha))
134
- SR=np.sort(ret_series)
135
- A=SR[t-1] #SR的第一个元素的序号是0
136
- VaR_1d=position*A
137
- return -abs(VaR_1d)
138
- #==============================================================================
139
- def VaR_montecarlo(position,ret_series, \
140
- future_days=1,alpha=0.99,random=10000):
141
- """
142
- 功能:计算VaR基本算法,蒙特卡洛模拟法,持有多日
143
- 输入参数:当前头寸金额,历史日收益率序列,未来持有天数,置信度,重复模拟次数
144
- 注:重复模拟次数越多,准确率就越高,但耗时也越多
145
- 输出:持有多天的VaR(金额)
146
- """
147
- import numpy as np
148
- #取得历史日收益率的均值和标准差
149
- miu=np.mean(ret_series)
150
- sigma=np.std(ret_series)
151
- #生成随机数序列
152
- np.random.seed(12345)
153
- #按照历史日收益率的均值和标准差重复模拟一定次数,生成新的日收益率序列
154
- RR=np.random.normal(miu,sigma,random)
155
- #基于新的日收益率序列,使用标准正态法计算VaR
156
- VaR_days=VaR_normal_standard(position,RR,future_days,alpha)
157
-
158
- #最多100%全损
159
- if abs(VaR_days) > position: VaR_days=-position
160
-
161
- return -abs(VaR_days)
162
- #==============================================================================
163
- def calc_VaR_1d(position,ret_series,alpha=0.99,model="montecarlo", \
164
- random=10000):
165
- """
166
- 功能:计算一个期间的VaR,允许指定不同的模型
167
- 输入参数:当前头寸,各个期间的收益率序列,置信度,模型,模拟次数(仅适用于蒙特卡洛模型)
168
- 输出:VaR金额
169
- """
170
-
171
- future_days=1
172
- #判断模型选择
173
- modeltype=model.lower()
174
- if modeltype in ['normal_standard','normal standard','ns']:
175
- #标准正态法
176
- mtype='normal_standard'
177
- VaR=VaR_normal_standard(position,ret_series,future_days,alpha)
178
- elif modeltype in ['normal_modified','normal modified','nm']:
179
- #修正正态法
180
- mtype='normal_modified'
181
- VaR=VaR_normal_modified(position,ret_series,future_days,alpha)
182
- elif modeltype in ['historical','historic','history','hist']:
183
- #历史模拟法
184
- mtype='historical'
185
- VaR=VaR_historical_1d(position,ret_series,alpha)
186
- elif modeltype in ['montecarlo','monte carlo','monte_carlo','mc']:
187
- #蒙特卡洛模拟法
188
- mtype='montecarlo'
189
- VaR=VaR_montecarlo(position,ret_series,future_days,alpha,random)
190
- else:
191
- print("Error #1(calc_VaR_1d): Type of model unsupported")
192
- print("Variable(s):",model)
193
- print("Models supported: normal_standard, normal_modificed, historical, montecarlo")
194
- return None
195
-
196
- return mtype,VaR
197
-
198
-
199
- if __name__ == "__main__":
200
- tickerlist=['AAPL','MSFT']
201
- sharelist=[1,2]
202
- start='2019-1-1'
203
- end='2019-6-30'
204
- price=get_prices_portfolio(tickerlist,sharelist,start,end)
205
-
206
- groupsize=5
207
- ret=calc_ret(price,groupsize)
208
-
209
- position=price['Close'][-1]
210
- alpha=0.99
211
- type,VaR=calc_VaR_1d(position,ret,alpha,model="montecarlo")
212
- ratio=abs(VaR/position)
213
-
214
- threshhold_expected=round(len(ret)*(1-alpha),2)
215
- threshhold_actual=len(ret[ret['Ret']<-ratio])
216
-
217
-
218
- #==============================================================================
219
-
220
-
221
-
222
- def backtest_VaR(tickerlist,sharelist,today,future_days=1, \
223
- alpha=0.99,pastyears=1,model="montecarlo",random=10000):
224
- """
225
- 功能:检验VaR模型的有效性,历史回溯测试
226
- 输入参数:股票代码列表,持有股数列表,当前日期,预期持有天数,置信度,
227
- 使用历史书据的年数,模型类型,模拟次数(仅适用于蒙特卡洛法)
228
- """
229
-
230
- #检查当前日期的合理性
231
- if not check_date(today): return
232
-
233
- #计算开始日期
234
- startdate=get_start_date(today,pastyears)
235
- import pandas as pd
236
- enddate=pd.to_datetime(today)
237
-
238
- #下载股价数据
239
- price=get_prices_portfolio(tickerlist,sharelist,startdate,enddate)
240
- #计算收益率,以future_days作为分组大小
241
- ret=calc_ret(price,future_days)
242
-
243
- #计算当前持有的头寸
244
- position=price['Close'][-1]
245
- #计算VaR
246
- type,VaR=calc_VaR_1d(position,ret,alpha,model)
247
- #计算VaR比率
248
- ratio=abs(VaR/position)
249
-
250
- #预期:收益率低于VaR比率的期数(天数或组数)
251
- threshhold_expected=round(len(ret)*(1-alpha),2)
252
- #实际:收益率低于VaR比率的期数(天数或组数)
253
- threshhold_actual=len(ret[ret<-ratio])
254
- alpha_actual=1-threshhold_actual/len(ret)
255
-
256
- #结果判读
257
- if abs(alpha_actual-alpha) < 0.001:
258
- result="准确"
259
- elif alpha_actual < alpha:
260
- result="低估"
261
- else:
262
- result="高估"
263
-
264
- #打印结果
265
- """
266
- print("\n======= VaR模型:回溯测试 =======")
267
- #print("投资组合 :",ticker_name(tickerlist))
268
- print("投资组合 :",end='')
269
- print_list(ticker_name(tickerlist,'bond'))
270
-
271
- print("成分股票配置 :",sharelist)
272
- print("持有日期 :",today)
273
- print("当前头寸 :",format(round(position,2),','))
274
- print("预计持有天数 :",future_days,"天")
275
- print("置信度水平 : ",alpha*100,"%",sep='')
276
- print("使用的历史样本数据:",pastyears,"年")
277
- print("使用的VaR模型 :",type)
278
-
279
- print("\n*** 在险价值 ***")
280
- print("VaR金额:",format(round(VaR,2),','))
281
- print("VaR比率: ",round(ratio*100,2),"%",sep='')
282
-
283
- print("\n*** 回溯测试 ***")
284
- print("期望的置信度水平 : ",alpha*100,"%",sep='')
285
- print("损失超过VaR的预期天数 :",threshhold_expected,'天')
286
- print("损失超过VaR的实际天数 :",threshhold_actual,'天')
287
- print("实际的置信度水平 : ",round(alpha_actual*100,2),"%",sep='')
288
- print("模型验证的回溯测试结果 :",result)
289
- """
290
-
291
- titletxt="VaR模型:回溯测试"
292
- import datetime as dt; todaydt=dt.date.today()
293
- footnote="数据来源:新浪/stooq,"+str(todaydt)
294
- ticker_name_list=list2str(ticker_name(tickerlist,'bond'))
295
- shares=sharelist
296
- if len(sharelist)==1: shares=sharelist[0]
297
-
298
- data_dict={'持有资产:':ticker_name_list, \
299
- '资产配置:':shares, \
300
- '持有日期:':today, \
301
- '预计持有天数:':str(future_days)+'天', \
302
- '置信度:':str(alpha*100)+'%', \
303
- "使用的历史样本数据:":str(pastyears)+"年", \
304
- "使用的VaR模型:":type, \
305
-
306
- "*** 在险价值 ***":'', \
307
- "VaR金额:":format(round(VaR,2),','), \
308
- "VaR比率:":str(round(ratio*100,2))+"%", \
309
-
310
- "*** 回溯测试 ***":'', \
311
- "期望的置信度水平:":str(alpha*100)+"%", \
312
- "损失超过VaR的预期天数:":str(threshhold_expected)+'天', \
313
- "损失超过VaR的实际天数:":str(threshhold_actual)+'天', \
314
- "实际的置信度水平:":str(round(alpha_actual*100,2))+"%", \
315
- "模型验证的回溯测试结果:":result}
316
-
317
- print2CSS(data_dict,titletxt=titletxt,footnote=footnote)
318
-
319
-
320
- return
321
-
322
- if __name__ == "__main__":
323
- tickerlist=['AAPL']
324
- sharelist=[1]
325
- backtest_VaR(tickerlist,sharelist,'2019-8-8',1, \
326
- pastyears=1,model="montecarlo")
327
- backtest_VaR(tickerlist,sharelist,'2019-8-8',1, \
328
- pastyears=1,model="normal_standard")
329
- backtest_VaR(tickerlist,sharelist,'2019-8-8',1, \
330
- pastyears=1,model="normal_modified")
331
- backtest_VaR(tickerlist,sharelist,'2019-8-8',1, \
332
- pastyears=1,model="historical")
333
-
334
- #==============================================================================
335
- def backtest_VaR_portfolio(portfolio,today,future_days=1, \
336
- alpha=0.99,pastyears=1,model="montecarlo",random=10000):
337
- """
338
- 功能:检验VaR模型的有效性,历史回溯测试
339
- 输入参数:股票代码列表,持有股数列表,当前日期,预期持有天数,置信度,
340
- 使用历史书据的年数,模型类型,模拟次数(仅适用于蒙特卡洛法)
341
- """
342
-
343
- #检查当前日期的合理性
344
- if not check_date(today): return
345
-
346
- #解构投资组合
347
- _,_,tickerlist,sharelist,ticker_type=decompose_portfolio(portfolio)
348
-
349
- #计算开始日期
350
- startdate=get_start_date(today,pastyears)
351
- import pandas as pd
352
- enddate=pd.to_datetime(today)
353
-
354
- #下载股价数据
355
- price=get_prices_portfolio(tickerlist,sharelist,startdate,enddate)
356
- #计算收益率,以future_days作为分组大小
357
- ret=calc_ret(price,future_days)
358
-
359
- #计算当前持有的头寸
360
- position=price['Close'][-1]
361
- #计算VaR
362
- type,VaR=calc_VaR_1d(position,ret,alpha,model)
363
- #计算VaR比率
364
- ratio=abs(VaR/position)
365
-
366
- #预期:收益率低于VaR比率的期数(天数或组数)
367
- threshhold_expected=round(len(ret)*(1-alpha),2)
368
- #实际:收益率低于VaR比率的期数(天数或组数)
369
- threshhold_actual=len(ret[ret<-ratio])
370
- alpha_actual=1-threshhold_actual/len(ret)
371
-
372
- #结果判读
373
- if abs(alpha_actual-alpha) < 0.001:
374
- result="准确"
375
- elif alpha_actual < alpha:
376
- result="低估"
377
- else:
378
- result="高估"
379
-
380
- #打印结果
381
- """
382
- print("\n======= VaR模型:回溯测试 =======")
383
- print("投资组合 :",tickerlist)
384
- print("成分股票配置 :",sharelist)
385
- print("持有日期 :",today)
386
- print("当前头寸 :",format(round(position,2),','))
387
- print("预计持有天数 :",future_days,"天")
388
- print("置信度水平 : ",alpha*100,"%",sep='')
389
- print("使用的历史样本数据:",pastyears,"年")
390
- print("使用的VaR模型 :",type)
391
-
392
- print("\n*** 在险价值 ***")
393
- print("VaR金额:",format(round(VaR,2),','))
394
- print("VaR比率: ",round(ratio*100,2),"%",sep='')
395
-
396
- print("\n*** 回溯测试 ***")
397
- print("期望的置信度水平 : ",alpha*100,"%",sep='')
398
- print("损失超过VaR的预期天数 :",threshhold_expected,'天')
399
- print("损失超过VaR的实际天数 :",threshhold_actual,'天')
400
- print("实际的置信度水平 : ",round(alpha_actual*100,2),"%",sep='')
401
- print("模型验证的回溯测试结果 :",result)
402
- """
403
-
404
- titletxt="VaR模型:回溯测试"
405
- import datetime as dt; todaydt=dt.date.today()
406
- footnote="数据来源:新浪/stooq,"+str(todaydt)
407
-
408
- data_dict={'投资组合:':portfolio_name(portfolio), \
409
- '持有日期:':today, \
410
- "当前头寸:":format(round(position,2),','), \
411
- '预计持有天数:':str(future_days)+'天', \
412
- '置信度水平:':str(alpha*100)+'%', \
413
- "使用的历史样本数据:":str(pastyears)+"年", \
414
- "使用的VaR模型:":type, \
415
-
416
- "*** 在险价值 ***":'', \
417
- "VaR金额:":format(round(VaR,2),','), \
418
- "VaR比率:":str(round(ratio*100,2))+"%", \
419
-
420
- "*** 回溯测试 ***":'', \
421
- "期望的置信度水平:":str(alpha*100)+"%", \
422
- "损失超过VaR的预期天数:":str(threshhold_expected)+'天', \
423
- "损失超过VaR的实际天数:":str(threshhold_actual)+'天', \
424
- "实际的置信度水平:":str(round(alpha_actual*100,2))+"%", \
425
- "模型验证的回溯测试结果:":result}
426
-
427
- print2CSS(data_dict,titletxt=titletxt,footnote=footnote)
428
-
429
-
430
- return
431
-
432
- if __name__ == "__main__":
433
- tickerlist=['AAPL']
434
- sharelist=[1]
435
- backtest_VaR(tickerlist,sharelist,'2019-8-8',1, \
436
- pastyears=1,model="montecarlo")
437
- backtest_VaR(tickerlist,sharelist,'2019-8-8',1, \
438
- pastyears=1,model="normal_standard")
439
- backtest_VaR(tickerlist,sharelist,'2019-8-8',1, \
440
- pastyears=1,model="normal_modified")
441
- backtest_VaR(tickerlist,sharelist,'2019-8-8',1, \
442
- pastyears=1,model="historical")
443
-
444
- #==============================================================================