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

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