siat 3.10.130__py3-none-any.whl → 3.10.132__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 (217) hide show
  1. build/lib/build/lib/siat/__init__.py +75 -0
  2. build/lib/build/lib/siat/allin.py +137 -0
  3. build/lib/build/lib/siat/assets_liquidity.py +915 -0
  4. build/lib/build/lib/siat/beta_adjustment.py +1058 -0
  5. build/lib/build/lib/siat/beta_adjustment_china.py +548 -0
  6. build/lib/build/lib/siat/blockchain.py +143 -0
  7. build/lib/build/lib/siat/bond.py +2900 -0
  8. build/lib/build/lib/siat/bond_base.py +992 -0
  9. build/lib/build/lib/siat/bond_china.py +100 -0
  10. build/lib/build/lib/siat/bond_zh_sina.py +143 -0
  11. build/lib/build/lib/siat/capm_beta.py +783 -0
  12. build/lib/build/lib/siat/capm_beta2.py +887 -0
  13. build/lib/build/lib/siat/common.py +5360 -0
  14. build/lib/build/lib/siat/compare_cross.py +642 -0
  15. build/lib/build/lib/siat/copyrights.py +18 -0
  16. build/lib/build/lib/siat/cryptocurrency.py +667 -0
  17. build/lib/build/lib/siat/economy.py +1471 -0
  18. build/lib/build/lib/siat/economy2.py +1853 -0
  19. build/lib/build/lib/siat/esg.py +536 -0
  20. build/lib/build/lib/siat/event_study.py +815 -0
  21. build/lib/build/lib/siat/fama_french.py +1521 -0
  22. build/lib/build/lib/siat/fin_stmt2_yahoo.py +982 -0
  23. build/lib/build/lib/siat/financial_base.py +1160 -0
  24. build/lib/build/lib/siat/financial_statements.py +598 -0
  25. build/lib/build/lib/siat/financials.py +2339 -0
  26. build/lib/build/lib/siat/financials2.py +1278 -0
  27. build/lib/build/lib/siat/financials_china.py +4433 -0
  28. build/lib/build/lib/siat/financials_china2.py +2212 -0
  29. build/lib/build/lib/siat/fund.py +629 -0
  30. build/lib/build/lib/siat/fund_china.py +3307 -0
  31. build/lib/build/lib/siat/future_china.py +551 -0
  32. build/lib/build/lib/siat/google_authenticator.py +47 -0
  33. build/lib/build/lib/siat/grafix.py +3636 -0
  34. build/lib/build/lib/siat/holding_risk.py +867 -0
  35. build/lib/build/lib/siat/luchy_draw.py +638 -0
  36. build/lib/build/lib/siat/market_china.py +1168 -0
  37. build/lib/build/lib/siat/markowitz.py +2363 -0
  38. build/lib/build/lib/siat/markowitz2.py +3150 -0
  39. build/lib/build/lib/siat/markowitz2_20250704.py +2969 -0
  40. build/lib/build/lib/siat/markowitz2_20250705.py +3158 -0
  41. build/lib/build/lib/siat/markowitz_simple.py +373 -0
  42. build/lib/build/lib/siat/ml_cases.py +2291 -0
  43. build/lib/build/lib/siat/ml_cases_example.py +60 -0
  44. build/lib/build/lib/siat/option_china.py +3069 -0
  45. build/lib/build/lib/siat/option_pricing.py +1925 -0
  46. build/lib/build/lib/siat/other_indexes.py +409 -0
  47. build/lib/build/lib/siat/risk_adjusted_return.py +1576 -0
  48. build/lib/build/lib/siat/risk_adjusted_return2.py +1900 -0
  49. build/lib/build/lib/siat/risk_evaluation.py +2218 -0
  50. build/lib/build/lib/siat/risk_free_rate.py +351 -0
  51. build/lib/build/lib/siat/sector_china.py +4140 -0
  52. build/lib/build/lib/siat/security_price2.py +727 -0
  53. build/lib/build/lib/siat/security_prices.py +3408 -0
  54. build/lib/build/lib/siat/security_trend.py +402 -0
  55. build/lib/build/lib/siat/security_trend2.py +646 -0
  56. build/lib/build/lib/siat/stock.py +4284 -0
  57. build/lib/build/lib/siat/stock_advice_linear.py +934 -0
  58. build/lib/build/lib/siat/stock_base.py +26 -0
  59. build/lib/build/lib/siat/stock_china.py +2095 -0
  60. build/lib/build/lib/siat/stock_prices_kneighbors.py +910 -0
  61. build/lib/build/lib/siat/stock_prices_linear.py +386 -0
  62. build/lib/build/lib/siat/stock_profile.py +707 -0
  63. build/lib/build/lib/siat/stock_technical.py +3305 -0
  64. build/lib/build/lib/siat/stooq.py +74 -0
  65. build/lib/build/lib/siat/transaction.py +347 -0
  66. build/lib/build/lib/siat/translate.py +5183 -0
  67. build/lib/build/lib/siat/valuation.py +1378 -0
  68. build/lib/build/lib/siat/valuation_china.py +2076 -0
  69. build/lib/build/lib/siat/var_model_validation.py +444 -0
  70. build/lib/build/lib/siat/yf_name.py +811 -0
  71. build/lib/siat/__init__.py +75 -0
  72. build/lib/siat/allin.py +137 -0
  73. build/lib/siat/assets_liquidity.py +915 -0
  74. build/lib/siat/beta_adjustment.py +1058 -0
  75. build/lib/siat/beta_adjustment_china.py +548 -0
  76. build/lib/siat/blockchain.py +143 -0
  77. build/lib/siat/bond.py +2900 -0
  78. build/lib/siat/bond_base.py +992 -0
  79. build/lib/siat/bond_china.py +100 -0
  80. build/lib/siat/bond_zh_sina.py +143 -0
  81. build/lib/siat/capm_beta.py +783 -0
  82. build/lib/siat/capm_beta2.py +887 -0
  83. build/lib/siat/common.py +5360 -0
  84. build/lib/siat/compare_cross.py +642 -0
  85. build/lib/siat/copyrights.py +18 -0
  86. build/lib/siat/cryptocurrency.py +667 -0
  87. build/lib/siat/economy.py +1471 -0
  88. build/lib/siat/economy2.py +1853 -0
  89. build/lib/siat/esg.py +536 -0
  90. build/lib/siat/event_study.py +815 -0
  91. build/lib/siat/fama_french.py +1521 -0
  92. build/lib/siat/fin_stmt2_yahoo.py +982 -0
  93. build/lib/siat/financial_base.py +1160 -0
  94. build/lib/siat/financial_statements.py +598 -0
  95. build/lib/siat/financials.py +2339 -0
  96. build/lib/siat/financials2.py +1278 -0
  97. build/lib/siat/financials_china.py +4433 -0
  98. build/lib/siat/financials_china2.py +2212 -0
  99. build/lib/siat/fund.py +629 -0
  100. build/lib/siat/fund_china.py +3307 -0
  101. build/lib/siat/future_china.py +551 -0
  102. build/lib/siat/google_authenticator.py +47 -0
  103. build/lib/siat/grafix.py +3636 -0
  104. build/lib/siat/holding_risk.py +867 -0
  105. build/lib/siat/luchy_draw.py +638 -0
  106. build/lib/siat/market_china.py +1168 -0
  107. build/lib/siat/markowitz.py +2363 -0
  108. build/lib/siat/markowitz2.py +3150 -0
  109. build/lib/siat/markowitz2_20250704.py +2969 -0
  110. build/lib/siat/markowitz2_20250705.py +3158 -0
  111. build/lib/siat/markowitz_simple.py +373 -0
  112. build/lib/siat/ml_cases.py +2291 -0
  113. build/lib/siat/ml_cases_example.py +60 -0
  114. build/lib/siat/option_china.py +3069 -0
  115. build/lib/siat/option_pricing.py +1925 -0
  116. build/lib/siat/other_indexes.py +409 -0
  117. build/lib/siat/risk_adjusted_return.py +1576 -0
  118. build/lib/siat/risk_adjusted_return2.py +1900 -0
  119. build/lib/siat/risk_evaluation.py +2218 -0
  120. build/lib/siat/risk_free_rate.py +351 -0
  121. build/lib/siat/sector_china.py +4140 -0
  122. build/lib/siat/security_price2.py +727 -0
  123. build/lib/siat/security_prices.py +3408 -0
  124. build/lib/siat/security_trend.py +402 -0
  125. build/lib/siat/security_trend2.py +646 -0
  126. build/lib/siat/stock.py +4284 -0
  127. build/lib/siat/stock_advice_linear.py +934 -0
  128. build/lib/siat/stock_base.py +26 -0
  129. build/lib/siat/stock_china.py +2095 -0
  130. build/lib/siat/stock_prices_kneighbors.py +910 -0
  131. build/lib/siat/stock_prices_linear.py +386 -0
  132. build/lib/siat/stock_profile.py +707 -0
  133. build/lib/siat/stock_technical.py +3305 -0
  134. build/lib/siat/stooq.py +74 -0
  135. build/lib/siat/transaction.py +347 -0
  136. build/lib/siat/translate.py +5183 -0
  137. build/lib/siat/valuation.py +1378 -0
  138. build/lib/siat/valuation_china.py +2076 -0
  139. build/lib/siat/var_model_validation.py +444 -0
  140. build/lib/siat/yf_name.py +811 -0
  141. siat/__init__.py +0 -0
  142. siat/allin.py +0 -0
  143. siat/assets_liquidity.py +0 -0
  144. siat/beta_adjustment.py +0 -0
  145. siat/beta_adjustment_china.py +0 -0
  146. siat/blockchain.py +0 -0
  147. siat/bond.py +0 -0
  148. siat/bond_base.py +0 -0
  149. siat/bond_china.py +0 -0
  150. siat/bond_zh_sina.py +0 -0
  151. siat/capm_beta.py +0 -0
  152. siat/capm_beta2.py +0 -0
  153. siat/common.py +94 -30
  154. siat/compare_cross.py +0 -0
  155. siat/copyrights.py +0 -0
  156. siat/cryptocurrency.py +0 -0
  157. siat/economy.py +0 -0
  158. siat/economy2.py +0 -0
  159. siat/esg.py +0 -0
  160. siat/event_study.py +0 -0
  161. siat/fama_french.py +0 -0
  162. siat/fin_stmt2_yahoo.py +0 -0
  163. siat/financial_base.py +0 -0
  164. siat/financial_statements.py +0 -0
  165. siat/financials.py +0 -0
  166. siat/financials2.py +0 -0
  167. siat/financials_china.py +0 -0
  168. siat/financials_china2.py +0 -0
  169. siat/fund.py +0 -0
  170. siat/fund_china.py +0 -0
  171. siat/future_china.py +0 -0
  172. siat/google_authenticator.py +0 -0
  173. siat/grafix.py +1 -1
  174. siat/holding_risk.py +0 -0
  175. siat/luchy_draw.py +0 -0
  176. siat/market_china.py +7 -1
  177. siat/markowitz.py +0 -0
  178. siat/markowitz2.py +240 -39
  179. siat/markowitz2_20250704.py +2969 -0
  180. siat/markowitz2_20250705.py +3158 -0
  181. siat/markowitz_simple.py +0 -0
  182. siat/ml_cases.py +0 -0
  183. siat/ml_cases_example.py +0 -0
  184. siat/option_china.py +0 -0
  185. siat/option_pricing.py +0 -0
  186. siat/other_indexes.py +0 -0
  187. siat/risk_adjusted_return.py +0 -0
  188. siat/risk_adjusted_return2.py +0 -0
  189. siat/risk_evaluation.py +0 -0
  190. siat/risk_free_rate.py +0 -0
  191. siat/sector_china.py +0 -0
  192. siat/security_price2.py +0 -0
  193. siat/security_prices.py +3 -1
  194. siat/security_trend.py +0 -0
  195. siat/security_trend2.py +1 -1
  196. siat/stock.py +4 -2
  197. siat/stock_advice_linear.py +0 -0
  198. siat/stock_base.py +0 -0
  199. siat/stock_china.py +0 -0
  200. siat/stock_prices_kneighbors.py +0 -0
  201. siat/stock_prices_linear.py +0 -0
  202. siat/stock_profile.py +0 -0
  203. siat/stock_technical.py +0 -0
  204. siat/stooq.py +0 -0
  205. siat/transaction.py +0 -0
  206. siat/translate.py +11 -11
  207. siat/valuation.py +0 -0
  208. siat/valuation_china.py +0 -0
  209. siat/var_model_validation.py +0 -0
  210. siat/yf_name.py +0 -0
  211. {siat-3.10.130.dist-info → siat-3.10.132.dist-info}/METADATA +11 -11
  212. siat-3.10.132.dist-info/RECORD +218 -0
  213. siat-3.10.132.dist-info/top_level.txt +4 -0
  214. siat-3.10.130.dist-info/RECORD +0 -76
  215. siat-3.10.130.dist-info/top_level.txt +0 -1
  216. {siat-3.10.130.dist-info → siat-3.10.132.dist-info}/WHEEL +0 -0
  217. {siat-3.10.130.dist-info → siat-3.10.132.dist-info}/licenses/LICENSE +0 -0
