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