@@ -0,0 +1,2969 @@
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ 本模块功能:证券投资组合理论优化分析,手动输入RF版
4
+ 所属工具包:证券投资分析工具SIAT
5
+ SIAT:Security Investment Analysis Tool
6
+ 创建日期:2024年4月19日
7
+ 最新修订日期:2024年4月19日
8
+ 作者:王德宏 (WANG Dehong, Peter)
9
+ 作者单位:北京外国语大学国际商学院
10
+ 作者邮件:wdehong2000@163.com
11
+ 版权所有:王德宏
12
+ 用途限制:仅限研究与教学使用,不可商用!商用需要额外授权。
13
+ 特别声明:作者不对使用本工具进行证券投资导致的任何损益负责!
14
+ """
15
+ #==============================================================================
16
+ #统一屏蔽一般性警告
17
+ import warnings; warnings.filterwarnings("ignore")
18
+ #==============================================================================
19
+
20
+ from siat.common import *
21
+ from siat.translate import *
22
+ from siat.security_prices import *
23
+ from siat.security_price2 import *
24
+ #from siat.fama_french import *
25
+
26
+ import pandas as pd
27
+ import numpy as np
28
+ import datetime
29
+ #==============================================================================
30
+ import seaborn as sns
31
+ import matplotlib.pyplot as plt
32
+ #统一设定绘制的图片大小:数值为英寸,1英寸=100像素
33
+ #plt.rcParams['figure.figsize']=(12.8,7.2)
34
+ plt.rcParams['figure.figsize']=(12.8,6.4)
35
+ plt.rcParams['figure.dpi']=300
36
+ plt.rcParams['font.size'] = 13
37
+ plt.rcParams['xtick.labelsize']=11 #横轴字体大小
38
+ plt.rcParams['ytick.labelsize']=11 #纵轴字体大小
39
+
40
+ title_txt_size=16
41
+ ylabel_txt_size=14
42
+ xlabel_txt_size=14
43
+ legend_txt_size=14
44
+
45
+ #设置绘图风格:网格虚线
46
+ plt.rcParams['axes.grid']=True
47
+ #plt.rcParams['grid.color']='steelblue'
48
+ #plt.rcParams['grid.linestyle']='dashed'
49
+ #plt.rcParams['grid.linewidth']=0.5
50
+ #plt.rcParams['axes.facecolor']='papayawhip'
51
+
52
+ #处理绘图汉字乱码问题
53
+ import sys; czxt=sys.platform
54
+ if czxt in ['win32','win64']:
55
+ plt.rcParams['font.sans-serif'] = ['SimHei'] # 设置默认字体
56
+ mpfrc={'font.family': 'SimHei'}
57
+ sns.set_style('whitegrid',{'font.sans-serif':['simhei','Arial']})
58
+
59
+ if czxt in ['darwin','linux']: #MacOSX
60
+ #plt.rcParams['font.family'] = ['Arial Unicode MS'] #用来正常显示中文标签
61
+ plt.rcParams['font.family']= ['Heiti TC']
62
+ mpfrc={'font.family': 'Heiti TC'}
63
+ sns.set_style('whitegrid',{'font.sans-serif':['Arial Unicode MS','Arial']})
64
+
65
+
66
+ # 解决保存图像时'-'显示为方块的问题
67
+ plt.rcParams['axes.unicode_minus'] = False
68
+ #==============================================================================
69
+ #全局变量定义
70
+ RANDOM_SEED=1234567890
71
+
72
+ #==============================================================================
73
+ def portfolio_config(tickerlist,sharelist):
74
+ """
75
+ 将股票列表tickerlist和份额列表sharelist合成为一个字典
76
+ """
77
+ #整理sharelist的小数点
78
+ ratiolist=[]
79
+ for s in sharelist:
80
+ ss=round(s,4); ratiolist=ratiolist+[ss]
81
+ #合成字典
82
+ new_dict=dict(zip(tickerlist,ratiolist))
83
+ return new_dict
84
+
85
+ #==============================================================================
86
+ def ratiolist_round(sharelist,num=4):
87
+ """
88
+ 将股票份额列表sharelist中的数值四舍五入
89
+ """
90
+ #整理sharelist的小数点
91
+ ratiolist=[]
92
+ for s in sharelist:
93
+ ss=round(s,num); ratiolist=ratiolist+[ss]
94
+ return ratiolist
95
+
96
+ #==============================================================================
97
+ def varname(p):
98
+ """
99
+ 功能:获得变量的名字本身。
100
+ """
101
+ import inspect
102
+ import re
103
+ for line in inspect.getframeinfo(inspect.currentframe().f_back)[3]:
104
+ m = re.search(r'\bvarname\s*\(\s*([A-Za-z_][A-Za-z0-9_]*)\s*\)', line)
105
+ if m:
106
+ return m.group(1)
107
+
108
+ #==============================================================================
109
+ if __name__=='__main__':
110
+ end_date='2021-12-3'
111
+ pastyears=3
112
+
113
+ def get_start_date(end_date,pastyears=1):
114
+ """
115
+ 输入参数:一个日期,年数
116
+ 输出参数:几年前的日期
117
+ start_date, end_date是datetime类型
118
+ """
119
+ import pandas as pd
120
+ try:
121
+ end_date=pd.to_datetime(end_date)
122
+ except:
123
+ print(" #Error(get_start_date): invalid date,",end_date)
124
+ return None
125
+
126
+ from datetime import datetime,timedelta
127
+ start_date=datetime(end_date.year-pastyears,end_date.month,end_date.day)
128
+ start_date=start_date-timedelta(days=1)
129
+ # 日期-1是为了保证计算收益率时得到足够的样本数量
130
+
131
+ start=start_date.strftime("%Y-%m-%d")
132
+
133
+ return start
134
+
135
+ #==============================================================================
136
+ #==============================================================================
137
+ #==============================================================================
138
+ if __name__=='__main__':
139
+ retgroup=StockReturns
140
+
141
+ def cumulative_returns_plot(retgroup,name_list="",titletxt="投资组合策略:业绩比较", \
142
+ ylabeltxt="持有收益率",xlabeltxt="", \
143
+ label_list=[],facecolor='papayawhip'):
144
+ """
145
+ 功能:基于传入的name_list绘制多条持有收益率曲线,并从label_list中取出曲线标记
146
+ 注意:最多绘制四条曲线,否则在黑白印刷时无法区分曲线,以此标记为实线、点虚线、划虚线和点划虚线四种
147
+ """
148
+ if name_list=="":
149
+ name_list=list(retgroup)
150
+
151
+ if len(label_list) < len(name_list):
152
+ label_list=name_list
153
+
154
+ if xlabeltxt=="":
155
+ #取出观察期
156
+ hstart0=retgroup.index[0]
157
+ #hstart=str(hstart0.date())
158
+ hstart=str(hstart0.strftime("%Y-%m-%d"))
159
+ hend0=retgroup.index[-1]
160
+ #hend=str(hend0.date())
161
+ hend=str(hend0.strftime("%Y-%m-%d"))
162
+
163
+ lang = check_language()
164
+ import datetime as dt; stoday=dt.date.today()
165
+ if lang == 'Chinese':
166
+ footnote1="观察期间: "+hstart+'至'+hend
167
+ footnote2="\n数据来源:Sina/EM/Stooq/Yahoo,"+str(stoday)
168
+ else:
169
+ footnote1="Period of sample: "+hstart+' to '+hend
170
+ footnote2="\nData source: Sina/EM/Stooq/Yahoo, "+str(stoday)
171
+
172
+ xlabeltxt=footnote1+footnote2
173
+
174
+ # 持有收益曲线绘制函数
175
+ lslist=['-','--',':','-.']
176
+ markerlist=['.','h','+','x','4','3','2','1']
177
+ for name in name_list:
178
+ pos=name_list.index(name)
179
+ rlabel=label_list[pos]
180
+ if pos < len(lslist):
181
+ thisls=lslist[pos]
182
+ else:
183
+ thisls=(45,(55,20))
184
+
185
+ # 计算持有收益率
186
+ CumulativeReturns = ((1+retgroup[name]).cumprod()-1)
187
+ if pos-len(lslist) < 0:
188
+ CumulativeReturns.plot(label=ectranslate(rlabel),ls=thisls)
189
+ else:
190
+ thismarker=markerlist[pos-len(lslist)]
191
+ CumulativeReturns.plot(label=ectranslate(rlabel),ls=thisls,marker=thismarker,markersize=4)
192
+
193
+ plt.axhline(y=0,ls=":",c="red")
194
+ plt.legend(loc='best')
195
+ plt.title(titletxt); plt.ylabel(ylabeltxt); plt.xlabel(xlabeltxt)
196
+
197
+ plt.gca().set_facecolor(facecolor)
198
+ plt.show()
199
+
200
+ return
201
+
202
+ if __name__=='__main__':
203
+ retgroup=StockReturns
204
+ cumulative_returns_plot(retgroup,name_list,titletxt,ylabeltxt,xlabeltxt, \
205
+ label_list=[])
206
+
207
+ def portfolio_expret_plot(retgroup,name_list="",titletxt="投资组合策略:业绩比较", \
208
+ ylabeltxt="持有收益率",xlabeltxt="", \
209
+ label_list=[]):
210
+ """
211
+ 功能:套壳函数cumulative_returns_plot
212
+ """
213
+
214
+ cumulative_returns_plot(retgroup,name_list,titletxt,ylabeltxt,xlabeltxt,label_list)
215
+
216
+ return
217
+
218
+ #==============================================================================
219
+ def portfolio_hpr(portfolio,thedate,pastyears=1, \
220
+ RF=0, \
221
+ printout=True,graph=True):
222
+ """
223
+ 功能:套壳函数portfolio_build
224
+ """
225
+ dflist=portfolio_build(portfolio=portfolio,thedate=thedate,pastyears=pastyears, \
226
+ printout=printout,graph=graph)
227
+
228
+ return dflist
229
+
230
+ #==============================================================================
231
+ if __name__=='__main__':
232
+ #测试1
233
+ Market={'Market':('US','^GSPC')}
234
+ Market={'Market':('US','^GSPC','我的组合001')}
235
+ Stocks1={'AAPL':.3,'MSFT':.15,'AMZN':.15,'GOOG':.01}
236
+ Stocks2={'XOM':.02,'JNJ':.02,'JPM':.01,'TSLA':.3,'SBUX':.03}
237
+ portfolio=dict(Market,**Stocks1,**Stocks2)
238
+
239
+ #测试2
240
+ Market={'Market':('China','000300.SS','养猪1号组合')}
241
+ porkbig={'000876.SZ':0.20,#新希望
242
+ '300498.SZ':0.15,#温氏股份
243
+ }
244
+ porksmall={'002124.SZ':0.10,#天邦股份
245
+ '600975.SS':0.10,#新五丰
246
+ '603477.SS':0.10,#巨星股份
247
+ '000735.SZ':0.07,#罗牛山
248
+ }
249
+ portfolio=dict(Market,**porkbig,**porksmall)
250
+
251
+ #测试3
252
+ Market={'Market':('China','000300.SS','股债基组合')}
253
+ Stocks={'600519.SS':0.3,#股票:贵州茅台
254
+ 'sh010504':[0.5,'bond'],#05国债⑷
255
+ '010504.SS':('fund',0.2),#招商稳兴混合C基金
256
+ }
257
+ portfolio=dict(Market,**Stocks)
258
+
259
+ printout=True
260
+ graph=False
261
+
262
+ indicator='Adj Close'
263
+ adjust='qfq'; source='auto'; ticker_type='bond'
264
+ thedate='2024-6-19'
265
+ pastyears=2
266
+
267
+
268
+ #测试3
269
+ Market={'Market':('China','000300.SS','股债基组合')}
270
+ Stocks={'600519.SS':0.3,#股票:贵州茅台
271
+ 'sh010504':[0.5,'bond'],#05国债⑷
272
+ '010504.SS':('fund',0.2),#招商稳兴混合C基金
273
+ }
274
+ portfolio=dict(Market,**Stocks)
275
+
276
+ indicator='Close'
277
+ adjust=''; source='auto'; ticker_type='auto'
278
+ thedate='2024-6-19'
279
+ pastyears=1
280
+ printout=True
281
+ graph=False
282
+
283
+
284
+ pf_info=portfolio_build(portfolio,thedate,pastyears,printout,graph)
285
+
286
+ """
287
+ def portfolio_cumret(portfolio,thedate,pastyears=1, \
288
+ RF=0, \
289
+ printout=True,graph=True):
290
+ """
291
+ def portfolio_build(portfolio,thedate='default',pastyears=3, \
292
+ indicator='Adj Close', \
293
+ adjust='qfq',source='auto',ticker_type='auto', \
294
+ printout=False,graph=False,facecolor='papayawhip'):
295
+ """
296
+ 功能:收集投资组合成份股数据,绘制收益率趋势图,并与等权和期间内交易额加权策略组合比较
297
+ 注意:
298
+ 1. 此处无需RF,待到优化策略时再指定
299
+ 2. printout=True控制下列内容是否显示:
300
+ 获取股价时的信息
301
+ 是否显示原始组合、等权重组合和交易金额加权组合的成分股构成
302
+ 是否显示原始组合、等权重组合和交易金额加权组合的收益风险排名
303
+ 3. pastyears=3更有可能生成斜向上的椭圆形可行集,短于3形状不佳,长于3改善形状有限。
304
+ 需要与不同行业的证券搭配。同行业证券相关性较强,不易生成斜向上的椭圆形可行集。
305
+ 4. 若ticker_type='fund'可能导致无法处理股票的复权价!
306
+ 5. 若要指定特定的证券为债券,则需要使用列表逐一指定证券的类型(股票,债券,基金)
307
+ 6. 默认采用前复权计算收益率,更加平稳
308
+ """
309
+ #判断复权标志
310
+ indicator_list=['Close','Adj Close']
311
+ if indicator not in indicator_list:
312
+ print(" Warning(portfolio_build): invalid indicator",indicator)
313
+ print(" Supported indicator:",indicator_list)
314
+ indicator='Adj Close'
315
+
316
+ adjust_list=['','qfq','hfq']
317
+ if adjust not in adjust_list:
318
+ print(" Warning(portfolio_build): invalid indicator",adjust)
319
+ print(" Supported adjust:",adjust_list)
320
+ adjust='qfq'
321
+
322
+ import datetime
323
+ stoday = datetime.date.today()
324
+ if thedate=='default':
325
+ thedate=str(stoday)
326
+ else:
327
+ if not check_date(thedate):
328
+ print(" #Warning(portfolio_build): invalid date",thedate)
329
+ return None
330
+
331
+ print(" Searching for portfolio info, which may take time ...")
332
+ # 解构投资组合
333
+ scope,_,tickerlist,sharelist0,ticker_type=decompose_portfolio(portfolio)
334
+ pname=portfolio_name(portfolio)
335
+
336
+ #如果持仓份额总数不为1,则将其转换为总份额为1
337
+ import numpy as np
338
+ totalshares=np.sum(sharelist0)
339
+ if abs(totalshares - 1) >= 0.00001:
340
+ print(" #Warning(portfolio_build): total weights is",totalshares,"\b, expecting 1.0 here")
341
+ print(" Action taken: automatically converted into total weights 1.0")
342
+ sharelist=list(sharelist0/totalshares)
343
+ else:
344
+ sharelist=sharelist0
345
+
346
+ #..........................................................................
347
+ # 计算历史数据的开始日期
348
+ start=get_start_date(thedate,pastyears)
349
+
350
+ #处理无风险利率,不再需要,但为兼容考虑仍保留,根据手动输入的RF构造rf_df以便后续改动量较小
351
+ import pandas as pd
352
+ date_series = pd.date_range(start=start,end=thedate,freq='D')
353
+ rf_df=pd.DataFrame(index=date_series)
354
+ rf_df['date']=rf_df.index
355
+ rf_df['date']=rf_df['date'].apply(lambda x: x.strftime('%Y-%m-%d'))
356
+ rf_df['RF']=RF=0
357
+ rf_df['rf_daily']=RF/365
358
+ """
359
+ #一次性获得无风险利率,传递给后续函数,避免后续每次获取,耗费时间
360
+ if RF:
361
+ rf_df=get_rf_daily(start,thedate,scope,rate_period,rate_type)
362
+ #结果字段中,RF是日利率百分比,rf_daily是日利率数值
363
+ if rf_df is None:
364
+ #print(" #Error(portfolio_build): failed to retrieve risk-free interest rate in",scope)
365
+ print(" #Warning: all subsequent portfolio optimizations cannot proceed")
366
+ print(" Solution1: try again after until success to include risk-free interest rate in calculation")
367
+ print(" Solution2: use RF=False in script command to ignore risk-free interest rate in calculation")
368
+ return None
369
+ else:
370
+ rf_df=None
371
+ """
372
+ #..........................................................................
373
+ import os, sys
374
+ class HiddenPrints:
375
+ def __enter__(self):
376
+ self._original_stdout = sys.stdout
377
+ sys.stdout = open(os.devnull, 'w')
378
+
379
+ def __exit__(self, exc_type, exc_val, exc_tb):
380
+ sys.stdout.close()
381
+ sys.stdout = self._original_stdout
382
+
383
+ # 抓取投资组合股价
384
+ #prices=get_prices(tickerlist,start,thedate)
385
+ #判断是否赚取复权价
386
+ if indicator == 'Adj Close' and adjust == '':
387
+ adjust='qfq'
388
+ if indicator == 'Close' and adjust != '':
389
+ indicator = 'Adj Close'
390
+
391
+ if printout:
392
+ #prices=get_prices_simple(tickerlist,start,thedate) #有待改造?
393
+ #债券优先
394
+ prices,found=get_price_mticker(tickerlist,start,thedate, \
395
+ adjust=adjust,source=source,ticker_type=ticker_type,fill=False)
396
+ else:
397
+ with HiddenPrints():
398
+ #prices=get_prices_simple(tickerlist,start,thedate) #有待改造?
399
+ prices,found=get_price_mticker(tickerlist,start,thedate, \
400
+ adjust=adjust,source=source,ticker_type=ticker_type,fill=False)
401
+
402
+ if found == 'Found':
403
+ ntickers=len(list(prices['Close']))
404
+ nrecords=len(prices)
405
+ #print(" Successfully retrieved",ntickers,"stocks with",nrecords,"record(s) respectively")
406
+ print(" Successfully retrieved prices of",ntickers,"securities for",pname)
407
+
408
+ if ntickers != len(tickerlist):
409
+ print(" However, failed to access some securities, unable to build portfolio",pname)
410
+ return None
411
+
412
+ #if prices is None:
413
+ if found == 'None':
414
+ print(" #Error(portfolio_build): failed to get portfolio prices",pname)
415
+ return None
416
+ #if len(prices) == 0:
417
+ if found == 'Empty':
418
+ print(" #Error(portfolio_build): retrieved empty prices for",pname)
419
+ return None
420
+ #..........................................................................
421
+ #判断是否使用复权价:若是,使用Adj Close直接覆盖Close。方法最简单,且兼容后续处理!
422
+ if (indicator =='Adj Close') or (adjust !=''):
423
+ prices_collist=list(prices)
424
+ for pc in prices_collist:
425
+ pc1=pc[0]; pc2=pc[1]
426
+ if pc1=='Close':
427
+ pc_adj=('Adj Close',pc2)
428
+ prices[pc]=prices[pc_adj]
429
+
430
+ # 取各个成份股的收盘价
431
+ aclose=prices['Close']
432
+ member_prices=aclose
433
+ # 计算各个成份股的日收益率,并丢弃缺失值
434
+ StockReturns = aclose.pct_change().dropna()
435
+ if len(StockReturns) == 0:
436
+ print("\n #Error(portfolio_build): retrieved empty returns for",pname)
437
+ return None
438
+
439
+ # 保存各个成份股的收益率数据,为了后续调用的方便
440
+ stock_return = StockReturns.copy()
441
+
442
+ # 将原投资组合的权重存储为numpy数组类型,为了合成投资组合计算方便
443
+ import numpy as np
444
+ portfolio_weights = np.array(sharelist)
445
+ # 合成portfolio的日收益率
446
+ WeightedReturns = stock_return.mul(portfolio_weights, axis=1)
447
+ # 原投资组合的收益率
448
+ StockReturns['Portfolio'] = WeightedReturns.sum(axis=1)
449
+ #..........................................................................
450
+ #lang = check_language()
451
+ #..........................................................................
452
+
453
+ # 绘制原投资组合的收益率曲线,以便使用收益率%来显示
454
+ if graph:
455
+ plotsr = StockReturns['Portfolio']
456
+ plotsr.plot(label=pname)
457
+ plt.axhline(y=0,ls=":",c="red")
458
+
459
+ title_txt=text_lang("投资组合: 日收益率的变化趋势","Investment Portfolio: Daily Return")
460
+ ylabel_txt=text_lang("日收益率","Daily Return")
461
+ source_txt=text_lang("来源: 综合新浪/东方财富/Stooq/雅虎等, ","Data source: Sina/EM/Stooq/Yahoo, ")
462
+
463
+ plt.title(title_txt)
464
+ plt.ylabel(ylabel_txt)
465
+
466
+ stoday = datetime.date.today()
467
+ plt.xlabel(source_txt+str(stoday))
468
+
469
+ plt.gca().set_facecolor(facecolor)
470
+
471
+ plt.legend(); plt.show(); plt.close()
472
+ #..........................................................................
473
+
474
+ # 计算原投资组合的持有收益率,并绘图
475
+ name_list=["Portfolio"]
476
+ label_list=[pname]
477
+
478
+
479
+ titletxt=text_lang("投资组合: 持有收益率的变化趋势","Investment Portfolio: Holding Period Return%")
480
+ ylabeltxt=text_lang("持有收益率","Holding Period Return%")
481
+ xlabeltxt1=text_lang("数据来源: 综合新浪/东方财富/Stooq/雅虎等, ","Data source: Sina/EM/Stooq/Yahoo, ")
482
+ xlabeltxt=xlabeltxt1+str(stoday)
483
+
484
+ #绘制持有收益率曲线
485
+ if graph:
486
+ cumulative_returns_plot(StockReturns,name_list,titletxt,ylabeltxt,xlabeltxt,label_list,facecolor=facecolor)
487
+ #..........................................................................
488
+
489
+ # 构造等权重组合Portfolio_EW的持有收益率
490
+ numstocks = len(tickerlist)
491
+ # 平均分配每一项的权重
492
+ portfolio_weights_ew = np.repeat(1/numstocks, numstocks)
493
+ # 合成等权重组合的收益,按行横向加总
494
+ StockReturns['Portfolio_EW']=stock_return.mul(portfolio_weights_ew,axis=1).sum(axis=1)
495
+ #..........................................................................
496
+
497
+ # 创建交易额加权组合:按照成交金额计算期间内交易额均值。债券和基金信息中无交易量!
498
+ if ('bond' not in ticker_type) and ('fund' not in ticker_type):
499
+ tamount=prices['Close']*prices['Volume']
500
+ tamountlist=tamount.mean(axis=0) #求列的均值
501
+ tamountlist_array = np.array(tamountlist)
502
+ # 计算成交金额权重
503
+ portfolio_weights_lw = tamountlist_array / np.sum(tamountlist_array)
504
+ # 计算成交金额加权的组合收益
505
+ StockReturns['Portfolio_LW'] = stock_return.mul(portfolio_weights_lw, axis=1).sum(axis=1)
506
+
507
+ #绘制累计收益率对比曲线
508
+ title_txt=text_lang("投资组合策略:业绩对比","Portfolio Strategies: Performance")
509
+ Portfolio_EW_txt=text_lang("等权重策略","Equal-weighted")
510
+ if ('bond' not in ticker_type) and ('fund' not in ticker_type):
511
+ Portfolio_LW_txt=text_lang("交易额加权策略","Amount-weighted")
512
+
513
+ name_list=['Portfolio', 'Portfolio_EW', 'Portfolio_LW']
514
+ label_list=[pname, Portfolio_EW_txt, Portfolio_LW_txt]
515
+ else:
516
+ name_list=['Portfolio', 'Portfolio_EW']
517
+ label_list=[pname, Portfolio_EW_txt]
518
+
519
+
520
+ titletxt=title_txt
521
+
522
+ #绘制各个投资组合的持有收益率曲线
523
+ if graph:
524
+ cumulative_returns_plot(StockReturns,name_list,titletxt,ylabeltxt,xlabeltxt,label_list)
525
+
526
+ #打印各个投资组合的持股比例
527
+ member_returns=stock_return
528
+ if printout:
529
+ portfolio_expectation_universal(pname,member_returns,portfolio_weights,member_prices,ticker_type)
530
+ portfolio_expectation_universal(Portfolio_EW_txt,member_returns,portfolio_weights_ew,member_prices,ticker_type)
531
+
532
+ if ('bond' not in ticker_type) and ('fund' not in ticker_type):
533
+ portfolio_expectation_universal(Portfolio_LW_txt,member_returns,portfolio_weights_lw,member_prices,ticker_type)
534
+
535
+ #返回投资组合的综合信息
536
+ member_returns=stock_return
537
+ portfolio_returns=StockReturns[name_list]
538
+
539
+ #投资组合名称改名
540
+ portfolio_returns=cvt_portfolio_name(pname,portfolio_returns)
541
+
542
+ #打印现有投资组合策略的排名
543
+ if printout:
544
+ portfolio_ranks(portfolio_returns,pname)
545
+
546
+ #
547
+ if ('bond' not in ticker_type) and ('fund' not in ticker_type):
548
+ return [[portfolio,thedate,member_returns,rf_df,member_prices], \
549
+ [portfolio_returns,portfolio_weights,portfolio_weights_ew,portfolio_weights_lw]]
550
+ else:
551
+ return [[portfolio,thedate,member_returns,rf_df,member_prices], \
552
+ [portfolio_returns,portfolio_weights,portfolio_weights_ew,None]]
553
+
554
+
555
+ if __name__=='__main__':
556
+ X=portfolio_build(portfolio,'2021-9-30')
557
+
558
+ if __name__=='__main__':
559
+ pf_info=portfolio_build(portfolio,'2021-9-30')
560
+
561
+ #==============================================================================
562
+
563
+ def portfolio_expret(portfolio,today,pastyears=1, \
564
+ RF=0,printout=True,graph=True):
565
+ """
566
+ 功能:绘制投资组合的持有期收益率趋势图,并与等权和期间内交易额加权组合比较
567
+ 套壳原来的portfolio_build函数,以维持兼容性
568
+ expret: expanding return,以维持与前述章节名词的一致性
569
+ hpr: holding period return, 持有(期)收益率
570
+ 注意:实验发现RF对于结果的影响极其微小难以观察,默认设为不使用无风险利率调整收益,以加快运行速度
571
+ """
572
+ #处理失败的返回值
573
+ results=portfolio_build(portfolio,today,pastyears, \
574
+ rate_period,rate_type,RF,printout,graph)
575
+ if results is None: return None
576
+
577
+ [[portfolio,thedate,member_returns,rf_df,member_prices], \
578
+ [portfolio_returns,portfolio_weights,portfolio_weights_ew,portfolio_weights_lw]] = results
579
+
580
+ return [[portfolio,thedate,member_returns,rf_df,member_prices], \
581
+ [portfolio_returns,portfolio_weights,portfolio_weights_ew,portfolio_weights_lw]]
582
+
583
+ if __name__=='__main__':
584
+ pf_info=portfolio_expret(portfolio,'2021-9-30')
585
+
586
+ #==============================================================================
587
+ def portfolio_correlate(pf_info):
588
+ """
589
+ 功能:绘制投资组合成份股之间相关关系的热力图
590
+ """
591
+ [[portfolio,thedate,stock_return,_,_],_]=pf_info
592
+ pname=portfolio_name(portfolio)
593
+
594
+ #取出观察期
595
+ hstart0=stock_return.index[0]; hstart=str(hstart0.strftime("%Y-%m-%d"))
596
+ hend0=stock_return.index[-1]; hend=str(hend0.strftime("%Y-%m-%d"))
597
+
598
+ sr=stock_return.copy()
599
+ collist=list(sr)
600
+ for col in collist:
601
+ #投资组合中名称翻译以债券优先处理,因此几乎没有人把基金作为成分股
602
+ sr.rename(columns={col:ticker_name(col,'bond')},inplace=True)
603
+
604
+ # 计算相关矩阵
605
+ correlation_matrix = sr.corr()
606
+
607
+ # 导入seaborn
608
+ import seaborn as sns
609
+ # 创建热图
610
+ sns.heatmap(correlation_matrix,annot=True,cmap="YlGnBu",linewidths=0.3,
611
+ annot_kws={"size": 16})
612
+ plt.title(pname+": 成份股收益率之间的相关系数")
613
+ plt.ylabel("成份股票")
614
+
615
+ footnote1="观察期间: "+hstart+'至'+hend
616
+ import datetime as dt; stoday=dt.date.today()
617
+ footnote2="\n来源:Sina/EM/stooq,"+str(stoday)
618
+ plt.xlabel(footnote1+footnote2)
619
+ plt.xticks(rotation=90); plt.yticks(rotation=0)
620
+
621
+ plt.gca().set_facecolor('papayawhip')
622
+ plt.show()
623
+
624
+ return
625
+
626
+ if __name__=='__main__':
627
+ Market={'Market':('US','^GSPC','我的组合001')}
628
+ Stocks1={'AAPL':.1,'MSFT':.13,'XOM':.09,'JNJ':.09,'JPM':.09}
629
+ Stocks2={'AMZN':.15,'GE':.08,'FB':.13,'T':.14}
630
+ portfolio=dict(Market,**Stocks1,**Stocks2)
631
+ pf_info=portfolio_expret(portfolio,'2019-12-31')
632
+
633
+ portfolio_correlate(pf_info)
634
+ #==============================================================================
635
+ def portfolio_covar(pf_info):
636
+ """
637
+ 功能:计算投资组合成份股之间的协方差
638
+ """
639
+ [[portfolio,thedate,stock_return,_,_],_]=pf_info
640
+ pname=portfolio_name(portfolio)
641
+
642
+ #取出观察期
643
+ hstart0=stock_return.index[0]; hstart=str(hstart0.strftime("%Y-%m-%d"))
644
+ hend0=stock_return.index[-1]; hend=str(hend0.strftime("%Y-%m-%d"))
645
+
646
+ # 计算协方差矩阵
647
+ cov_mat = stock_return.cov()
648
+ # 年化协方差矩阵,252个交易日
649
+ cov_mat_annual = cov_mat * 252
650
+
651
+ # 导入seaborn
652
+ import seaborn as sns
653
+ # 创建热图
654
+ sns.heatmap(cov_mat_annual,annot=True,cmap="YlGnBu",linewidths=0.3,
655
+ annot_kws={"size": 8})
656
+ plt.title(pname+": 成份股之间的协方差")
657
+ plt.ylabel("成份股票")
658
+
659
+ footnote1="观察期间: "+hstart+'至'+hend
660
+ import datetime as dt; stoday=dt.date.today()
661
+ footnote2="\n来源:Sina/EM/stooq,"+str(stoday)
662
+ plt.xlabel(footnote1+footnote2)
663
+ plt.xticks(rotation=90)
664
+ plt.yticks(rotation=0)
665
+
666
+ plt.gca().set_facecolor('papayawhip')
667
+ plt.show()
668
+
669
+ return
670
+
671
+ #==============================================================================
672
+ def portfolio_expectation_original(pf_info):
673
+ """
674
+ 功能:计算原始投资组合的年均收益率和标准差
675
+ 输入:pf_info
676
+ 输出:年化收益率和标准差
677
+ """
678
+ [[portfolio,_,member_returns,_,member_prices],[_,portfolio_weights,_,_]]=pf_info
679
+ pname=portfolio_name(portfolio)
680
+
681
+ portfolio_expectation_universal(pname,member_returns,portfolio_weights,member_prices)
682
+
683
+ return
684
+
685
+ if __name__=='__main__':
686
+ Market={'Market':('US','^GSPC','我的组合001')}
687
+ Stocks1={'AAPL':.1,'MSFT':.13,'XOM':.09,'JNJ':.09,'JPM':.09}
688
+ Stocks2={'AMZN':.15,'GE':.08,'FB':.13,'T':.14}
689
+ portfolio=dict(Market,**Stocks1,**Stocks2)
690
+ pf_info=portfolio_expret(portfolio,'2019-12-31')
691
+
692
+ portfolio_expectation_original(pf_info)
693
+
694
+ #==============================================================================
695
+ def portfolio_expectation_universal(pname,member_returns,portfolio_weights,member_prices,ticker_type):
696
+ """
697
+ 功能:计算给定成份股收益率和持股权重的投资组合年均收益率和标准差
698
+ 输入:投资组合名称,成份股历史收益率数据表,投资组合权重series
699
+ 输出:年化收益率和标准差
700
+ 用途:求出MSR、GMV等持仓策略后计算投资组合的年化收益率和标准差
701
+ """
702
+
703
+ #观察期
704
+ hstart0=member_returns.index[0]
705
+ #hstart=str(hstart0.date())
706
+ hstart=str(hstart0.strftime("%Y-%m-%d"))
707
+ hend0=member_returns.index[-1]
708
+ #hend=str(hend0.date())
709
+ hend=str(hend0.strftime("%Y-%m-%d"))
710
+ tickerlist=list(member_returns)
711
+
712
+ #合成投资组合的历史收益率,按行横向加权求和
713
+ preturns=member_returns.copy() #避免改变输入的数据
714
+ preturns['Portfolio']=preturns.mul(portfolio_weights,axis=1).sum(axis=1)
715
+
716
+ #计算一手投资组合的价格,最小持股份额的股票需要100股
717
+ import numpy as np
718
+ min_weight=np.min(portfolio_weights)
719
+ # 将最少持股的股票份额转换为1
720
+ portfolio_weights_1=portfolio_weights / min_weight * 1
721
+ portfolio_values=member_prices.mul(portfolio_weights_1,axis=1).sum(axis=1)
722
+ portfolio_value_thedate=portfolio_values[-1:].values[0]
723
+
724
+ #计算年化收益率:按列求均值,需要有选项:滚动的年化收益率或月度收益率?
725
+ mean_return=preturns['Portfolio'].mean(axis=0)
726
+ annual_return = (1 + mean_return)**252 - 1
727
+
728
+ #计算年化标准差
729
+ std_return=preturns['Portfolio'].std(axis=0)
730
+ import numpy as np
731
+ annual_std = std_return*np.sqrt(252)
732
+
733
+ lang=check_language()
734
+ import datetime as dt; stoday=dt.date.today()
735
+ if lang == 'Chinese':
736
+ print("\n ======= 投资组合的收益与风险 =======")
737
+ print(" 投资组合:",pname)
738
+ print(" 分析日期:",str(hend))
739
+ # 投资组合中即使持股比例最低的股票每次交易最少也需要1手(100股)
740
+ print(" 1手组合单位价值:","约"+str(round(portfolio_value_thedate/10000*100,2))+"万")
741
+ print(" 观察期间:",hstart+'至'+hend)
742
+ print(" 年化收益率:",round(annual_return,4))
743
+ print(" 年化标准差:",round(annual_std,4))
744
+ print(" ***投资组合持仓策略***")
745
+ print_tickerlist_sharelist(tickerlist,portfolio_weights,leading_blanks=4,ticker_type=ticker_type)
746
+
747
+ print(" *数据来源:Sina/EM/Stooq/Yahoo,"+str(stoday)+"统计")
748
+ else:
749
+ print("\n ======= Investment Portfolio: Return and Risk =======")
750
+ print(" Investment portfolio:",pname)
751
+ print(" Date of analysis:",str(hend))
752
+ print(" Value of portfolio:","about "+str(round(portfolio_value_thedate/1000,2))+"K/portfolio unit")
753
+ print(" Period of sample:",hstart+' to '+hend)
754
+ print(" Annualized return:",round(annual_return,4))
755
+ print(" Annualized std of return:",round(annual_std,4))
756
+ print(" ***Portfolio Constructing Strategy***")
757
+ print_tickerlist_sharelist(tickerlist,portfolio_weights,4)
758
+
759
+ print(" *Data source: Sina/EM/Stooq/Yahoo, "+str(stoday))
760
+
761
+ return
762
+
763
+ if __name__=='__main__':
764
+ Market={'Market':('US','^GSPC','我的组合001')}
765
+ Stocks1={'AAPL':.1,'MSFT':.13,'XOM':.09,'JNJ':.09,'JPM':.09}
766
+ Stocks2={'AMZN':.15,'GE':.08,'FB':.13,'T':.14}
767
+ portfolio=dict(Market,**Stocks1,**Stocks2)
768
+ pf_info=portfolio_expret(portfolio,'2019-12-31')
769
+
770
+ [[portfolio,thedate,member_returns,_,_],[_,portfolio_weights,_,_]]=pf_info
771
+ pname=portfolio_name(portfolio)
772
+
773
+ portfolio_expectation2(pname,member_returns, portfolio_weights)
774
+
775
+ #==============================================================================
776
+ def portfolio_expectation(pname,pf_info,portfolio_weights,ticker_type):
777
+ """
778
+ 功能:计算给定pf_info和持仓权重的投资组合年均收益率和标准差
779
+ 输入:投资组合名称,pf_info,投资组合权重series
780
+ 输出:年化收益率和标准差
781
+ 用途:求出持仓策略后计算投资组合的年化收益率和标准差,为外部独立使用方便
782
+ """
783
+ [[_,_,member_returns,_,member_prices],_]=pf_info
784
+
785
+ portfolio_expectation_universal(pname,member_returns,portfolio_weights,member_prices,ticker_type)
786
+
787
+ return
788
+
789
+ if __name__=='__main__':
790
+ Market={'Market':('US','^GSPC','我的组合001')}
791
+ Stocks1={'AAPL':.1,'MSFT':.13,'XOM':.09,'JNJ':.09,'JPM':.09}
792
+ Stocks2={'AMZN':.15,'GE':.08,'FB':.13,'T':.14}
793
+ portfolio=dict(Market,**Stocks1,**Stocks2)
794
+ pf_info=portfolio_expret(portfolio,'2019-12-31')
795
+
796
+ [[portfolio,thedate,member_returns,_,_],[_,portfolio_weights,_,_]]=pf_info
797
+ pname=portfolio_name(portfolio)
798
+
799
+ portfolio_expectation2(pname,member_returns, portfolio_weights)
800
+
801
+
802
+ #==============================================================================
803
+
804
+
805
+ def portfolio_ranks(portfolio_returns,pname,facecolor='papayawhip'):
806
+ """
807
+ 功能:区分中英文
808
+ """
809
+ """
810
+ lang = check_language()
811
+ if lang == 'Chinese':
812
+ df=portfolio_ranks_cn(portfolio_returns=portfolio_returns,pname=pname,facecolor=facecolor)
813
+ else:
814
+ df=portfolio_ranks_en(portfolio_returns=portfolio_returns,pname=pname)
815
+ """
816
+ df=portfolio_ranks_cn(portfolio_returns=portfolio_returns,pname=pname,facecolor=facecolor)
817
+
818
+ return df
819
+
820
+ #==============================================================================
821
+
822
+ def portfolio_ranks_cn(portfolio_returns,pname,facecolor='papayawhip'):
823
+ """
824
+ 功能:打印现有投资组合的收益率、标准差排名,收益率降序,标准差升序,中文/英文
825
+ """
826
+ #临时保存,避免影响原值
827
+ pr=portfolio_returns.copy()
828
+
829
+ #统一核定小数位数
830
+ ndecimals=2
831
+
832
+ #以pname组合作为基准
833
+ import numpy as np
834
+ mean_return_pname=pr[pname].mean(axis=0)
835
+ annual_return_pname=round(((1 + mean_return_pname)**252 - 1)*100,ndecimals)
836
+ """
837
+ if annual_return_pname > 0:
838
+ pct_style=True #百分比模式
839
+ else: #数值模式,直接加减
840
+ pct_style=False
841
+ """
842
+ pct_style=False
843
+
844
+ std_return_pname=pr[pname].std(axis=0)
845
+ annual_std_pname= round((std_return_pname*np.sqrt(252))*100,ndecimals)
846
+
847
+ import pandas as pd
848
+ #prr=pd.DataFrame(columns=["名称","年化收益率","收益率变化","年化标准差","标准差变化","收益/风险"])
849
+ #prr=pd.DataFrame(columns=["名称","年化收益率%","收益率变化","年化标准差%","标准差变化","收益/风险"])
850
+ prr=pd.DataFrame(columns=["名称","年化收益率%","收益率变化","年化标准差%","标准差变化","收益率/标准差"])
851
+ cols=list(pr)
852
+ for c in cols:
853
+
854
+ #年化收益率:按列求均值
855
+ mean_return=pr[c].mean(axis=0)
856
+ annual_return = round(((1 + mean_return)**252 - 1)*100,ndecimals)
857
+
858
+ if pct_style:
859
+ return_chg=round((annual_return - annual_return_pname) / annual_return_pname * 100,ndecimals)
860
+ else:
861
+ return_chg=round((annual_return - annual_return_pname),ndecimals)
862
+
863
+ #收益率变化
864
+ if return_chg==0:
865
+ return_chg_str=text_lang("基准","Benchmark")
866
+ elif return_chg > 0:
867
+ if pct_style:
868
+ return_chg_str='+'+str(return_chg)+'%'
869
+ else:
870
+ return_chg_str='+'+str(return_chg)
871
+ else:
872
+ if pct_style:
873
+ return_chg_str='-'+str(-return_chg)+'%'
874
+ else:
875
+ return_chg_str='-'+str(-return_chg)
876
+
877
+ #年化标准差
878
+ std_return=pr[c].std(axis=0)
879
+ annual_std = round((std_return*np.sqrt(252))*100,ndecimals)
880
+
881
+ #sharpe_ratio=round(annual_return / annual_std,2)
882
+ sharpe_ratio=round((annual_return) / annual_std,ndecimals)
883
+
884
+ if pct_style:
885
+ std_chg=round((annual_std - annual_std_pname) / annual_std_pname * 100,ndecimals)
886
+ else:
887
+ std_chg=round((annual_std - annual_std_pname),ndecimals)
888
+
889
+ #标准差变化
890
+ if std_chg==0:
891
+ std_chg_str=text_lang("基准","Benchmark")
892
+ elif std_chg > 0:
893
+ if pct_style:
894
+ std_chg_str='+'+str(std_chg)+'%'
895
+ else:
896
+ std_chg_str='+'+str(std_chg)
897
+ else:
898
+ if pct_style:
899
+ std_chg_str='-'+str(-std_chg)+'%'
900
+ else:
901
+ std_chg_str='-'+str(-std_chg)
902
+
903
+ row=pd.Series({"名称":c,"年化收益率%":annual_return, \
904
+ "收益率变化":return_chg_str, \
905
+ "年化标准差%":annual_std,"标准差变化":std_chg_str,"收益率/标准差":sharpe_ratio})
906
+ try:
907
+ prr=prr.append(row,ignore_index=True)
908
+ except:
909
+ prr=prr._append(row,ignore_index=True)
910
+
911
+ #先按风险降序排名,高者排前面
912
+ prr.sort_values(by="年化标准差%",ascending=False,inplace=True)
913
+ prr.reset_index(inplace=True)
914
+ prr['风险排名']=prr.index+1
915
+
916
+ #再按收益降序排名,高者排前面
917
+ prr.sort_values(by="年化收益率%",ascending=False,inplace=True)
918
+ prr.reset_index(inplace=True)
919
+ prr['收益排名']=prr.index+1
920
+
921
+ #prr2=prr[["名称","收益排名","风险排名","年化收益率","年化标准差","收益率变化","标准差变化","收益/风险"]]
922
+ prr2=prr[["名称","收益排名","年化收益率%","收益率变化", \
923
+ "风险排名","年化标准差%","标准差变化", \
924
+ "收益率/标准差"]]
925
+ prr2.sort_values(by="年化收益率%",ascending=False,inplace=True)
926
+ #prr2.reset_index(inplace=True)
927
+
928
+ #打印
929
+ """
930
+ print("\n========= 投资组合策略排名:平衡收益与风险 =========\n")
931
+ #打印对齐
932
+ pd.set_option('display.max_columns', 1000)
933
+ pd.set_option('display.width', 1000)
934
+ pd.set_option('display.max_colwidth', 1000)
935
+ pd.set_option('display.unicode.ambiguous_as_wide', True)
936
+ pd.set_option('display.unicode.east_asian_width', True)
937
+
938
+ #print(prr2.to_string(index=False,header=False))
939
+ #print(prr2.to_string(index=False))
940
+
941
+ alignlist=['left']+['center']*(len(list(prr2))-2)+['right']
942
+ print(prr2.to_markdown(index=False,tablefmt='plain',colalign=alignlist))
943
+ """
944
+ #一点改造
945
+ print('') #空一行
946
+ prr2.index=prr2.index + 1
947
+ prr2.rename(columns={'名称':'投资组合名称/策略'},inplace=True)
948
+ for c in list(prr2):
949
+ try:
950
+ prr2[c]=prr2[c].apply(lambda x: str(round(x,4)) if isinstance(x,float) else str(x))
951
+ except: pass
952
+
953
+ titletxt=text_lang('投资组合策略排名:平衡收益与风险','Investment Portfolio Strategies: Performance, Balancing Return and Risk')
954
+ """
955
+ dispt=prr2.style.set_caption(titletxt).set_table_styles(
956
+ [{'selector':'caption',
957
+ 'props':[('color','black'),('font-size','16px'),('font-weight','bold')]}])
958
+ dispf=dispt.set_properties(**{'text-align':'center'})
959
+
960
+ from IPython.display import display
961
+ display(dispf)
962
+ """
963
+
964
+ prr2.rename(columns={"投资组合名称/策略":text_lang("投资组合名称/策略","Strategy"), \
965
+ "收益排名":text_lang("收益排名","Return#"), \
966
+ "年化收益率%":text_lang("年化收益率%","pa Return%"), \
967
+ "收益率变化":text_lang("收益率变化","Return%+/-"), \
968
+ "风险排名":text_lang("风险排名","Risk#"), \
969
+ "年化标准差%":text_lang("年化标准差%","pa Std%"), \
970
+ "标准差变化":text_lang("标准差变化","Std%+/-"), \
971
+ "收益率/标准差":text_lang("收益/风险性价比","Return/Std")}, \
972
+ inplace=True)
973
+
974
+ #重新排名:相同的值赋予相同的序号
975
+ prr2[text_lang("年化收益率%","pa Return%")]=prr2[text_lang("年化收益率%","pa Return%")].apply(lambda x: round(float(x),ndecimals))
976
+ prr2[text_lang("收益排名","Return#")]=prr2[text_lang("年化收益率%","pa Return%")].rank(ascending=False,method='dense')
977
+ prr2[text_lang("收益排名","Return#")]=prr2[text_lang("收益排名","Return#")].apply(lambda x: int(x))
978
+
979
+ prr2[text_lang("年化标准差%","pa Std%")]=prr2[text_lang("年化标准差%","pa Std%")].apply(lambda x: round(float(x),ndecimals))
980
+ prr2[text_lang("风险排名","Risk#")]=prr2[text_lang("年化标准差%","pa Std%")].rank(ascending=False,method='dense')
981
+ prr2[text_lang("风险排名","Risk#")]=prr2[text_lang("风险排名","Risk#")].apply(lambda x: int(x))
982
+
983
+ prr2[text_lang("收益/风险性价比","Return/Std")]=prr2[text_lang("收益/风险性价比","Return/Std")].apply(lambda x: round(float(x),ndecimals))
984
+ prr2[text_lang("性价比排名","Ret/Std#")]=prr2[text_lang("收益/风险性价比","Return/Std")].rank(ascending=False,method='dense')
985
+ prr2[text_lang("性价比排名","Ret/Std#")]=prr2[text_lang("性价比排名","Ret/Std#")].apply(lambda x: int(x))
986
+
987
+ df_display_CSS(prr2,titletxt=titletxt,footnote='',facecolor='papayawhip',decimals=ndecimals, \
988
+ first_col_align='left',second_col_align='center', \
989
+ last_col_align='center',other_col_align='center', \
990
+ titile_font_size='15px',heading_font_size='13px', \
991
+ data_font_size='13px')
992
+
993
+ """
994
+ print(' ') #空一行
995
+
996
+ disph=prr2.style.hide() #不显示索引列
997
+ dispp=disph.format(precision=2) #设置带有小数点的列精度调整为小数点后2位
998
+ #设置标题/列名
999
+ dispt=dispp.set_caption(titletxt).set_table_styles(
1000
+ [{'selector':'caption', #设置标题属性
1001
+ 'props':[('color','black'),('font-size','18px'),('font-weight','bold')]}, \
1002
+ {'selector':'th.col_heading', #设置列名属性
1003
+ 'props':[('color','black'),('font-size','17px'),('background-color',facecolor),('text-align','center'),('margin','auto')]}])
1004
+ #设置列数值对齐
1005
+ dispt1=dispt.set_properties(**{'font-size':'17px'})
1006
+ dispf=dispt1.set_properties(**{'text-align':'center'})
1007
+ #设置前景背景颜色
1008
+ try:
1009
+ dispf2=dispf.set_properties(**{'background-color':facecolor,'color':'black'})
1010
+ except:
1011
+ print(" #Warning(portfolio_ranks_cn): color",facecolor,"is unsupported, changed to default setting")
1012
+ dispf2=dispf.set_properties(**{'background-color':'papayawhip','color':'black'})
1013
+
1014
+ from IPython.display import display
1015
+ display(dispf2)
1016
+
1017
+ print('') #空一行
1018
+ """
1019
+ return prr2
1020
+
1021
+ if __name__=='__main__':
1022
+ portfolio_ranks(portfolio_returns,pname)
1023
+
1024
+ #==============================================================================
1025
+
1026
+ def portfolio_ranks_en(portfolio_returns,pname):
1027
+ """
1028
+ 功能:打印现有投资组合的收益率、标准差排名,收益率降序,标准差升序,英文
1029
+ 废弃!!!
1030
+ """
1031
+ #临时保存,避免影响原值
1032
+ pr=portfolio_returns.copy()
1033
+
1034
+ #以pname组合作为基准
1035
+ import numpy as np
1036
+ mean_return_pname=pr[pname].mean(axis=0)
1037
+ annual_return_pname=(1 + mean_return_pname)**252 - 1
1038
+ if annual_return_pname > 0:
1039
+ pct_style=True
1040
+ else:
1041
+ pct_style=False
1042
+
1043
+ std_return_pname=pr[pname].std(axis=0)
1044
+ annual_std_pname= std_return_pname*np.sqrt(252)
1045
+
1046
+ import pandas as pd
1047
+ prr=pd.DataFrame(columns=["Portfolio","Annualized Return","Change of Return","Annualized Std","Change of Std","Return/Risk"])
1048
+ cols=list(pr)
1049
+ for c in cols:
1050
+ #计算年化收益率:按列求均值
1051
+ mean_return=pr[c].mean(axis=0)
1052
+ annual_return = (1 + mean_return)**252 - 1
1053
+
1054
+ if pct_style:
1055
+ return_chg=round((annual_return - annual_return_pname) / annual_return_pname *100,1)
1056
+ else:
1057
+ return_chg=round((annual_return - annual_return_pname),5)
1058
+
1059
+ if return_chg==0:
1060
+ return_chg_str="base"
1061
+ elif return_chg > 0:
1062
+ if pct_style:
1063
+ return_chg_str='+'+str(return_chg)+'%'
1064
+ else:
1065
+ return_chg_str='+'+str(return_chg)
1066
+ else:
1067
+ if pct_style:
1068
+ return_chg_str='-'+str(-return_chg)+'%'
1069
+ else:
1070
+ return_chg_str='-'+str(-return_chg)
1071
+
1072
+ #计算年化标准差
1073
+ std_return=pr[c].std(axis=0)
1074
+ annual_std = std_return*np.sqrt(252)
1075
+
1076
+ sharpe_ratio=round(annual_return / annual_std,4)
1077
+
1078
+ if pct_style:
1079
+ std_chg=round((annual_std - annual_std_pname) / annual_std_pname *100,4)
1080
+ else:
1081
+ std_chg=round((annual_std - annual_std_pname),4)
1082
+ if std_chg==0:
1083
+ std_chg_str="base"
1084
+ elif std_chg > 0:
1085
+ if pct_style:
1086
+ std_chg_str='+'+str(std_chg)+'%'
1087
+ else:
1088
+ std_chg_str='+'+str(std_chg)
1089
+ else:
1090
+ if pct_style:
1091
+ std_chg_str='-'+str(-std_chg)+'%'
1092
+ else:
1093
+ std_chg_str='-'+str(-std_chg)
1094
+
1095
+ row=pd.Series({"Portfolio":c,"Annualized Return":annual_return,"Change of Return":return_chg_str, \
1096
+ "Annualized Std":annual_std,"Change of Std":std_chg_str,"Return/Risk":sharpe_ratio})
1097
+ try:
1098
+ prr=prr.append(row,ignore_index=True)
1099
+ except:
1100
+ prr=prr._append(row,ignore_index=True)
1101
+
1102
+ #处理小数位数,以便与其他地方的小数位数一致
1103
+ prr['Annualized Return']=round(prr['Annualized Return'],4)
1104
+ prr['Annualized Std']=round(prr['Annualized Std'],4)
1105
+
1106
+ #先按风险降序排名,高者排前面
1107
+ prr.sort_values(by="Annualized Std",ascending=False,inplace=True)
1108
+ prr.reset_index(inplace=True)
1109
+ prr['Risk Rank']=prr.index+1
1110
+
1111
+ #再按收益降序排名,高者排前面
1112
+ prr.sort_values(by="Annualized Return",ascending=False,inplace=True)
1113
+ prr.reset_index(inplace=True)
1114
+ prr['Return Rank']=prr.index+1
1115
+
1116
+ prr2=prr[["Portfolio","Return Rank","Risk Rank","Annualized Return","Annualized Std","Change of Return","Change of Std","Return/Risk"]]
1117
+ prr2.sort_values(by="Annualized Return",ascending=False,inplace=True)
1118
+ #prr2.reset_index(inplace=True)
1119
+
1120
+ #打印
1121
+ print("\n========= Investment Portfolio Strategy Ranking: Balancing Return & Risk =========\n")
1122
+ #打印对齐
1123
+ pd.set_option('display.max_columns', 1000)
1124
+ pd.set_option('display.width', 1000)
1125
+ pd.set_option('display.max_colwidth', 1000)
1126
+ pd.set_option('display.unicode.ambiguous_as_wide', True)
1127
+ pd.set_option('display.unicode.east_asian_width', True)
1128
+
1129
+ #print(prr2.to_string(index=False,header=False))
1130
+ print(prr2.to_string(index=False))
1131
+
1132
+ return prr2
1133
+
1134
+ #==============================================================================
1135
+ if __name__=='__main__':
1136
+ #Define market information and name of the portfolio: Banking #1
1137
+ Market={'Market':('China','000300.SS','Banking #1')}
1138
+ #First batch of component stocks
1139
+ Stocks1={'601939.SS':.3,#CCB Bank
1140
+ '600000.SS':.3, #SPDB Bank
1141
+ '600036.SS':.2, #CMB Bank
1142
+ '601166.SS':.2,#Industrial Bank
1143
+ }
1144
+ portfolio=dict(Market,**Stocks1)
1145
+
1146
+ pf_info=portfolio_build(portfolio,thedate='2024-7-17')
1147
+
1148
+ simulation=50000
1149
+ convex_hull=True; frontier="both"; facecolor='papayawhip'
1150
+
1151
+ portfolio_eset(pf_info,simulation=50000)
1152
+
1153
+ def portfolio_feset(pf_info,simulation=10000,convex_hull=True,frontier="both",facecolor='papayawhip'):
1154
+ """
1155
+ 功能:套壳函数portfolio_eset
1156
+ 当frontier不在列表['efficient','inefficient','both']中时,绘制可行集
1157
+ 当frontier == 'efficient'时绘制有效边界
1158
+ 当frontier == 'inefficient'时绘制无效边界
1159
+ 当frontier == 'both'时同时绘制有效边界和无效边界
1160
+ 当绘制有效/无效边界时,默认使用凸包绘制(convex_hull=True)
1161
+ 注:若可行集形状不佳,首先尝试pastyears=3,再尝试增加simulation数量
1162
+ """
1163
+ if frontier is None:
1164
+ convex_hull=False
1165
+ elif isinstance(frontier,str):
1166
+ frontier=frontier.lower()
1167
+
1168
+ frontier_list=['efficient','inefficient','both']
1169
+ if not any(element in frontier for element in frontier_list):
1170
+ convex_hull=False
1171
+ else:
1172
+ convex_hull=True
1173
+ else:
1174
+ convex_hull=False
1175
+
1176
+ results=portfolio_eset(pf_info,simulation=simulation,convex_hull=convex_hull,frontier=frontier,facecolor=facecolor)
1177
+
1178
+ return results
1179
+
1180
+
1181
+ def portfolio_eset(pf_info,simulation=50000,convex_hull=False,frontier="both",facecolor='papayawhip'):
1182
+ """
1183
+ 功能:基于随机数,生成大量可能的投资组合,计算各个投资组合的年均收益率和标准差,绘制投资组合的可行集
1184
+ 默认绘制散点图凸包:convex_hull=True
1185
+ """
1186
+ DEBUG=True; MORE_DETAIL=False
1187
+
1188
+ frontier_list=['efficient','inefficient','both']
1189
+ if isinstance(frontier,str):
1190
+ if any(element in frontier for element in frontier_list):
1191
+ efficient_set=True
1192
+ else:
1193
+ efficient_set=False
1194
+ else:
1195
+ efficient_set=False
1196
+
1197
+ [[portfolio,thedate,stock_return,_,_],_]=pf_info
1198
+ pname=portfolio_name(portfolio)
1199
+ _,_,tickerlist,_,ticker_type=decompose_portfolio(portfolio)
1200
+
1201
+ #取出观察期
1202
+ hstart0=stock_return.index[0]; hstart=str(hstart0.strftime("%Y-%m-%d"))
1203
+ hend0=stock_return.index[-1]; hend=str(hend0.strftime("%Y-%m-%d"))
1204
+
1205
+ #获得成份股个数
1206
+ numstocks=len(tickerlist)
1207
+
1208
+ # 设置空的numpy数组,用于存储每次模拟得到的成份股权重、投资组合的收益率和标准差
1209
+ import numpy as np
1210
+ random_p = np.empty((simulation,numstocks+2))
1211
+ # 设置随机数种子,这里是为了结果可重复
1212
+ np.random.seed(RANDOM_SEED)
1213
+
1214
+ # 循环模拟n次随机的投资组合
1215
+ print(" Calculating portfolio feasible set, please wait ...")
1216
+ for i in range(simulation):
1217
+ # 生成numstocks个随机数,并归一化,得到一组随机的权重数据
1218
+ random9 = np.random.random(numstocks)
1219
+ random_weight = random9 / np.sum(random9)
1220
+
1221
+ # 计算随机投资组合的年化平均收益率
1222
+ mean_return=stock_return.mul(random_weight,axis=1).sum(axis=1).mean(axis=0)
1223
+ annual_return = (1 + mean_return)**252 - 1
1224
+
1225
+ # 计算随机投资组合的年化平均标准差
1226
+ std_return=stock_return.mul(random_weight,axis=1).sum(axis=1).std(axis=0)
1227
+ annual_std = std_return*np.sqrt(252)
1228
+
1229
+ # 将上面生成的权重,和计算得到的收益率、标准差存入数组random_p中
1230
+ # 数组矩阵的前numstocks为随机权重,其后为年均收益率,再后为年均标准差
1231
+ random_p[i][:numstocks] = random_weight
1232
+ random_p[i][numstocks] = annual_return
1233
+ random_p[i][numstocks+1] = annual_std
1234
+
1235
+ #显示完成进度
1236
+ print_progress_percent(i,simulation,steps=10,leading_blanks=2)
1237
+
1238
+ # 将numpy数组转化成DataFrame数据框
1239
+ import pandas as pd
1240
+ RandomPortfolios = pd.DataFrame(random_p)
1241
+ # 设置数据框RandomPortfolios每一列的名称
1242
+ RandomPortfolios.columns = [ticker + "_weight" for ticker in tickerlist] \
1243
+ + ['Returns', 'Volatility']
1244
+
1245
+ # 绘制散点图
1246
+ """
1247
+ RandomPortfolios.plot('Volatility','Returns',kind='scatter',color='y',edgecolors='k')
1248
+ """
1249
+ #RandomPortfolios['Returns_Volatility']=RandomPortfolios['Returns'] / RandomPortfolios['Volatility']
1250
+ #pf_ratio = np.array(RandomPortfolios['Returns_Volatility'])
1251
+ pf_ratio = np.array(RandomPortfolios['Returns'] / RandomPortfolios['Volatility'])
1252
+ pf_returns = np.array(RandomPortfolios['Returns'])
1253
+ pf_volatilities = np.array(RandomPortfolios['Volatility'])
1254
+
1255
+ #plt.style.use('seaborn-dark') #不支持中文
1256
+ #plt.figure(figsize=(12.8,6.4))
1257
+ plt.scatter(pf_volatilities,pf_returns,c=pf_ratio,cmap='RdYlGn',edgecolors='black',marker='o')
1258
+ #plt.grid(True)
1259
+
1260
+ #绘制散点图轮廓线凸包(convex hull)
1261
+ if convex_hull:
1262
+ print(" Calculating convex hull ...")
1263
+
1264
+ from scipy.spatial import ConvexHull
1265
+
1266
+ #构造散点对的列表
1267
+ pf_volatilities_list=list(pf_volatilities)
1268
+ pf_returns_list=list(pf_returns)
1269
+ points=[]
1270
+ for x in pf_volatilities_list:
1271
+ pos=pf_volatilities_list.index(x)
1272
+ y=pf_returns_list[pos]
1273
+ points=points+[[x,y]]
1274
+
1275
+ #寻找最左侧的坐标:在x最小的同时,y要最大
1276
+ points_df = pd.DataFrame(points, columns=['x', 'y'])
1277
+ points_df.sort_values(by=['x','y'],ascending=[True,False],inplace=True)
1278
+ x1,y1=points_df.head(1).values[0]
1279
+ if DEBUG and MORE_DETAIL:
1280
+ print("\n*** Leftmost point (x1,y1):",x1,y1)
1281
+
1282
+ #寻找最高点的坐标:在y最大的同时,x要最小
1283
+ points_df.sort_values(by=['y','x'],ascending=[False,True],inplace=True)
1284
+ x2,y2=points_df.head(1).values[0]
1285
+ if DEBUG and MORE_DETAIL:
1286
+ print("*** Highest point (x2,y2):",x2,y2)
1287
+
1288
+ if DEBUG:
1289
+ plt.plot([x1,x2],[y1,y2],ls=':',lw=2,alpha=0.5)
1290
+
1291
+ #建立最左侧和最高点之间的拟合直线方程y=a+bx
1292
+ a=(x1*y2-x2*y1)/(x1-x2); b=(y1-y2)/(x1-x2)
1293
+ def y_bar(x_bar):
1294
+ return a+b*x_bar
1295
+
1296
+ # 计算散点集的外轮廓
1297
+ hull = ConvexHull(points)
1298
+
1299
+ # 绘制外轮廓线
1300
+ firsttime_efficient=True; firsttime_inefficient=True
1301
+ for simplex in hull.simplices:
1302
+ #p1中是一条线段起点和终点的横坐标
1303
+ p1=[points[simplex[0]][0], points[simplex[1]][0]]
1304
+ px1=p1[0];px2=p1[1]
1305
+ #p2中是一条线段起点和终点的纵坐标
1306
+ p2=[points[simplex[0]][1], points[simplex[1]][1]]
1307
+ py1=p2[0]; py2=p2[1]
1308
+
1309
+ if DEBUG and MORE_DETAIL:
1310
+ print("\n*** Hull line start (px1,py1):",px1,py1)
1311
+ print("*** Hull line end (px2,py2):",px2,py2)
1312
+
1313
+ """
1314
+ plt.plot([points[simplex[0]][0], points[simplex[1]][0]],
1315
+ [points[simplex[0]][1], points[simplex[1]][1]], 'k-.')
1316
+ """
1317
+
1318
+ #线段起点:px1,py1;线段终点:px2,py2
1319
+ if DEBUG and MORE_DETAIL:
1320
+ is_efficient=(py1>=y_bar(px1) or py1==y1) and (py2>=y_bar(px2) or py2==y2)
1321
+ print("\n*** is_efficient:",is_efficient)
1322
+ print("py1=",py1,"y_bar1",y_bar(px1),"y1=",y1,"py2=",py2,"ybar2=",y_bar(px2),"y2=",y2)
1323
+ if px1==x1 and py1==y1:
1324
+ print("====== This is the least risk point !")
1325
+ if px2==x2 and py2==y2:
1326
+ print("====== This is the highest return point !")
1327
+
1328
+ #坐标对[px1,py1]既可能作为开始点,也可能作为结束点,[px2,py2]同样
1329
+ if ((py1>=y_bar(px1) or py1==y1) and (py2>=y_bar(px2) or py2==y2)) or \
1330
+ ((py1>=y_bar(px2) or py1==y2) and (py2>=y_bar(px1) or py2==y1)):
1331
+
1332
+ #有效边界
1333
+ if frontier.lower() in ['both','efficient']:
1334
+ if firsttime_efficient:
1335
+ plt.plot(p1,p2, 'r--',label=text_lang("有效边界","Efficient Frontier"),lw=3,alpha=0.5)
1336
+ firsttime_efficient=False
1337
+ else:
1338
+ plt.plot(p1,p2, 'r--',lw=3,alpha=0.5)
1339
+ else:
1340
+ pass
1341
+ else:
1342
+ #其余边沿
1343
+ if frontier.lower() in ['both','inefficient']:
1344
+ if firsttime_inefficient:
1345
+ plt.plot(p1,p2, 'k-.',label=text_lang("无效边界","Inefficient Frontier"),alpha=0.5)
1346
+ firsttime_inefficient=False
1347
+ else:
1348
+ plt.plot(p1,p2, 'k-.',alpha=0.5)
1349
+ else:
1350
+ pass
1351
+ else:
1352
+ pass
1353
+
1354
+ # 空一行
1355
+ print('')
1356
+
1357
+
1358
+ import datetime as dt; stoday=dt.date.today()
1359
+ lang = check_language()
1360
+ if lang == 'Chinese':
1361
+ if pname == '': pname='投资组合'
1362
+
1363
+ plt.colorbar(label='收益率/标准差')
1364
+
1365
+ if efficient_set:
1366
+ if frontier == 'efficient':
1367
+ titletxt0=": 马科维茨有效集(有效边界)"
1368
+ elif frontier == 'inefficient':
1369
+ titletxt0=": 马科维茨无效集(无效边界)"
1370
+ elif frontier == 'both':
1371
+ titletxt0=": 马科维茨有效边界与无效边界"
1372
+ else:
1373
+ titletxt0=": 马科维茨可行集"
1374
+ else:
1375
+ titletxt0=": 马科维茨可行集"
1376
+
1377
+ plt.title(pname+titletxt0,fontsize=title_txt_size)
1378
+ plt.ylabel("年化收益率",fontsize=ylabel_txt_size)
1379
+
1380
+ footnote1="年化收益率标准差-->"
1381
+ footnote2="\n\n基于给定的成份证券构造"+str(simulation)+"个投资组合"
1382
+ footnote3="\n观察期间:"+hstart+"至"+hend
1383
+ footnote4="\n数据来源: Sina/EM/Stooq/Yahoo, "+str(stoday)
1384
+ else:
1385
+ if pname == '': pname='Investment Portfolio'
1386
+
1387
+ if efficient_set:
1388
+ if frontier == 'efficient':
1389
+ titletxt0=": Markowitz Efficient Set (Efficient Frontier)"
1390
+ elif frontier == 'inefficient':
1391
+ titletxt0=": Markowitz Inefficient Set (Inefficient Frontier)"
1392
+ elif frontier == 'both':
1393
+ titletxt0=": Markowitz Efficient & Inefficient Frontier"
1394
+ else:
1395
+ titletxt0=": Markowitz Feasible Set"
1396
+ else:
1397
+ titletxt0=": Markowitz Feasible Set"
1398
+
1399
+ plt.colorbar(label='Return/Std')
1400
+ plt.title(pname+titletxt0,fontsize=title_txt_size)
1401
+ plt.ylabel("Annualized Return",fontsize=ylabel_txt_size)
1402
+
1403
+ footnote1="Annualized Std -->\n\n"
1404
+ footnote2="Built "+str(simulation)+" portfolios of given securities\n"
1405
+ footnote3="Period of sample: "+hstart+" to "+hend
1406
+ footnote4="\nData source: Sina/EM/Stooq/Yahoo, "+str(stoday)
1407
+
1408
+ plt.xlabel(footnote1+footnote2+footnote3+footnote4,fontsize=xlabel_txt_size)
1409
+
1410
+ plt.gca().set_facecolor(facecolor)
1411
+ if efficient_set:
1412
+ plt.legend(loc='best')
1413
+ plt.show()
1414
+
1415
+ return [pf_info,RandomPortfolios]
1416
+
1417
+ if __name__=='__main__':
1418
+ Market={'Market':('US','^GSPC','我的组合001')}
1419
+ Stocks1={'AAPL':.1,'MSFT':.13,'XOM':.09,'JNJ':.09,'JPM':.09}
1420
+ Stocks2={'AMZN':.15,'GE':.08,'FB':.13,'T':.14}
1421
+ portfolio=dict(Market,**Stocks1,**Stocks2)
1422
+ pf_info=portfolio_expret(portfolio,'2019-12-31')
1423
+
1424
+ es=portfolio_eset(pf_info,simulation=50000)
1425
+
1426
+ #==============================================================================
1427
+ if __name__=='__main__':
1428
+ simulation=1000
1429
+ rate_period='1Y'
1430
+ rate_type='treasury'
1431
+
1432
+ def portfolio_es_sharpe(pf_info,simulation=50000,RF=0):
1433
+ """
1434
+ 功能:基于随机数,生成大量可能的投资组合,计算各个投资组合的年均风险溢价及其标准差,绘制投资组合的可行集
1435
+ """
1436
+ print(" Calculating possible portfolio combinations, please wait ...")
1437
+
1438
+ [[portfolio,thedate,stock_return0,rf_df,_],_]=pf_info
1439
+ pname=portfolio_name(portfolio)
1440
+ scope,_,tickerlist,_,ticker_type=decompose_portfolio(portfolio)
1441
+
1442
+ #取出观察期
1443
+ hstart0=stock_return0.index[0]; hstart=str(hstart0.strftime("%Y-%m-%d"))
1444
+ hend0=stock_return0.index[-1]; hend=str(hend0.strftime("%Y-%m-%d"))
1445
+
1446
+ import pandas as pd
1447
+ #处理无风险利率
1448
+ """
1449
+ if RF:
1450
+ #rf_df=get_rf_daily(hstart,hend,scope,rate_period,rate_type)
1451
+ if not (rf_df is None):
1452
+ stock_return1=pd.merge(stock_return0,rf_df,how='inner',left_index=True,right_index=True)
1453
+ for t in tickerlist:
1454
+ #计算风险溢价
1455
+ stock_return1[t]=stock_return1[t]-stock_return1['rf_daily']
1456
+
1457
+ stock_return=stock_return1[tickerlist]
1458
+ else:
1459
+ print(" #Error(portfolio_es_sharpe): failed to retrieve risk-free interest rate, please try again")
1460
+ return None
1461
+ else:
1462
+ #不考虑RF
1463
+ stock_return=stock_return0
1464
+ """
1465
+ rf_daily=RF/365
1466
+ for t in tickerlist:
1467
+ #计算风险溢价
1468
+ stock_return0[t]=stock_return0[t]-rf_daily
1469
+ stock_return=stock_return0[tickerlist]
1470
+
1471
+ #获得成份股个数
1472
+ numstocks=len(tickerlist)
1473
+
1474
+ # 设置空的numpy数组,用于存储每次模拟得到的成份股权重、组合的收益率和标准差
1475
+ import numpy as np
1476
+ random_p = np.empty((simulation,numstocks+2))
1477
+ # 设置随机数种子,这里是为了结果可重复
1478
+ np.random.seed(RANDOM_SEED)
1479
+
1480
+ # 循环模拟n次随机的投资组合
1481
+ for i in range(simulation):
1482
+ # 生成numstocks个随机数,并归一化,得到一组随机的权重数据
1483
+ random9 = np.random.random(numstocks)
1484
+ random_weight = random9 / np.sum(random9)
1485
+
1486
+ # 计算随机投资组合的年化平均收益率
1487
+ mean_return=stock_return.mul(random_weight,axis=1).sum(axis=1).mean(axis=0)
1488
+ annual_return = (1 + mean_return)**252 - 1
1489
+
1490
+ # 计算随机投资组合的年化平均标准差
1491
+ std_return=stock_return.mul(random_weight,axis=1).sum(axis=1).std(axis=0)
1492
+ annual_std = std_return*np.sqrt(252)
1493
+
1494
+ # 将上面生成的权重,和计算得到的收益率、标准差存入数组random_p中
1495
+ # 数组矩阵的前numstocks为随机权重,其后为年均收益率,再后为年均标准差
1496
+ random_p[i][:numstocks] = random_weight
1497
+ random_p[i][numstocks] = annual_return
1498
+ random_p[i][numstocks+1] = annual_std
1499
+
1500
+ #显示完成进度
1501
+ print_progress_percent(i,simulation,steps=10,leading_blanks=2)
1502
+
1503
+ # 将numpy数组转化成DataFrame数据框
1504
+ RandomPortfolios = pd.DataFrame(random_p)
1505
+ # 设置数据框RandomPortfolios每一列的名称
1506
+ RandomPortfolios.columns = [ticker + "_weight" for ticker in tickerlist] \
1507
+ + ['Risk premium', 'Risk premium volatility']
1508
+
1509
+ return [pf_info,RandomPortfolios]
1510
+
1511
+ if __name__=='__main__':
1512
+ Market={'Market':('US','^GSPC','我的组合001')}
1513
+ Stocks1={'AAPL':.1,'MSFT':.13,'XOM':.09,'JNJ':.09,'JPM':.09}
1514
+ Stocks2={'AMZN':.15,'GE':.08,'FB':.13,'T':.14}
1515
+ portfolio=dict(Market,**Stocks1,**Stocks2)
1516
+ pf_info=portfolio_expret(portfolio,'2019-12-31')
1517
+
1518
+ es_sharpe=portfolio_es_sharpe(pf_info,simulation=50000)
1519
+
1520
+ #==============================================================================
1521
+ if __name__=='__main__':
1522
+ simulation=1000
1523
+ rate_period='1Y'
1524
+ rate_type='treasury'
1525
+
1526
+ def portfolio_es_sortino(pf_info,simulation=50000,RF=0):
1527
+ """
1528
+ 功能:基于随机数,生成大量可能的投资组合,计算各个投资组合的年均风险溢价及其下偏标准差,绘制投资组合的可行集
1529
+ """
1530
+ print(" Calculating possible portfolio combinations, please wait ...")
1531
+
1532
+ [[portfolio,thedate,stock_return0,rf_df,_],_]=pf_info
1533
+ pname=portfolio_name(portfolio)
1534
+ scope,_,tickerlist,_,ticker_type=decompose_portfolio(portfolio)
1535
+
1536
+ #取出观察期
1537
+ hstart0=stock_return0.index[0]; hstart=str(hstart0.strftime("%Y-%m-%d"))
1538
+ hend0=stock_return0.index[-1]; hend=str(hend0.strftime("%Y-%m-%d"))
1539
+
1540
+ import pandas as pd
1541
+ #处理无风险利率
1542
+ """
1543
+ if RF:
1544
+ #rf_df=get_rf_daily(hstart,hend,scope,rate_period,rate_type)
1545
+ if not (rf_df is None):
1546
+ stock_return1=pd.merge(stock_return0,rf_df,how='inner',left_index=True,right_index=True)
1547
+ for t in tickerlist:
1548
+ #计算风险溢价
1549
+ stock_return1[t]=stock_return1[t]-stock_return1['rf_daily']
1550
+
1551
+ stock_return=stock_return1[tickerlist]
1552
+ else:
1553
+ print(" #Error(portfolio_es_sortino): failed to retrieve risk-free interest rate, please try again")
1554
+ return None
1555
+ else:
1556
+ #不考虑RF
1557
+ stock_return=stock_return0
1558
+ """
1559
+ rf_daily=RF/365
1560
+ for t in tickerlist:
1561
+ #计算风险溢价
1562
+ stock_return0[t]=stock_return0[t]-rf_daily
1563
+ stock_return=stock_return0[tickerlist]
1564
+
1565
+ #获得成份股个数
1566
+ numstocks=len(tickerlist)
1567
+
1568
+ # 设置空的numpy数组,用于存储每次模拟得到的成份股权重、组合的收益率和标准差
1569
+ import numpy as np
1570
+ random_p = np.empty((simulation,numstocks+2))
1571
+ # 设置随机数种子,这里是为了结果可重复
1572
+ np.random.seed(RANDOM_SEED)
1573
+ # 与其他比率设置不同的随机数种子,意在产生多样性的随机组合
1574
+
1575
+ # 循环模拟n次随机的投资组合
1576
+ for i in range(simulation):
1577
+ # 生成numstocks个随机数,并归一化,得到一组随机的权重数据
1578
+ random9 = np.random.random(numstocks)
1579
+ random_weight = random9 / np.sum(random9)
1580
+
1581
+ # 计算随机投资组合的年化平均收益率
1582
+ mean_return=stock_return.mul(random_weight,axis=1).sum(axis=1).mean(axis=0)
1583
+ annual_return = (1 + mean_return)**252 - 1
1584
+
1585
+ # 计算随机投资组合的年化平均下偏标准差
1586
+ sr_temp0=stock_return.copy()
1587
+ sr_temp0['Portfolio Ret']=sr_temp0.mul(random_weight,axis=1).sum(axis=1)
1588
+ sr_temp1=sr_temp0[sr_temp0['Portfolio Ret'] < mean_return]
1589
+ sr_temp2=sr_temp1[tickerlist]
1590
+ lpsd_return=sr_temp2.mul(random_weight,axis=1).sum(axis=1).std(axis=0)
1591
+ annual_lpsd = lpsd_return*np.sqrt(252)
1592
+
1593
+ # 将上面生成的权重,和计算得到的收益率、标准差存入数组random_p中
1594
+ # 数组矩阵的前numstocks为随机权重,其后为年均收益率,再后为年均标准差
1595
+ random_p[i][:numstocks] = random_weight
1596
+ random_p[i][numstocks] = annual_return
1597
+ random_p[i][numstocks+1] = annual_lpsd
1598
+
1599
+ #显示完成进度
1600
+ print_progress_percent(i,simulation,steps=10,leading_blanks=2)
1601
+
1602
+ # 将numpy数组转化成DataFrame数据框
1603
+ RandomPortfolios = pd.DataFrame(random_p)
1604
+ # 设置数据框RandomPortfolios每一列的名称
1605
+ RandomPortfolios.columns = [ticker + "_weight" for ticker in tickerlist] \
1606
+ + ['Risk premium', 'Risk premium LPSD']
1607
+
1608
+ return [pf_info,RandomPortfolios]
1609
+
1610
+ if __name__=='__main__':
1611
+ Market={'Market':('US','^GSPC','我的组合001')}
1612
+ Stocks1={'AAPL':.1,'MSFT':.13,'XOM':.09,'JNJ':.09,'JPM':.09}
1613
+ Stocks2={'AMZN':.15,'GE':.08,'FB':.13,'T':.14}
1614
+ portfolio=dict(Market,**Stocks1,**Stocks2)
1615
+ pf_info=portfolio_expret(portfolio,'2019-12-31')
1616
+
1617
+ es_sortino=portfolio_es_sortino(pf_info,simulation=50000)
1618
+
1619
+ #==============================================================================
1620
+ #==============================================================================
1621
+ if __name__=='__main__':
1622
+ simulation=1000
1623
+ rate_period='1Y'
1624
+ rate_type='treasury'
1625
+
1626
+ def portfolio_es_alpha(pf_info,simulation=50000,RF=0):
1627
+ """
1628
+ 功能:基于随机数,生成大量可能的投资组合,计算各个投资组合的年化标准差和阿尔法指数,绘制投资组合的可行集
1629
+ """
1630
+ print(" Calculating possible portfolio combinations, please wait ...")
1631
+
1632
+ [[portfolio,thedate,stock_return0,rf_df,_],_]=pf_info
1633
+ pname=portfolio_name(portfolio)
1634
+ scope,mktidx,tickerlist,_,ticker_type=decompose_portfolio(portfolio)
1635
+
1636
+ #取出观察期
1637
+ hstart0=stock_return0.index[0]; hstart=str(hstart0.strftime("%Y-%m-%d"))
1638
+ hend0=stock_return0.index[-1]; hend=str(hend0.strftime("%Y-%m-%d"))
1639
+
1640
+ #计算市场指数的收益率
1641
+ import pandas as pd
1642
+ start1=date_adjust(hstart,adjust=-30)
1643
+ mkt=get_prices(mktidx,start1,hend)
1644
+ mkt['Mkt']=mkt['Close'].pct_change()
1645
+ mkt.dropna(inplace=True)
1646
+ mkt1=pd.DataFrame(mkt['Mkt'])
1647
+
1648
+ stock_return0m=pd.merge(stock_return0,mkt1,how='left',left_index=True,right_index=True)
1649
+ #必须舍弃空值,否则下面的回归将得不到系数!!!
1650
+ stock_return0m.dropna(inplace=True)
1651
+
1652
+ #处理期间内无风险利率
1653
+ """
1654
+ if RF:
1655
+ #rf_df=get_rf_daily(hstart,hend,scope,rate_period,rate_type)
1656
+ if not (rf_df is None):
1657
+ stock_return1=pd.merge(stock_return0m,rf_df,how='inner',left_index=True,right_index=True)
1658
+ for t in tickerlist:
1659
+ #计算风险溢价
1660
+ stock_return1[t]=stock_return1[t]-stock_return1['rf_daily']
1661
+
1662
+ stock_return1['Mkt']=stock_return1['Mkt']-stock_return1['rf_daily']
1663
+ stock_return=stock_return1[tickerlist+['Mkt']]
1664
+ else:
1665
+ print(" #Error(portfolio_es_alpha): failed to retrieve risk-free interest rate, please try again")
1666
+ return None
1667
+ else:
1668
+ #不考虑RF
1669
+ stock_return=stock_return0m[tickerlist+['Mkt']]
1670
+ """
1671
+ rf_daily=RF/365
1672
+ for t in tickerlist:
1673
+ #计算风险溢价
1674
+ stock_return0m[t]=stock_return0m[t]-rf_daily
1675
+ stock_return0m['Mkt']=stock_return0m['Mkt']-rf_daily
1676
+ stock_return=stock_return0m[tickerlist+['Mkt']]
1677
+
1678
+ #获得成份股个数
1679
+ numstocks=len(tickerlist)
1680
+
1681
+ # 设置空的numpy数组,用于存储每次模拟得到的成份股权重、组合的收益率和标准差
1682
+ import numpy as np
1683
+ random_p = np.empty((simulation,numstocks+2))
1684
+ # 设置随机数种子,这里是为了结果可重复
1685
+ np.random.seed(RANDOM_SEED)
1686
+ # 与其他比率设置不同的随机数种子,意在产生多样性的随机组合
1687
+
1688
+ # 循环模拟n次随机的投资组合
1689
+ from scipy import stats
1690
+ for i in range(simulation):
1691
+ # 生成numstocks个随机数,并归一化,得到一组随机的权重数据
1692
+ random9 = np.random.random(numstocks)
1693
+ random_weight = random9 / np.sum(random9)
1694
+
1695
+ # 计算随机投资组合的历史收益率
1696
+ stock_return['pRet']=stock_return[tickerlist].mul(random_weight,axis=1).sum(axis=1)
1697
+ """
1698
+ #使用年化收益率,便于得到具有可比性的纵轴数据刻度
1699
+ stock_return['pReta']=(1+stock_return['pRet'])**252 - 1
1700
+ stock_return['Mkta']=(1+stock_return['Mkt'])**252 - 1
1701
+ """
1702
+ #回归求截距项作为阿尔法指数:参与回归的变量不能有空值,否则回归系数将为空值!!!
1703
+ (beta,alpha,_,_,_)=stats.linregress(stock_return['Mkt'],stock_return['pRet'])
1704
+ """
1705
+ mean_return=stock_return[tickerlist].mul(random_weight,axis=1).sum(axis=1).mean(axis=0)
1706
+ annual_return = (1 + mean_return)**252 - 1
1707
+
1708
+ # 计算随机投资组合的年化平均标准差
1709
+ std_return=stock_return[tickerlist].mul(random_weight,axis=1).sum(axis=1).std(axis=0)
1710
+ annual_std = std_return*np.sqrt(252)
1711
+ """
1712
+ # 将上面生成的权重,和计算得到的阿尔法指数、贝塔系数存入数组random_p中
1713
+ # 数组矩阵的前numstocks为随机权重,其后为收益指标,再后为风险指标
1714
+ random_p[i][:numstocks] = random_weight
1715
+ random_p[i][numstocks] = alpha
1716
+ random_p[i][numstocks+1] = beta
1717
+
1718
+ #显示完成进度
1719
+ print_progress_percent(i,simulation,steps=10,leading_blanks=2)
1720
+
1721
+ # 将numpy数组转化成DataFrame数据框
1722
+ RandomPortfolios = pd.DataFrame(random_p)
1723
+ # 设置数据框RandomPortfolios每一列的名称
1724
+ RandomPortfolios.columns = [ticker + "_weight" for ticker in tickerlist] \
1725
+ + ['alpha', 'beta']
1726
+
1727
+ return [pf_info,RandomPortfolios]
1728
+
1729
+ if __name__=='__main__':
1730
+ Market={'Market':('US','^GSPC','我的组合001')}
1731
+ Stocks1={'AAPL':.1,'MSFT':.13,'XOM':.09,'JNJ':.09,'JPM':.09}
1732
+ Stocks2={'AMZN':.15,'GE':.08,'FB':.13,'T':.14}
1733
+ portfolio=dict(Market,**Stocks1,**Stocks2)
1734
+ pf_info=portfolio_expret(portfolio,'2019-12-31')
1735
+
1736
+ es_alpha=portfolio_es_alpha(pf_info,simulation=50000)
1737
+
1738
+ #==============================================================================
1739
+ if __name__=='__main__':
1740
+ simulation=1000
1741
+ rate_period='1Y'
1742
+ rate_type='treasury'
1743
+
1744
+ def portfolio_es_treynor(pf_info,simulation=50000,RF=0):
1745
+ """
1746
+ 功能:基于随机数,生成大量可能的投资组合,计算各个投资组合的风险溢价和贝塔系数,绘制投资组合的可行集
1747
+ """
1748
+ print(" Calculating possible portfolio combinations, please wait ...")
1749
+
1750
+ [[portfolio,_,stock_return0,rf_df,_],_]=pf_info
1751
+ pname=portfolio_name(portfolio)
1752
+ scope,mktidx,tickerlist,_,ticker_type=decompose_portfolio(portfolio)
1753
+
1754
+ #取出观察期
1755
+ hstart0=stock_return0.index[0]; hstart=str(hstart0.strftime("%Y-%m-%d"))
1756
+ hend0=stock_return0.index[-1]; hend=str(hend0.strftime("%Y-%m-%d"))
1757
+
1758
+ #计算市场指数的收益率
1759
+ import pandas as pd
1760
+ start1=date_adjust(hstart,adjust=-30)
1761
+ mkt=get_prices(mktidx,start1,hend)
1762
+ mkt['Mkt']=mkt['Close'].pct_change()
1763
+ mkt.dropna(inplace=True)
1764
+ mkt1=pd.DataFrame(mkt['Mkt'])
1765
+
1766
+ stock_return0m=pd.merge(stock_return0,mkt1,how='left',left_index=True,right_index=True)
1767
+ #处理无风险利率
1768
+ """
1769
+ if RF:
1770
+ #rf_df=get_rf_daily(hstart,hend,scope,rate_period,rate_type)
1771
+ if not (rf_df is None):
1772
+ stock_return1=pd.merge(stock_return0m,rf_df,how='inner',left_index=True,right_index=True)
1773
+ for t in tickerlist:
1774
+ #计算风险溢价
1775
+ stock_return1[t]=stock_return1[t]-stock_return1['rf_daily']
1776
+
1777
+ stock_return1['Mkt']=stock_return1['Mkt']-stock_return1['rf_daily']
1778
+ stock_return=stock_return1[tickerlist+['Mkt']]
1779
+ else:
1780
+ print(" #Error(portfolio_es_treynor): failed to retrieve risk-free interest rate, please try again")
1781
+ return None
1782
+ else:
1783
+ #不考虑RF
1784
+ stock_return=stock_return0m[tickerlist+['Mkt']]
1785
+ """
1786
+ rf_daily=RF/365
1787
+ for t in tickerlist:
1788
+ #计算风险溢价
1789
+ stock_return0m[t]=stock_return0m[t]-rf_daily
1790
+ stock_return0m['Mkt']=stock_return0m['Mkt']-rf_daily
1791
+ stock_return=stock_return0m[tickerlist+['Mkt']]
1792
+
1793
+
1794
+ #获得成份股个数
1795
+ numstocks=len(tickerlist)
1796
+
1797
+ # 设置空的numpy数组,用于存储每次模拟得到的成份股权重、组合的收益率和标准差
1798
+ import numpy as np
1799
+ random_p = np.empty((simulation,numstocks+2))
1800
+ # 设置随机数种子,这里是为了结果可重复
1801
+ np.random.seed(RANDOM_SEED)
1802
+ # 与其他比率设置不同的随机数种子,意在产生多样性的随机组合
1803
+
1804
+ # 循环模拟simulation次随机的投资组合
1805
+ from scipy import stats
1806
+ for i in range(simulation):
1807
+ # 生成numstocks个随机数放入random9,计算成份股持仓比例放入random_weight,得到一组随机的权重数据
1808
+ random9 = np.random.random(numstocks)
1809
+ random_weight = random9 / np.sum(random9)
1810
+
1811
+ # 计算随机投资组合的历史收益率
1812
+ stock_return['pRet']=stock_return[tickerlist].mul(random_weight,axis=1).sum(axis=1)
1813
+
1814
+ #回归求贝塔系数作为指数分母
1815
+ (beta,alpha,_,_,_)=stats.linregress(stock_return['Mkt'],stock_return['pRet'])
1816
+
1817
+ #计算年化风险溢价
1818
+ mean_return=stock_return[tickerlist].mul(random_weight,axis=1).sum(axis=1).mean(axis=0)
1819
+ annual_return = (1 + mean_return)**252 - 1
1820
+ """
1821
+ # 计算随机投资组合的年化平均标准差
1822
+ std_return=stock_return.mul(random_weight,axis=1).sum(axis=1).std(axis=0)
1823
+ annual_std = std_return*np.sqrt(252)
1824
+ """
1825
+ # 将上面生成的权重,和计算得到的风险溢价、贝塔系数存入数组random_p中
1826
+ # 数组矩阵的前numstocks为随机权重,其后为收益指标,再后为风险指标
1827
+ random_p[i][:numstocks] = random_weight
1828
+ random_p[i][numstocks] = annual_return
1829
+ random_p[i][numstocks+1] = beta
1830
+
1831
+ #显示完成进度
1832
+ print_progress_percent(i,simulation,steps=10,leading_blanks=2)
1833
+
1834
+ # 将numpy数组转化成DataFrame数据框
1835
+ RandomPortfolios = pd.DataFrame(random_p)
1836
+
1837
+ # 设置数据框RandomPortfolios每一列的名称
1838
+ RandomPortfolios.columns = [ticker + "_weight" for ticker in tickerlist] \
1839
+ + ['Risk premium', 'beta']
1840
+
1841
+ return [pf_info,RandomPortfolios]
1842
+
1843
+ if __name__=='__main__':
1844
+ Market={'Market':('US','^GSPC','我的组合001')}
1845
+ Stocks1={'AAPL':.1,'MSFT':.13,'XOM':.09,'JNJ':.09,'JPM':.09}
1846
+ Stocks2={'AMZN':.15,'GE':.08,'FB':.13,'T':.14}
1847
+ portfolio=dict(Market,**Stocks1,**Stocks2)
1848
+ pf_info=portfolio_expret(portfolio,'2019-12-31')
1849
+
1850
+ es_treynor=portfolio_es_treynor(pf_info,simulation=50000)
1851
+
1852
+ #==============================================================================
1853
+ def RandomPortfolios_plot(RandomPortfolios,col_x,col_y,colorbartxt,title_ext, \
1854
+ ylabeltxt,x_axis_name,pname,simulation,hstart,hend, \
1855
+ hiret_point,lorisk_point,convex_hull=True,frontier='efficient', \
1856
+ facecolor="papayawhip"):
1857
+ """
1858
+ 功能:将生成的马科维茨可行集RandomPortfolios绘制成彩色散点图
1859
+ """
1860
+
1861
+ """
1862
+ #特雷诺比率,对照用
1863
+ #RandomPortfolios.plot('beta','Risk premium',kind='scatter',color='y',edgecolors='k')
1864
+ pf_ratio = np.array(RandomPortfolios['Risk premium'] / RandomPortfolios['beta'])
1865
+ pf_returns = np.array(RandomPortfolios['Risk premium'])
1866
+ pf_volatilities = np.array(RandomPortfolios['beta'])
1867
+
1868
+ plt.figure(figsize=(12.8,6.4))
1869
+ plt.scatter(pf_volatilities, pf_returns, c=pf_ratio,cmap='RdYlGn', edgecolors='black',marker='o')
1870
+ plt.colorbar(label='特雷诺比率')
1871
+
1872
+ plt.title("投资组合: 马科维茨可行集,基于特雷诺比率")
1873
+ plt.ylabel("年化风险溢价")
1874
+
1875
+ import datetime as dt; stoday=dt.date.today()
1876
+ footnote1="贝塔系数-->"
1877
+ footnote2="\n\n基于"+pname+"之成份股构造"+str(simulation)+"个投资组合"
1878
+ footnote3="\n观察期间:"+hstart+"至"+hend
1879
+ footnote4="\n来源: Sina/EM/stooq/fred, "+str(stoday)
1880
+ plt.xlabel(footnote1+footnote2+footnote3+footnote4)
1881
+ plt.show()
1882
+ """
1883
+ DEBUG=False
1884
+
1885
+ #RandomPortfolios.plot(col_x,col_y,kind='scatter',color='y',edgecolors='k')
1886
+
1887
+ pf_ratio = np.array(RandomPortfolios[col_y] / RandomPortfolios[col_x])
1888
+ pf_returns = np.array(RandomPortfolios[col_y])
1889
+ pf_volatilities = np.array(RandomPortfolios[col_x])
1890
+
1891
+ #plt.figure(figsize=(12.8,6.4))
1892
+ plt.scatter(pf_volatilities, pf_returns, c=pf_ratio,cmap='RdYlGn', edgecolors='black',marker='o')
1893
+ plt.colorbar(label=colorbartxt)
1894
+
1895
+ #绘制散点图轮廓线凸包(convex hull)
1896
+ if convex_hull:
1897
+ print(" Calculating convex hull ...")
1898
+ from scipy.spatial import ConvexHull
1899
+
1900
+ #构造散点对的列表
1901
+ pf_volatilities_list=list(pf_volatilities)
1902
+ pf_returns_list=list(pf_returns)
1903
+ points=[]
1904
+ for x in pf_volatilities_list:
1905
+ pos=pf_volatilities_list.index(x)
1906
+ y=pf_returns_list[pos]
1907
+ points=points+[[x,y]]
1908
+
1909
+ #寻找最左侧的坐标:在x最小的同时,y要最大
1910
+ points_df = pd.DataFrame(points, columns=['x', 'y'])
1911
+ points_df.sort_values(by=['x','y'],ascending=[True,False],inplace=True)
1912
+ x1,y1=points_df.head(1).values[0]
1913
+
1914
+ #寻找最高点的坐标:在y最大的同时,x要最小
1915
+ points_df.sort_values(by=['y','x'],ascending=[False,True],inplace=True)
1916
+ x2,y2=points_df.head(1).values[0]
1917
+
1918
+ if DEBUG:
1919
+ plt.plot([x1,x2],[y1,y2],ls=':',lw=2,alpha=0.5)
1920
+
1921
+ #建立最左侧和最高点之间的拟合直线方程y=a+bx
1922
+ a=(x1*y2-x2*y1)/(x1-x2); b=(y1-y2)/(x1-x2)
1923
+ def y_bar(x_bar):
1924
+ return a+b*x_bar
1925
+
1926
+ # 计算散点集的外轮廓
1927
+ hull = ConvexHull(points)
1928
+
1929
+ # 绘制外轮廓线
1930
+ firsttime_efficient=True; firsttime_inefficient=True
1931
+ for simplex in hull.simplices:
1932
+ #p1中是一条线段起点和终点的横坐标
1933
+ p1=[points[simplex[0]][0], points[simplex[1]][0]]
1934
+ px1=p1[0];px2=p1[1]
1935
+ #p2中是一条线段起点和终点的纵坐标
1936
+ p2=[points[simplex[0]][1], points[simplex[1]][1]]
1937
+ py1=p2[0]; py2=p2[1]
1938
+
1939
+ """
1940
+ plt.plot([points[simplex[0]][0], points[simplex[1]][0]],
1941
+ [points[simplex[0]][1], points[simplex[1]][1]], 'k-.')
1942
+ """
1943
+ #线段起点:px1,py1;线段终点:px2,py2。但也可能互换起点和终点
1944
+ if ((py1>=y_bar(px1) or py1==y1) and (py2>=y_bar(px2) or py2==y2)) or \
1945
+ ((py1>=y_bar(px2) or py1==y2) and (py2>=y_bar(px1) or py2==y1)) :
1946
+ #有效边界
1947
+ if frontier.lower() in ['both','efficient']:
1948
+ if firsttime_efficient:
1949
+ plt.plot(p1,p2, 'r--',label=text_lang("有效边界","Efficient Frontier"),lw=3,alpha=0.5)
1950
+ firsttime_efficient=False
1951
+ else:
1952
+ plt.plot(p1,p2, 'r--',lw=3,alpha=0.5)
1953
+ else:
1954
+ pass
1955
+ else:
1956
+ #其余边沿
1957
+ if frontier.lower() in ['both','inefficient']:
1958
+ if firsttime_inefficient:
1959
+ plt.plot(p1,p2, 'k-.',label=text_lang("无效边界","Inefficient Frontier"),alpha=0.5)
1960
+ firsttime_inefficient=False
1961
+ else:
1962
+ plt.plot(p1,p2, 'k-.',alpha=0.5)
1963
+ else:
1964
+ pass
1965
+ else:
1966
+ #无convex hull
1967
+ pass
1968
+
1969
+ # 空一行
1970
+ print('')
1971
+
1972
+ lang = check_language()
1973
+ if lang == 'Chinese':
1974
+ if pname == '': pname='投资组合'
1975
+
1976
+ plt.title(pname+": 投资组合优化策略,基于"+title_ext,fontsize=title_txt_size)
1977
+ plt.ylabel(ylabeltxt,fontsize=ylabel_txt_size)
1978
+
1979
+ import datetime as dt; stoday=dt.date.today()
1980
+ footnote1=x_axis_name+" -->\n\n"
1981
+ footnote2="基于给定证券构造"+str(simulation)+"个投资组合"
1982
+ footnote3="\n观察期间:"+hstart+"至"+hend
1983
+ footnote4="\n数据来源: Sina/EM/Stooq/Yahoo, "+str(stoday)
1984
+ else:
1985
+ if pname == '': pname='Investment Portfolio'
1986
+
1987
+ plt.title(pname+": Portfolio Optimization, Based on "+title_ext,fontsize=title_txt_size)
1988
+ plt.ylabel(ylabeltxt,fontsize=ylabel_txt_size)
1989
+
1990
+ import datetime as dt; stoday=dt.date.today()
1991
+ footnote1=x_axis_name+" -->\n\n"
1992
+ footnote2="Built "+str(simulation)+" portfolios of given securities"
1993
+ footnote3="\nPeriod of sample: "+hstart+" to "+hend
1994
+ footnote4="\nData source: Sina/EM/Stooq/Yahoo, "+str(stoday)
1995
+
1996
+ plt.xlabel(footnote1+footnote2+footnote3+footnote4,fontsize=xlabel_txt_size)
1997
+
1998
+ #解析最大比率点和最低风险点信息,并绘点
1999
+ [hiret_x,hiret_y,name_hiret]=hiret_point
2000
+ #plt.scatter(hiret_x, hiret_y, color='red',marker='*',s=150,label=name_hiret)
2001
+ plt.scatter(hiret_x, hiret_y, color='red',marker='*',s=300,label=name_hiret,alpha=0.5)
2002
+
2003
+ [lorisk_x,lorisk_y,name_lorisk]=lorisk_point
2004
+ #plt.scatter(lorisk_x, lorisk_y, color='m',marker='8',s=100,label=name_lorisk)
2005
+ plt.scatter(lorisk_x, lorisk_y, color='blue',marker='8',s=150,label=name_lorisk,alpha=0.5)
2006
+
2007
+ plt.legend(loc='best')
2008
+
2009
+ plt.gca().set_facecolor(facecolor)
2010
+ plt.show()
2011
+
2012
+ return
2013
+ #==============================================================================
2014
+ #==============================================================================
2015
+ if __name__=='__main__':
2016
+ pname="MSR组合"
2017
+ modify_portfolio_name(pname)
2018
+
2019
+ def modify_portfolio_name(pname):
2020
+ """
2021
+ 功能:将原来的类似于MSR组合修改为更易懂的名称,仅供打印时使用
2022
+ """
2023
+ pclist=['等权重组合','交易额加权组合','MSR组合','GMVS组合','MSO组合','GML组合', \
2024
+ 'MAR组合','GMBA组合', 'MTR组合','GMBT组合']
2025
+
2026
+ pclist1=['等权重组合','交易额加权组合', \
2027
+ '最佳夏普比率组合(MSR)','夏普比率最小风险组合(GMVS)', \
2028
+ '最佳索替诺比率组合(MSO)','索替诺比率最小风险组合(GML)', \
2029
+ '最佳阿尔法指标组合(MAR)','阿尔法指标最小风险组合(GMBA)', \
2030
+ '最佳特雷诺比率组合(MTR)','特雷诺比率最小风险组合(GMBT)']
2031
+
2032
+ if pname not in pclist:
2033
+ return pname
2034
+
2035
+ pos=pclist.index(pname)
2036
+
2037
+ return pclist1[pos]
2038
+
2039
+ #==============================================================================
2040
+ def cvt_portfolio_name(pname,portfolio_returns):
2041
+ """
2042
+ 功能:将结果数据表中投资组合策略的名字从英文改为中文
2043
+ 将原各处portfolio_optimize函数中的过程统一起来
2044
+ """
2045
+
2046
+ pelist=['Portfolio','Portfolio_EW','Portfolio_LW','Portfolio_MSR','Portfolio_GMVS', \
2047
+ 'Portfolio_MSO','Portfolio_GML','Portfolio_MAR','Portfolio_GMBA', \
2048
+ 'Portfolio_MTR','Portfolio_GMBT']
2049
+
2050
+ lang=check_language()
2051
+ if lang == "Chinese":
2052
+ """
2053
+ pclist=[pname,'等权重组合','交易额加权组合','MSR组合','GMVS组合','MSO组合','GML组合', \
2054
+ 'MAR组合','GMBA组合', 'MTR组合','GMBT组合']
2055
+ """
2056
+ pclist=[pname,'等权重组合','交易额加权组合', \
2057
+ '最佳夏普比率组合(MSR)','夏普比率最小风险组合(GMVS)', \
2058
+ '最佳索替诺比率组合(MSO)','索替诺比率最小风险组合(GML)', \
2059
+ '最佳阿尔法指标组合(MAR)','阿尔法指标最小风险组合(GMBA)', \
2060
+ '最佳特雷诺比率组合(MTR)','特雷诺比率最小风险组合(GMBT)']
2061
+
2062
+ else:
2063
+ #"""
2064
+ pclist=[pname,'Equal-weighted','Amount-weighted','MSR','GMVS','MSO','GML', \
2065
+ 'MAR','GMBA', 'MTR','GMBT']
2066
+ """
2067
+ pclist=[pname,'Equal-weighted','Amount-weighted','Max Sharpe Ratio(MSR)', \
2068
+ 'Min Risk in Sharpe Ratio(GMVS)','Max Sortino Ratio(MSO)', \
2069
+ 'Min Risk in Sortino Ratio(GML)','Max Alpha(MAR)','Min Risk in Alpha(GMBA)', \
2070
+ 'Max Treynor Ratio(MTR)','Min Risk in Treynor Ratio(GMBT)']
2071
+ """
2072
+
2073
+ pecols=list(portfolio_returns)
2074
+ for p in pecols:
2075
+ try:
2076
+ ppos=pelist.index(p)
2077
+ except:
2078
+ continue
2079
+ else:
2080
+ pc=pclist[ppos]
2081
+ portfolio_returns.rename(columns={p:pc},inplace=True)
2082
+
2083
+ return portfolio_returns
2084
+
2085
+ #==============================================================================
2086
+
2087
+ def portfolio_optimize_sharpe(es_info,graph=True,convex_hull=False,frontier='efficient',facecolor='papayawhip'):
2088
+ """
2089
+ 功能:计算投资组合的最高夏普比率组合,并绘图
2090
+ MSR: Maximium Sharpe Rate, 最高夏普指数方案
2091
+ GMVS: Global Minimum Volatility by Sharpe, 全局最小波动方案
2092
+ """
2093
+
2094
+ #需要定制:定义名称变量......................................................
2095
+ col_ratio='Sharpe' #指数名称
2096
+ col_y='Risk premium' #指数分子
2097
+ col_x='Risk premium volatility' #指数分母
2098
+
2099
+ name_hiret='MSR' #Maximum Sharpe Ratio,指数最高点
2100
+ name_lorisk='GMVS' #Global Minimum Volatility by Sharpe,风险最低点
2101
+
2102
+ lang = check_language()
2103
+ if lang == 'Chinese':
2104
+ title_ext="夏普比率" #用于标题区别
2105
+ """
2106
+ if RF:
2107
+ colorbartxt='夏普比率(经无风险利率调整后)' #用于彩色棒标签
2108
+ ylabeltxt="年化风险溢价" #用于纵轴名称
2109
+ x_axis_name="年化风险溢价标准差" #用于横轴名称
2110
+ else:
2111
+ colorbartxt='夏普比率(未经无风险利率调整)' #用于彩色棒标签
2112
+ ylabeltxt="年化收益率" #用于纵轴名称
2113
+ x_axis_name="年化标准差" #用于横轴名称
2114
+ """
2115
+ colorbartxt='夏普比率' #用于彩色棒标签
2116
+ ylabeltxt="年化风险溢价" #用于纵轴名称
2117
+ x_axis_name="年化风险溢价标准差" #用于横轴名称
2118
+
2119
+ else:
2120
+ title_ext="Sharpe Ratio" #用于标题区别
2121
+ """
2122
+ if RF:
2123
+ colorbartxt='Sharpe Ratio(Rf adjusted)' #用于彩色棒标签
2124
+ ylabeltxt="Annualized Risk Premium" #用于纵轴名称
2125
+ x_axis_name="Annualized Std of Risk Premium" #用于横轴名称
2126
+ else:
2127
+ colorbartxt='Sharpe Ratio(Rf unadjusted)' #用于彩色棒标签
2128
+ ylabeltxt="Annualized Return" #用于纵轴名称
2129
+ x_axis_name="Annualized Std" #用于横轴名称
2130
+ """
2131
+ colorbartxt='Sharpe Ratio' #用于彩色棒标签
2132
+ ylabeltxt="Annualized Risk Premium" #用于纵轴名称
2133
+ x_axis_name="Annualized Risk Premium STD" #用于横轴名称
2134
+
2135
+ #定制部分结束...............................................................
2136
+
2137
+ #计算指数,寻找最大指数点和风险最低点,并绘图标注两个点
2138
+ hiret_weights,lorisk_weights,portfolio_returns = \
2139
+ portfolio_optimize_rar(es_info,col_ratio,col_y,col_x,name_hiret,name_lorisk, \
2140
+ colorbartxt,title_ext,ylabeltxt,x_axis_name,graph=graph, \
2141
+ convex_hull=convex_hull,frontier=frontier,facecolor=facecolor)
2142
+
2143
+ print(text_lang("【注释】","[Notes]"))
2144
+ print("★MSR :Maximized Sharpe Ratio"+text_lang(",最大夏普比率点",''))
2145
+ print("◍GMVS:Global Minimized Volatility by Sharpe Ratio"+text_lang(",全局最小夏普比率波动点",''))
2146
+
2147
+ return name_hiret,hiret_weights,name_lorisk,lorisk_weights,portfolio_returns
2148
+
2149
+
2150
+ if __name__=='__main__':
2151
+ Market={'Market':('US','^GSPC','我的组合001')}
2152
+ Stocks1={'AAPL':.1,'MSFT':.13,'XOM':.09,'JNJ':.09,'JPM':.09}
2153
+ Stocks2={'AMZN':.15,'GE':.08,'FB':.13,'T':.14}
2154
+ portfolio=dict(Market,**Stocks1,**Stocks2)
2155
+
2156
+ pf_info=portfolio_expret(portfolio,'2019-12-31')
2157
+ es_sharpe=portfolio_es_sharpe(pf_info,simulation=50000)
2158
+
2159
+ MSR_weights,GMV_weights,portfolio_returns=portfolio_optimize_sharpe(es_sharpe)
2160
+
2161
+
2162
+ #==============================================================================
2163
+
2164
+ def portfolio_optimize_sortino(es_info,graph=True,convex_hull=False,frontier='efficient',facecolor="papayawhip"):
2165
+ """
2166
+ 功能:计算投资组合的最高索替诺比率组合,并绘图
2167
+ MSO: Maximium Sortino ratio, 最高索替诺比率方案
2168
+ GML: Global Minimum LPSD volatility, 全局最小LPSD下偏标准差方案
2169
+ """
2170
+
2171
+ #需要定制:定义名称变量......................................................
2172
+ col_ratio='Sortino' #指数名称
2173
+ col_y='Risk premium' #指数分子
2174
+ col_x='Risk premium LPSD' #指数分母
2175
+
2176
+ name_hiret='MSO' #Maximum SOrtino ratio,指数最高点
2177
+ name_lorisk='GML' #Global Minimum LPSD,风险最低点
2178
+
2179
+ title_ext=text_lang("索替诺比率","Sortino Ratio") #用于标题区别
2180
+ colorbartxt=text_lang("索替诺比率","Sortino Ratio") #用于彩色棒标签
2181
+ ylabeltxt=text_lang("年化风险溢价","Annualized Risk Premium") #用于纵轴名称
2182
+ x_axis_name=text_lang("年化风险溢价之下偏标准差","Annualized Risk Premium LPSD") #用于横轴名称
2183
+
2184
+ #定制部分结束...............................................................
2185
+
2186
+ #计算指数,寻找最大指数点和风险最低点,并绘图标注两个点
2187
+ hiret_weights,lorisk_weights,portfolio_returns = \
2188
+ portfolio_optimize_rar(es_info,col_ratio,col_y,col_x,name_hiret,name_lorisk, \
2189
+ colorbartxt,title_ext,ylabeltxt,x_axis_name,graph=graph, \
2190
+ convex_hull=convex_hull,frontier=frontier,facecolor=facecolor)
2191
+
2192
+ print(text_lang("【注释】","[Notes]"))
2193
+ print("★MSO:Maximum SOrtino ratio"+text_lang(",最大索替诺比率点",''))
2194
+ print("◍GML:Global Minimum LPSD"+text_lang(",全局最小LPSD点",''))
2195
+
2196
+ return name_hiret,hiret_weights,name_lorisk,lorisk_weights,portfolio_returns
2197
+
2198
+
2199
+ if __name__=='__main__':
2200
+ Market={'Market':('US','^GSPC','我的组合001')}
2201
+ Stocks1={'AAPL':.1,'MSFT':.13,'XOM':.09,'JNJ':.09,'JPM':.09}
2202
+ Stocks2={'AMZN':.15,'GE':.08,'FB':.13,'T':.14}
2203
+ portfolio=dict(Market,**Stocks1,**Stocks2)
2204
+
2205
+ pf_info=portfolio_expret(portfolio,'2019-12-31')
2206
+ es_sortino=portfolio_es_sortino(pf_info,simulation=50000)
2207
+
2208
+ MSO_weights,GML_weights,portfolio_returns=portfolio_optimize_sortino(es_Sortino)
2209
+
2210
+
2211
+ #==============================================================================
2212
+ if __name__=='__main__':
2213
+ graph=True; convex_hull=False
2214
+
2215
+ def portfolio_optimize_alpha(es_info,graph=True,convex_hull=False,frontier='efficient',facecolor='papayawhip'):
2216
+ """
2217
+ 功能:计算投资组合的最高詹森阿尔法组合,并绘图
2218
+ MAR: Maximium Alpha Ratio, 最高阿尔法指数方案
2219
+ GMBA: Global Minimum Beta by Alpha, 全局最小贝塔系数方案
2220
+ """
2221
+
2222
+ #需要定制:定义名称变量......................................................
2223
+ col_ratio='Alpha' #指数名称
2224
+ col_y='alpha' #指数分子
2225
+ #col_y='Risk premium' #指数分子
2226
+ col_x='beta' #指数分母
2227
+
2228
+ name_hiret='MAR' #Maximum Alpha Ratio,指数最高点
2229
+ name_lorisk='GMBA' #Global Minimum Beta by Alpha,风险最低点
2230
+
2231
+ title_ext=text_lang("阿尔法指数","Jensen Alpha") #用于标题区别
2232
+ colorbartxt=text_lang("阿尔法指数","Jensen Alpha") #用于彩色棒标签
2233
+ ylabeltxt=text_lang("阿尔法指数","Jensen Alpha") #用于纵轴名称
2234
+ x_axis_name=text_lang("贝塔系数","Beta") #用于横轴名称
2235
+ #定制部分结束...............................................................
2236
+
2237
+ #计算指数,寻找最大指数点和风险最低点,并绘图标注两个点
2238
+ hiret_weights,lorisk_weights,portfolio_returns = \
2239
+ portfolio_optimize_rar(es_info,col_ratio,col_y,col_x,name_hiret,name_lorisk, \
2240
+ colorbartxt,title_ext,ylabeltxt,x_axis_name,graph=graph, \
2241
+ convex_hull=convex_hull,frontier=frontier,facecolor=facecolor)
2242
+
2243
+ print(text_lang("【注释】","[Notes]"))
2244
+ print("★MAR :Maximum Alpha Ratio"+text_lang(",最大阿尔法点",''))
2245
+ print("◍GMBA:Global Minimum Beta by Alpha"+text_lang(",全局最小阿尔法-贝塔点",''))
2246
+
2247
+ return name_hiret,hiret_weights,name_lorisk,lorisk_weights,portfolio_returns
2248
+
2249
+
2250
+ if __name__=='__main__':
2251
+ Market={'Market':('US','^GSPC','我的组合001')}
2252
+ Stocks1={'AAPL':.1,'MSFT':.13,'XOM':.09,'JNJ':.09,'JPM':.09}
2253
+ Stocks2={'AMZN':.15,'GE':.08,'FB':.13,'T':.14}
2254
+ portfolio=dict(Market,**Stocks1,**Stocks2)
2255
+
2256
+ pf_info=portfolio_expret(portfolio,'2019-12-31')
2257
+ es_alpha=portfolio_es_alpha(pf_info,simulation=50000)
2258
+
2259
+ MAR_weights,GMB_weights,portfolio_returns=portfolio_optimize_alpha(es_alpha)
2260
+
2261
+ #==============================================================================
2262
+
2263
+ def portfolio_optimize_treynor(es_info,graph=True,convex_hull=False,frontier='efficient',facecolor='papayawhip'):
2264
+ """
2265
+ 功能:计算投资组合的最高特雷诺比率组合,并绘图
2266
+ MTR: Maximium Treynor Ratio, 最高特雷诺指数方案
2267
+ GMBT: Global Minimum Beta by Treynor, 全局最小贝塔系数方案
2268
+ """
2269
+
2270
+ #需要定制:定义名称变量......................................................
2271
+ col_ratio='Treynor' #指数名称
2272
+ col_y='Risk premium' #指数分子
2273
+ col_x='beta' #指数分母
2274
+
2275
+ name_hiret='MTR' #Maximum Treynor Ratio,指数最高点
2276
+ name_lorisk='GMBT' #Global Minimum Beta in Treynor,风险最低点
2277
+
2278
+ title_ext=text_lang("特雷诺比率","Treynor Ratio") #用于标题区别
2279
+ colorbartxt=text_lang("特雷诺比率","Treynor Ratio") #用于彩色棒标签
2280
+ ylabeltxt=text_lang("年化风险溢价","Annualized Risk Premium") #用于纵轴名称
2281
+ x_axis_name=text_lang("贝塔系数","Beta") #用于横轴名称
2282
+ #定制部分结束...............................................................
2283
+
2284
+ #计算指数,寻找最大指数点和风险最低点,并绘图标注两个点
2285
+ hiret_weights,lorisk_weights,portfolio_returns = \
2286
+ portfolio_optimize_rar(es_info,col_ratio,col_y,col_x,name_hiret,name_lorisk, \
2287
+ colorbartxt,title_ext,ylabeltxt,x_axis_name,graph=graph, \
2288
+ convex_hull=convex_hull,frontier=frontier,facecolor=facecolor)
2289
+
2290
+ print(text_lang("【注释】","[Notes]"))
2291
+ print("★MTR :Maximum Treynor Ratio"+text_lang(",最大特雷诺比率点",''))
2292
+ print("◍GMBT:Global Minimum Beta in Treynor"+text_lang(",全局最小特雷诺-贝塔点",''))
2293
+
2294
+ return name_hiret,hiret_weights,name_lorisk,lorisk_weights,portfolio_returns
2295
+
2296
+ #==============================================================================
2297
+ if __name__=='__main__':
2298
+ col_ratio,col_y,col_x,name_hiret,name_lorisk,colorbartxt,title_ext,ylabeltxt,x_axis_name= \
2299
+ ('Sharpe', 'alpha', 'beta', 'MAR', 'GMBA', '阿尔法指数', '阿尔法指数', '阿尔法指数', '贝塔系数')
2300
+
2301
+ def portfolio_optimize_rar(es_info,col_ratio,col_y,col_x,name_hiret,name_lorisk, \
2302
+ colorbartxt,title_ext,ylabeltxt,x_axis_name,graph=True, \
2303
+ convex_hull=False,frontier='efficient',facecolor='papayawhip'):
2304
+ """
2305
+ 功能:提供rar比率优化的共同处理部分
2306
+ 基于RandomPortfolios中的随机投资组合,计算相应的指数,寻找最大指数点和风险最小点,并绘图标注两个点
2307
+ 输入:以特雷诺比率为例
2308
+ col_ratio='Treynor' #指数名称
2309
+ col_y='Risk premium' #指数分子
2310
+ col_x='beta' #指数分母
2311
+ name_hiret='MTR' #Maximum Treynor Ratio,指数最高点
2312
+ name_lorisk='GMBT' #Global Minimum Beta in Treynor,风险最低点
2313
+
2314
+ colorbartxt='特雷诺比率' #用于彩色棒标签
2315
+ title_ext="特雷诺比率" #用于标题区别
2316
+ ylabeltxt="年化风险溢价" #用于纵轴名称
2317
+ x_axis_name="贝塔系数" #用于横轴名称
2318
+
2319
+ """
2320
+ #解析传入的数据
2321
+ [[[portfolio,thedate,stock_return,_,_],[StockReturns,_,_,_]],RandomPortfolios]=es_info
2322
+ _,_,tickerlist,_,ticker_type=decompose_portfolio(portfolio)
2323
+ numstocks=len(tickerlist)
2324
+ pname=portfolio_name(portfolio)
2325
+
2326
+ #取出观察期
2327
+ hstart0=StockReturns.index[0]; hstart=str(hstart0.strftime("%Y-%m-%d"))
2328
+ hend0=StockReturns.index[-1]; hend=str(hend0.strftime("%Y-%m-%d"))
2329
+
2330
+ #识别并计算指数..........................................................
2331
+ if col_ratio.title() in ['Alpha']:
2332
+ RandomPortfolios[col_ratio] = RandomPortfolios[col_y]
2333
+ elif col_ratio.title() in ['Treynor','Sharpe','Sortino']:
2334
+ RandomPortfolios[col_ratio] = RandomPortfolios[col_y] / RandomPortfolios[col_x]
2335
+ else:
2336
+ print(" #Error(portfolio_optimize_rar): invalid rar",col_ratio)
2337
+ print(" Supported rar(risk-adjusted-return): Treynor, Sharpe, Sortino, Alpha")
2338
+ return None
2339
+
2340
+ # 找到指数最大数据对应的索引值
2341
+ max_index = RandomPortfolios[col_ratio].idxmax()
2342
+ # 找出指数最大的点坐标并绘制该点
2343
+ hiret_x = RandomPortfolios.loc[max_index,col_x]
2344
+ hiret_y = RandomPortfolios.loc[max_index,col_y]
2345
+
2346
+ # 提取最高指数组合对应的权重,并转化为numpy数组
2347
+ import numpy as np
2348
+ hiret_weights = np.array(RandomPortfolios.iloc[max_index, 0:numstocks])
2349
+ # 计算最高指数组合的收益率
2350
+ StockReturns['Portfolio_'+name_hiret] = stock_return[tickerlist].mul(hiret_weights, axis=1).sum(axis=1)
2351
+
2352
+ # 找到风险最小组合的索引值
2353
+ min_index = RandomPortfolios[col_x].idxmin()
2354
+ # 提取最小风险组合对应的权重, 并转换成Numpy数组
2355
+ # 找出风险最小的点坐标并绘制该点
2356
+ lorisk_x = RandomPortfolios.loc[min_index,col_x]
2357
+ lorisk_y = RandomPortfolios.loc[min_index,col_y]
2358
+
2359
+ # 提取最小风险组合对应的权重,并转化为numpy数组
2360
+ lorisk_weights = np.array(RandomPortfolios.iloc[min_index, 0:numstocks])
2361
+ # 计算风险最小组合的收益率
2362
+ StockReturns['Portfolio_'+name_lorisk] = stock_return[tickerlist].mul(lorisk_weights, axis=1).sum(axis=1)
2363
+
2364
+ #绘制散点图
2365
+ simulation=len(RandomPortfolios)
2366
+
2367
+ lang = check_language()
2368
+ if lang == 'Chinese':
2369
+ point_txt="点"
2370
+ else:
2371
+ point_txt=" Point"
2372
+
2373
+ hiret_point=[hiret_x,hiret_y,name_hiret+point_txt]
2374
+ lorisk_point=[lorisk_x,lorisk_y,name_lorisk+point_txt]
2375
+ if graph:
2376
+ RandomPortfolios_plot(RandomPortfolios,col_x,col_y,colorbartxt,title_ext, \
2377
+ ylabeltxt,x_axis_name,pname,simulation,hstart,hend, \
2378
+ hiret_point,lorisk_point,convex_hull=convex_hull, \
2379
+ frontier=frontier,facecolor=facecolor)
2380
+
2381
+ #返回数据,供进一步分析
2382
+ portfolio_returns=StockReturns.copy()
2383
+
2384
+ #将投资组合策略改为中文
2385
+ portfolio_returns=cvt_portfolio_name(pname,portfolio_returns)
2386
+
2387
+ return hiret_weights,lorisk_weights,portfolio_returns
2388
+
2389
+
2390
+ if __name__=='__main__':
2391
+ Market={'Market':('US','^GSPC','我的组合001')}
2392
+ Stocks1={'AAPL':.1,'MSFT':.13,'XOM':.09,'JNJ':.09,'JPM':.09}
2393
+ Stocks2={'AMZN':.15,'GE':.08,'FB':.13,'T':.14}
2394
+ portfolio=dict(Market,**Stocks1,**Stocks2)
2395
+
2396
+ pf_info=portfolio_expret(portfolio,'2019-12-31')
2397
+ es_treynor=portfolio_es_treynor(pf_info,simulation=50000)
2398
+
2399
+ MTR_weights,GMB2_weights,portfolio_returns=portfolio_optimize_treynor(es_treynor)
2400
+
2401
+ #==============================================================================
2402
+ #==============================================================================
2403
+ if __name__=='__main__':
2404
+ ratio='sharpe'
2405
+ ratio='alpha'
2406
+ ratio='treynor'
2407
+ simulation=1000
2408
+ simulation=50000
2409
+
2410
+ pf_info0=pf_info
2411
+ ratio='treynor'
2412
+
2413
+ simulation=10000
2414
+ RF=0.046
2415
+ graph=True
2416
+ hirar_return=True; lorisk=True
2417
+ convex_hull=True; frontier='efficient'; facecolor='papayawhip'
2418
+
2419
+
2420
+
2421
+ def portfolio_optimize(pf_info0,ratio='sharpe',simulation=10000,RF=0, \
2422
+ graph=True,hirar_return=False,lorisk=True, \
2423
+ convex_hull=True,frontier='efficient',facecolor='papayawhip'):
2424
+ """
2425
+ 功能:集成式投资组合优化策略
2426
+ 注意:实验发现RF较小时对于结果的影响极其微小难以观察,默认设为不使用无风险利率调整收益
2427
+ 但RF较大时对于结果的影响明显变大,已经不能忽略!
2428
+ 若可行集形状不佳,优先尝试pastyears=3,再尝试增加simulation次数。
2429
+ simulation数值过大时将导致速度太慢。
2430
+ """
2431
+ # 防止原始数据被修改
2432
+ import copy
2433
+ pf_info=copy.deepcopy(pf_info0)
2434
+
2435
+ ratio_list=['treynor','sharpe','sortino','alpha']
2436
+ ratio=ratio.lower()
2437
+ if not (ratio in ratio_list):
2438
+ print(" #Error(portfolio_optimize_strategy): invalid strategy ratio",ratio)
2439
+ print(" Supported strategy ratios",ratio_list)
2440
+ return
2441
+
2442
+ print(" Optimizing portfolio configuration by",ratio,"ratio ...")
2443
+
2444
+ [[portfolio,_,_,_,_],_]=pf_info
2445
+ pname=portfolio_name(portfolio)
2446
+ _,_,_,_,ticker_type=decompose_portfolio(portfolio)
2447
+
2448
+ #观察马科维茨可行集:风险溢价-标准差,用于夏普比率优化
2449
+ func_es="portfolio_es_"+ratio
2450
+ es_info=eval(func_es)(pf_info=pf_info,simulation=simulation,RF=RF)
2451
+
2452
+
2453
+ #寻找比率最优点:最大比率策略和最小风险策略
2454
+ func_optimize="portfolio_optimize_"+ratio
2455
+ """
2456
+ name_hiret,hiret_weights,name_lorisk,lorisk_weights,portfolio_returns= \
2457
+ eval(func_optimize)(es_info=es_info,RF=RF,graph=graph)
2458
+ """
2459
+ name_hiret,hiret_weights,name_lorisk,lorisk_weights,portfolio_returns= \
2460
+ eval(func_optimize)(es_info=es_info,graph=graph,convex_hull=convex_hull, \
2461
+ frontier=frontier,facecolor=facecolor)
2462
+
2463
+
2464
+ lang = check_language()
2465
+ if lang == 'Chinese':
2466
+ zhuhe_txt='组合'
2467
+ mingcheng_txt='投资组合名称/策略'
2468
+ titletxt="投资组合策略:业绩比较"
2469
+ ylabeltxt="持有期收益率"
2470
+ else:
2471
+ zhuhe_txt=''
2472
+ mingcheng_txt='Strategy'
2473
+ titletxt="Investment Portfolio Strategy: Performance Comparison"
2474
+ ylabeltxt="Holding Period Return"
2475
+
2476
+ #打印投资组合构造和业绩表现
2477
+ hi_name=modify_portfolio_name(name_hiret+zhuhe_txt)
2478
+ lo_name=modify_portfolio_name(name_lorisk+zhuhe_txt)
2479
+ portfolio_expectation(hi_name,pf_info,hiret_weights,ticker_type)
2480
+
2481
+ if hirar_return:
2482
+ scope,mktidx,tickerlist,_,ticker_type=decompose_portfolio(portfolio)
2483
+ hwdf=pd.DataFrame(hiret_weights)
2484
+ hwdft=hwdf.T
2485
+ hwdft.columns=tickerlist
2486
+ hwdftt=hwdft.T
2487
+ hwdftt.sort_values(by=[0],ascending=False,inplace=True)
2488
+ hwdftt['ticker']=hwdftt.index
2489
+ hwdftt['weight']=hwdftt[0].apply(lambda x:round(x,4))
2490
+ stocks_new=hwdftt.set_index(['ticker'])['weight'].to_dict()
2491
+ pname=portfolio_name(portfolio)
2492
+
2493
+ Market={'Market':(scope,mktidx,pname)}
2494
+ portfolio_new=dict(Market,**stocks_new)
2495
+
2496
+ if lorisk:
2497
+ portfolio_expectation(lo_name,pf_info,lorisk_weights,ticker_type)
2498
+
2499
+ #现有投资组合的排名
2500
+ ranks=portfolio_ranks(portfolio_returns,pname)
2501
+
2502
+ #绘制投资组合策略业绩比较曲线:最多显示4条曲线,否则黑白打印时无法区分
2503
+ top4=list(ranks[mingcheng_txt])[:4]
2504
+ for p in top4:
2505
+ if p in [pname,hi_name,lo_name]:
2506
+ continue
2507
+ else:
2508
+ break
2509
+ name_list=[pname,hi_name,lo_name,p]
2510
+
2511
+ if graph:
2512
+ portfolio_expret_plot(portfolio_returns,name_list,titletxt=titletxt,ylabeltxt=ylabeltxt)
2513
+
2514
+ if hirar_return:
2515
+ return portfolio_new
2516
+ else:
2517
+ return
2518
+
2519
+ #==============================================================================
2520
+ #==============================================================================
2521
+ #==============================================================================
2522
+ #==============================================================================
2523
+ #==============================================================================
2524
+ #==============================================================================
2525
+
2526
+ def translate_tickerlist(tickerlist):
2527
+ newlist=[]
2528
+ for t in tickerlist:
2529
+ name=ticker_name(t,'bond')
2530
+ newlist=newlist+[name]
2531
+
2532
+ return newlist
2533
+ #==============================================================================
2534
+ # 绘制马科维茨有效边界
2535
+ #==============================================================================
2536
+ def ret_monthly(ticker,prices):
2537
+ """
2538
+ 功能:
2539
+ """
2540
+ price=prices['Adj Close'][ticker]
2541
+
2542
+ import numpy as np
2543
+ div=price.pct_change()+1
2544
+ logret=np.log(div)
2545
+ import pandas as pd
2546
+ lrdf=pd.DataFrame(logret)
2547
+ lrdf['ymd']=lrdf.index.astype("str")
2548
+ lrdf['ym']=lrdf['ymd'].apply(lambda x:x[0:7])
2549
+ lrdf.dropna(inplace=True)
2550
+
2551
+ mret=lrdf.groupby(by=['ym'])[ticker].sum()
2552
+
2553
+ return mret
2554
+
2555
+ if __name__=='__main__':
2556
+ ticker='MSFT'
2557
+ fromdate,todate='2019-1-1','2020-8-1'
2558
+
2559
+ #==============================================================================
2560
+ def objFunction(W,R,target_ret):
2561
+
2562
+ import numpy as np
2563
+ stock_mean=np.mean(R,axis=0)
2564
+ port_mean=np.dot(W,stock_mean) # portfolio mean
2565
+
2566
+ cov=np.cov(R.T) # var-cov matrix
2567
+ port_var=np.dot(np.dot(W,cov),W.T) # portfolio variance
2568
+ penalty = 2000*abs(port_mean-target_ret)# penalty 4 deviation
2569
+
2570
+ objfunc=np.sqrt(port_var) + penalty # objective function
2571
+
2572
+ return objfunc
2573
+
2574
+ #==============================================================================
2575
+ def portfolio_ef_0(stocks,fromdate,todate):
2576
+ """
2577
+ 功能:绘制马科维茨有效前沿,不区分上半沿和下半沿
2578
+ 问题:很可能出现上下边界折叠的情况,难以解释,弃用!!!
2579
+ """
2580
+ #Code for getting stock prices
2581
+ prices=get_prices(stocks,fromdate,todate)
2582
+
2583
+ #Code for generating a return matrix R
2584
+ R0=ret_monthly(stocks[0],prices) # starting from 1st stock
2585
+ n_stock=len(stocks) # number of stocks
2586
+ import pandas as pd
2587
+ import numpy as np
2588
+ for i in range(1,n_stock): # merge with other stocks
2589
+ x=ret_monthly(stocks[i],prices)
2590
+ R0=pd.merge(R0,x,left_index=True,right_index=True)
2591
+ R=np.array(R0)
2592
+
2593
+ #Code for estimating optimal portfolios for a given return
2594
+ out_mean,out_std,out_weight=[],[],[]
2595
+ import numpy as np
2596
+ stockMean=np.mean(R,axis=0)
2597
+
2598
+ from scipy.optimize import minimize
2599
+ for r in np.linspace(np.min(stockMean),np.max(stockMean),num=100):
2600
+ W = np.ones([n_stock])/n_stock # starting from equal weights
2601
+ b_ = [(0,1) for i in range(n_stock)] # bounds, here no short
2602
+ c_ = ({'type':'eq', 'fun': lambda W: sum(W)-1. }) #constraint
2603
+ result=minimize(objFunction,W,(R,r),method='SLSQP'
2604
+ ,constraints=c_, bounds=b_)
2605
+ if not result.success: # handle error raise
2606
+ BaseException(result.message)
2607
+
2608
+ try:
2609
+ out_mean.append(round(r,4)) # 4 decimal places
2610
+ except:
2611
+ out_mean._append(round(r,4))
2612
+
2613
+ std_=round(np.std(np.sum(R*result.x,axis=1)),6)
2614
+ try:
2615
+ out_std.append(std_)
2616
+ out_weight.append(result.x)
2617
+ except:
2618
+ out_std._append(std_)
2619
+ out_weight._append(result.x)
2620
+
2621
+ #Code for plotting the efficient frontier
2622
+
2623
+ plt.title('Efficient Frontier of Portfolio')
2624
+ plt.xlabel('Standard Deviation of portfolio (Risk))')
2625
+ plt.ylabel('Return of portfolio')
2626
+
2627
+ out_std_min=min(out_std)
2628
+ pos=out_std.index(out_std_min)
2629
+ out_mean_min=out_mean[pos]
2630
+ x_left=out_std_min+0.25
2631
+ y_left=out_mean_min+0.5
2632
+
2633
+ #plt.figtext(x_left,y_left,str(n_stock)+' stock are used: ')
2634
+ plt.figtext(x_left,y_left,"投资组合由"+str(n_stock)+'种证券构成: ')
2635
+ plt.figtext(x_left,y_left-0.05,' '+str(stocks))
2636
+ plt.figtext(x_left,y_left-0.1,'观察期间:'+str(fromdate)+'至'+str(todate))
2637
+ plt.plot(out_std,out_mean,color='r',ls=':',lw=4)
2638
+
2639
+ plt.gca().set_facecolor('papayawhip')
2640
+ plt.show()
2641
+
2642
+ return
2643
+
2644
+ if __name__=='__main__':
2645
+ stocks=['IBM','WMT','AAPL','C','MSFT']
2646
+ fromdate,todate='2019-1-1','2020-8-1'
2647
+ portfolio_ef_0(stocks,fromdate,todate)
2648
+
2649
+ #==============================================================================
2650
+ def portfolio_ef(stocks,fromdate,todate):
2651
+ """
2652
+ 功能:多只股票的马科维茨有效边界,区分上半沿和下半沿,标记风险极小点
2653
+ 问题:很可能出现上下边界折叠的情况,难以解释,弃用!!!
2654
+ """
2655
+ print("\n Searching for portfolio information, please wait...")
2656
+ #Code for getting stock prices
2657
+ prices=get_prices(stocks,fromdate,todate)
2658
+
2659
+ #Code for generating a return matrix R
2660
+ R0=ret_monthly(stocks[0],prices) # starting from 1st stock
2661
+ n_stock=len(stocks) # number of stocks
2662
+
2663
+ import pandas as pd
2664
+ import numpy as np
2665
+ for i in range(1,n_stock): # merge with other stocks
2666
+ x=ret_monthly(stocks[i],prices)
2667
+ R0=pd.merge(R0,x,left_index=True,right_index=True)
2668
+ R=np.array(R0)
2669
+
2670
+ #Code for estimating optimal portfolios for a given return
2671
+ out_mean,out_std,out_weight=[],[],[]
2672
+ stockMean=np.mean(R,axis=0)
2673
+
2674
+ from scipy.optimize import minimize
2675
+ for r in np.linspace(np.min(stockMean),np.max(stockMean),num=100):
2676
+ W = np.ones([n_stock])/n_stock # starting from equal weights
2677
+ b_ = [(0,1) for i in range(n_stock)] # bounds, here no short
2678
+ c_ = ({'type':'eq', 'fun': lambda W: sum(W)-1. }) #constraint
2679
+ result=minimize(objFunction,W,(R,r),method='SLSQP'
2680
+ ,constraints=c_, bounds=b_)
2681
+ if not result.success: # handle error raise
2682
+ BaseException(result.message)
2683
+
2684
+ try:
2685
+ out_mean.append(round(r,4)) # 4 decimal places
2686
+ std_=round(np.std(np.sum(R*result.x,axis=1)),6)
2687
+ out_std.append(std_)
2688
+ out_weight.append(result.x)
2689
+ except:
2690
+ out_mean._append(round(r,4)) # 4 decimal places
2691
+ std_=round(np.std(np.sum(R*result.x,axis=1)),6)
2692
+ out_std._append(std_)
2693
+ out_weight._append(result.x)
2694
+
2695
+ #Code for positioning
2696
+ out_std_min=min(out_std)
2697
+ pos=out_std.index(out_std_min)
2698
+ out_mean_min=out_mean[pos]
2699
+ x_left=out_std_min+0.25
2700
+ y_left=out_mean_min+0.5
2701
+
2702
+ import pandas as pd
2703
+ out_df=pd.DataFrame(out_mean,out_std,columns=['mean'])
2704
+ out_df_ef=out_df[out_df['mean']>=out_mean_min]
2705
+ out_df_ief=out_df[out_df['mean']<out_mean_min]
2706
+
2707
+ #Code for plotting the efficient frontier
2708
+
2709
+ plt.title('投资组合:马科维茨有效边界(理想图)')
2710
+
2711
+ import datetime as dt; stoday=dt.date.today()
2712
+ plt.xlabel('收益率标准差-->'+"\n数据来源:新浪/EM/stooq, "+str(stoday))
2713
+ plt.ylabel('收益率')
2714
+
2715
+ plt.figtext(x_left,y_left,"投资组合由"+str(n_stock)+'种证券构成: ')
2716
+ plt.figtext(x_left,y_left-0.05,' '+str(stocks))
2717
+ plt.figtext(x_left,y_left-0.1,'观察期间:'+str(fromdate)+'至'+str(todate))
2718
+ plt.plot(out_df_ef.index,out_df_ef['mean'],color='r',ls='--',lw=2,label='有效边界')
2719
+ plt.plot(out_df_ief.index,out_df_ief['mean'],color='k',ls=':',lw=2,label='无效边界')
2720
+ plt.plot(out_std_min,out_mean_min,'g*-',markersize=16,label='风险最低点')
2721
+
2722
+ plt.legend(loc='best')
2723
+ plt.gca().set_facecolor('papayawhip')
2724
+ plt.show()
2725
+
2726
+ return
2727
+
2728
+ if __name__=='__main__':
2729
+ stocks=['IBM','WMT','AAPL','C','MSFT']
2730
+ fromdate,todate='2019-1-1','2020-8-1'
2731
+ df=portfolio_ef(stocks,fromdate,todate)
2732
+
2733
+ #==============================================================================
2734
+ if __name__=='__main__':
2735
+ tickers=['^GSPC','000001.SS','^HSI','^N225','^BSESN']
2736
+ start='2023-1-1'
2737
+ end='2023-3-22'
2738
+ info_type='Volume'
2739
+ df=security_correlation(tickers,start,end,info_type='Close')
2740
+
2741
+
2742
+ def cm2inch(x,y):
2743
+ return x/2.54,y/2.54
2744
+
2745
+ def security_correlation(tickers,start='L5Y',end='today',info_type='Close', \
2746
+ facecolor='white'):
2747
+ """
2748
+ ===========================================================================
2749
+ 功能:股票/指数收盘价之间的相关性
2750
+ 参数:
2751
+ tickers:指标列表,至少两个
2752
+ start:起始日期,格式YYYY-MM-DD,支持简易格式
2753
+ end:截止日期
2754
+ info_type:指标的数值类型,默认'Close', 还可为Open/High/Low/Volume
2755
+ facecolor:背景颜色,默认'papayawhip'
2756
+
2757
+ 返回:相关系数df
2758
+ """
2759
+
2760
+ start,end=start_end_preprocess(start,end)
2761
+
2762
+ info_types=['Close','Open','High','Low','Volume']
2763
+ info_types_cn=['收盘价','开盘价','最高价','最低价','成交量']
2764
+ if not(info_type in info_types):
2765
+ print(" #Error(security_correlation): invalid information type",info_type)
2766
+ print(" Supported information type:",info_types)
2767
+ return None
2768
+ pos=info_types.index(info_type)
2769
+ info_type_cn=info_types_cn[pos]
2770
+
2771
+ #屏蔽函数内print信息输出的类
2772
+ import os, sys
2773
+ class HiddenPrints:
2774
+ def __enter__(self):
2775
+ self._original_stdout = sys.stdout
2776
+ sys.stdout = open(os.devnull, 'w')
2777
+
2778
+ def __exit__(self, exc_type, exc_val, exc_tb):
2779
+ sys.stdout.close()
2780
+ sys.stdout = self._original_stdout
2781
+
2782
+ print(" Searching for security prices, please wait ...\n")
2783
+ with HiddenPrints():
2784
+ prices=get_prices_simple(tickers,start,end)
2785
+ df=prices[info_type]
2786
+ df.dropna(axis=0,inplace=True)
2787
+
2788
+ # here put the import lib
2789
+ import seaborn as sns
2790
+ sns.set(font='SimHei') # 解决Seaborn中文显示问题
2791
+ #sns.set_style('whitegrid',{'font.sans-serif':['SimHei','Arial']})
2792
+ #sns.set_style('whitegrid',{'font.sans-serif':['FangSong']})
2793
+
2794
+ import numpy as np
2795
+ from scipy.stats import pearsonr
2796
+
2797
+ collist=list(df)
2798
+ for col in collist:
2799
+ df.rename(columns={col:ticker_name(col,'bond')},inplace=True)
2800
+ df_coor = df.corr()
2801
+
2802
+
2803
+ #fig = plt.figure(figsize=(cm2inch(16,12)))
2804
+ #fig = plt.figure(figsize=(cm2inch(12,8)))
2805
+ #fig = plt.figure(figsize=(12.8,7.2))
2806
+ fig = plt.figure(figsize=(12.8,6.4))
2807
+ ax1 = plt.gca()
2808
+
2809
+ #构造mask,去除重复数据显示
2810
+ mask = np.zeros_like(df_coor)
2811
+ mask[np.triu_indices_from(mask)] = True
2812
+ mask2 = mask
2813
+ mask = (np.flipud(mask)-1)*(-1)
2814
+ mask = np.rot90(mask,k = -1)
2815
+
2816
+ im1 = sns.heatmap(df_coor,annot=True,cmap="YlGnBu"
2817
+ , mask=mask#构造mask,去除重复数据显示
2818
+ , vmax=1,vmin=-1
2819
+ , cbar=False
2820
+ , fmt='.2f',ax = ax1,annot_kws={"size": 16})
2821
+
2822
+ ax1.tick_params(axis = 'both', length=0)
2823
+
2824
+ #计算相关性显著性并显示
2825
+ rlist = []
2826
+ plist = []
2827
+ for i in df.columns.values:
2828
+ for j in df.columns.values:
2829
+ r,p = pearsonr(df[i],df[j])
2830
+ try:
2831
+ rlist.append(r)
2832
+ plist.append(p)
2833
+ except:
2834
+ rlist._append(r)
2835
+ plist._append(p)
2836
+
2837
+ rarr = np.asarray(rlist).reshape(len(df.columns.values),len(df.columns.values))
2838
+ parr = np.asarray(plist).reshape(len(df.columns.values),len(df.columns.values))
2839
+ xlist = ax1.get_xticks()
2840
+ ylist = ax1.get_yticks()
2841
+
2842
+ widthx = 0
2843
+ widthy = -0.15
2844
+
2845
+ # 星号的大小
2846
+ font_dict={'size':10}
2847
+
2848
+ for m in ax1.get_xticks():
2849
+ for n in ax1.get_yticks():
2850
+ pv = (parr[int(m),int(n)])
2851
+ rv = (rarr[int(m),int(n)])
2852
+ if mask2[int(m),int(n)]<1.:
2853
+ if abs(rv) > 0.5:
2854
+ if pv< 0.05 and pv>= 0.01:
2855
+ ax1.text(n+widthx,m+widthy,'*',ha = 'center',color = 'white',fontdict=font_dict)
2856
+ if pv< 0.01 and pv>= 0.001:
2857
+ ax1.text(n+widthx,m+widthy,'**',ha = 'center',color = 'white',fontdict=font_dict)
2858
+ if pv< 0.001:
2859
+ #print([int(m),int(n)])
2860
+ ax1.text(n+widthx,m+widthy,'***',ha = 'center',color = 'white',fontdict=font_dict)
2861
+ else:
2862
+ if pv< 0.05 and pv>= 0.01:
2863
+ ax1.text(n+widthx,m+widthy,'*',ha = 'center',color = 'k',fontdict=font_dict)
2864
+ elif pv< 0.01 and pv>= 0.001:
2865
+ ax1.text(n+widthx,m+widthy,'**',ha = 'center',color = 'k',fontdict=font_dict)
2866
+ elif pv< 0.001:
2867
+ ax1.text(n+widthx,m+widthy,'***',ha = 'center',color = 'k',fontdict=font_dict)
2868
+
2869
+ #plt.title(text_lang("时间序列相关性分析:","Time Series Correlation Analysis: ")+text_lang(info_type_cn,info_type),fontsize=16)
2870
+ plt.title(text_lang("时间序列相关性分析","Time Series Correlation Analysis"),fontsize=16)
2871
+ plt.tick_params(labelsize=10)
2872
+
2873
+ footnote1=text_lang("\n显著性数值:***非常显著(<0.001),**很显著(<0.01),*显著(<0.05),其余为不显著", \
2874
+ "\nSig level: *** Extremely sig(p<0.001), ** Very sig(<0.01), * Sig(<0.05), others unsig")
2875
+ footnote2=text_lang("\n系数绝对值:>=0.8极强相关,0.6-0.8强相关,0.4-0.6相关,0.2-0.4弱相关,否则为极弱(不)相关", \
2876
+ "\nCoef. abs: >=0.8 Extreme corr, 0.6-0.8 Strong corr, 0.4-0.6 Corr, <0.4 Weak or uncorr")
2877
+
2878
+ footnote3=text_lang("\n观察期间: ","\nPeriod of sample: ")+start+text_lang('至',' to ')+end
2879
+ import datetime as dt; stoday=dt.date.today()
2880
+ footnote4=text_lang(";数据来源:Sina/EM/Stooq/Yahoo,",". Data source: Sina/EM/Stooq/Yahoo, ")+str(stoday)
2881
+
2882
+ fontxlabel={'size':8}
2883
+ plt.xlabel(footnote1+footnote2+footnote3+footnote4,fontxlabel)
2884
+ #plt.xticks(rotation=45)
2885
+
2886
+ plt.gca().set_facecolor(facecolor)
2887
+
2888
+ #plt.xticks(fontsize=10, rotation=90)
2889
+ plt.xticks(fontsize=10, rotation=30)
2890
+ plt.yticks(fontsize=10, rotation=0)
2891
+
2892
+ plt.show()
2893
+
2894
+ return df_coor
2895
+
2896
+ #==============================================================================
2897
+ if __name__ =="__main__":
2898
+ portfolio={'Market':('US','^GSPC','Test 1'),'EDU':0.4,'TAL':0.3,'TEDU':0.2}
2899
+
2900
+ def describe_portfolio(portfolio):
2901
+ """
2902
+ 功能:描述投资组合的信息
2903
+ 输入:投资组合
2904
+ 输出:市场,市场指数,股票代码列表和份额列表
2905
+ """
2906
+
2907
+ scope,mktidx,tickerlist,sharelist,ticker_type=decompose_portfolio(portfolio)
2908
+ pname=portfolio_name(portfolio)
2909
+
2910
+ print("*** 投资组合信息:",pname)
2911
+ print("\n所在市场:",ectranslate(scope))
2912
+ print("市场指数:",ticker_name(mktidx,'bond')+'('+mktidx+')')
2913
+ print("成分股及其份额:")
2914
+
2915
+ num=len(tickerlist)
2916
+ #seqlist=[]
2917
+ tickerlist1=[]
2918
+ sharelist1=[]
2919
+ for t in range(num):
2920
+ #seqlist=seqlist+[t+1]
2921
+ tickerlist1=tickerlist1+[ticker_name(tickerlist[t],'bond')+'('+tickerlist[t]+')']
2922
+ sharelist1=sharelist1+[str(round(sharelist[t],2))+'%']
2923
+
2924
+ import pandas as pd
2925
+ #df=pd.DataFrame({'序号':seqlist,'成分股':tickerlist1,'份额':sharelist1})
2926
+ df=pd.DataFrame({'成分股':tickerlist1,'份额':sharelist1})
2927
+ df.index=df.index+1
2928
+
2929
+ alignlist=['center','left','right']
2930
+ print(df.to_markdown(index=True,tablefmt='plain',colalign=alignlist))
2931
+
2932
+ return
2933
+
2934
+ #==============================================================================
2935
+ def portfolio_drop(portfolio,last=0,droplist=[],new_name=''):
2936
+ """
2937
+ 功能:删除最后几个成分股
2938
+ """
2939
+ scope,mktidx,tickerlist,sharelist,ticker_type=decompose_portfolio(portfolio)
2940
+ pname=portfolio_name(portfolio)
2941
+
2942
+ if not (last ==0):
2943
+ for i in range(last):
2944
+ #print(i)
2945
+ tmp=tickerlist.pop()
2946
+ tmp=sharelist.pop()
2947
+
2948
+ if not (droplist==[]):
2949
+ for d in droplist:
2950
+ pos=tickerlist.index(d)
2951
+ tmp=tickerlist.pop(pos)
2952
+ tmp=sharelist.pop(pos)
2953
+
2954
+ stocks_new=dict(zip(tickerlist,sharelist))
2955
+
2956
+ if new_name=='':
2957
+ new_name=pname
2958
+
2959
+ Market={'Market':(scope,mktidx,new_name)}
2960
+ portfolio_new=dict(Market,**stocks_new)
2961
+
2962
+ return portfolio_new
2963
+
2964
+ #==============================================================================
2965
+ #==============================================================================
2966
+ #==============================================================================
2967
+ #==============================================================================
2968
+
2969
+