siat 3.10.130__py3-none-any.whl → 3.10.132__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- build/lib/build/lib/siat/__init__.py +75 -0
- build/lib/build/lib/siat/allin.py +137 -0
- build/lib/build/lib/siat/assets_liquidity.py +915 -0
- build/lib/build/lib/siat/beta_adjustment.py +1058 -0
- build/lib/build/lib/siat/beta_adjustment_china.py +548 -0
- build/lib/build/lib/siat/blockchain.py +143 -0
- build/lib/build/lib/siat/bond.py +2900 -0
- build/lib/build/lib/siat/bond_base.py +992 -0
- build/lib/build/lib/siat/bond_china.py +100 -0
- build/lib/build/lib/siat/bond_zh_sina.py +143 -0
- build/lib/build/lib/siat/capm_beta.py +783 -0
- build/lib/build/lib/siat/capm_beta2.py +887 -0
- build/lib/build/lib/siat/common.py +5360 -0
- build/lib/build/lib/siat/compare_cross.py +642 -0
- build/lib/build/lib/siat/copyrights.py +18 -0
- build/lib/build/lib/siat/cryptocurrency.py +667 -0
- build/lib/build/lib/siat/economy.py +1471 -0
- build/lib/build/lib/siat/economy2.py +1853 -0
- build/lib/build/lib/siat/esg.py +536 -0
- build/lib/build/lib/siat/event_study.py +815 -0
- build/lib/build/lib/siat/fama_french.py +1521 -0
- build/lib/build/lib/siat/fin_stmt2_yahoo.py +982 -0
- build/lib/build/lib/siat/financial_base.py +1160 -0
- build/lib/build/lib/siat/financial_statements.py +598 -0
- build/lib/build/lib/siat/financials.py +2339 -0
- build/lib/build/lib/siat/financials2.py +1278 -0
- build/lib/build/lib/siat/financials_china.py +4433 -0
- build/lib/build/lib/siat/financials_china2.py +2212 -0
- build/lib/build/lib/siat/fund.py +629 -0
- build/lib/build/lib/siat/fund_china.py +3307 -0
- build/lib/build/lib/siat/future_china.py +551 -0
- build/lib/build/lib/siat/google_authenticator.py +47 -0
- build/lib/build/lib/siat/grafix.py +3636 -0
- build/lib/build/lib/siat/holding_risk.py +867 -0
- build/lib/build/lib/siat/luchy_draw.py +638 -0
- build/lib/build/lib/siat/market_china.py +1168 -0
- build/lib/build/lib/siat/markowitz.py +2363 -0
- build/lib/build/lib/siat/markowitz2.py +3150 -0
- build/lib/build/lib/siat/markowitz2_20250704.py +2969 -0
- build/lib/build/lib/siat/markowitz2_20250705.py +3158 -0
- build/lib/build/lib/siat/markowitz_simple.py +373 -0
- build/lib/build/lib/siat/ml_cases.py +2291 -0
- build/lib/build/lib/siat/ml_cases_example.py +60 -0
- build/lib/build/lib/siat/option_china.py +3069 -0
- build/lib/build/lib/siat/option_pricing.py +1925 -0
- build/lib/build/lib/siat/other_indexes.py +409 -0
- build/lib/build/lib/siat/risk_adjusted_return.py +1576 -0
- build/lib/build/lib/siat/risk_adjusted_return2.py +1900 -0
- build/lib/build/lib/siat/risk_evaluation.py +2218 -0
- build/lib/build/lib/siat/risk_free_rate.py +351 -0
- build/lib/build/lib/siat/sector_china.py +4140 -0
- build/lib/build/lib/siat/security_price2.py +727 -0
- build/lib/build/lib/siat/security_prices.py +3408 -0
- build/lib/build/lib/siat/security_trend.py +402 -0
- build/lib/build/lib/siat/security_trend2.py +646 -0
- build/lib/build/lib/siat/stock.py +4284 -0
- build/lib/build/lib/siat/stock_advice_linear.py +934 -0
- build/lib/build/lib/siat/stock_base.py +26 -0
- build/lib/build/lib/siat/stock_china.py +2095 -0
- build/lib/build/lib/siat/stock_prices_kneighbors.py +910 -0
- build/lib/build/lib/siat/stock_prices_linear.py +386 -0
- build/lib/build/lib/siat/stock_profile.py +707 -0
- build/lib/build/lib/siat/stock_technical.py +3305 -0
- build/lib/build/lib/siat/stooq.py +74 -0
- build/lib/build/lib/siat/transaction.py +347 -0
- build/lib/build/lib/siat/translate.py +5183 -0
- build/lib/build/lib/siat/valuation.py +1378 -0
- build/lib/build/lib/siat/valuation_china.py +2076 -0
- build/lib/build/lib/siat/var_model_validation.py +444 -0
- build/lib/build/lib/siat/yf_name.py +811 -0
- build/lib/siat/__init__.py +75 -0
- build/lib/siat/allin.py +137 -0
- build/lib/siat/assets_liquidity.py +915 -0
- build/lib/siat/beta_adjustment.py +1058 -0
- build/lib/siat/beta_adjustment_china.py +548 -0
- build/lib/siat/blockchain.py +143 -0
- build/lib/siat/bond.py +2900 -0
- build/lib/siat/bond_base.py +992 -0
- build/lib/siat/bond_china.py +100 -0
- build/lib/siat/bond_zh_sina.py +143 -0
- build/lib/siat/capm_beta.py +783 -0
- build/lib/siat/capm_beta2.py +887 -0
- build/lib/siat/common.py +5360 -0
- build/lib/siat/compare_cross.py +642 -0
- build/lib/siat/copyrights.py +18 -0
- build/lib/siat/cryptocurrency.py +667 -0
- build/lib/siat/economy.py +1471 -0
- build/lib/siat/economy2.py +1853 -0
- build/lib/siat/esg.py +536 -0
- build/lib/siat/event_study.py +815 -0
- build/lib/siat/fama_french.py +1521 -0
- build/lib/siat/fin_stmt2_yahoo.py +982 -0
- build/lib/siat/financial_base.py +1160 -0
- build/lib/siat/financial_statements.py +598 -0
- build/lib/siat/financials.py +2339 -0
- build/lib/siat/financials2.py +1278 -0
- build/lib/siat/financials_china.py +4433 -0
- build/lib/siat/financials_china2.py +2212 -0
- build/lib/siat/fund.py +629 -0
- build/lib/siat/fund_china.py +3307 -0
- build/lib/siat/future_china.py +551 -0
- build/lib/siat/google_authenticator.py +47 -0
- build/lib/siat/grafix.py +3636 -0
- build/lib/siat/holding_risk.py +867 -0
- build/lib/siat/luchy_draw.py +638 -0
- build/lib/siat/market_china.py +1168 -0
- build/lib/siat/markowitz.py +2363 -0
- build/lib/siat/markowitz2.py +3150 -0
- build/lib/siat/markowitz2_20250704.py +2969 -0
- build/lib/siat/markowitz2_20250705.py +3158 -0
- build/lib/siat/markowitz_simple.py +373 -0
- build/lib/siat/ml_cases.py +2291 -0
- build/lib/siat/ml_cases_example.py +60 -0
- build/lib/siat/option_china.py +3069 -0
- build/lib/siat/option_pricing.py +1925 -0
- build/lib/siat/other_indexes.py +409 -0
- build/lib/siat/risk_adjusted_return.py +1576 -0
- build/lib/siat/risk_adjusted_return2.py +1900 -0
- build/lib/siat/risk_evaluation.py +2218 -0
- build/lib/siat/risk_free_rate.py +351 -0
- build/lib/siat/sector_china.py +4140 -0
- build/lib/siat/security_price2.py +727 -0
- build/lib/siat/security_prices.py +3408 -0
- build/lib/siat/security_trend.py +402 -0
- build/lib/siat/security_trend2.py +646 -0
- build/lib/siat/stock.py +4284 -0
- build/lib/siat/stock_advice_linear.py +934 -0
- build/lib/siat/stock_base.py +26 -0
- build/lib/siat/stock_china.py +2095 -0
- build/lib/siat/stock_prices_kneighbors.py +910 -0
- build/lib/siat/stock_prices_linear.py +386 -0
- build/lib/siat/stock_profile.py +707 -0
- build/lib/siat/stock_technical.py +3305 -0
- build/lib/siat/stooq.py +74 -0
- build/lib/siat/transaction.py +347 -0
- build/lib/siat/translate.py +5183 -0
- build/lib/siat/valuation.py +1378 -0
- build/lib/siat/valuation_china.py +2076 -0
- build/lib/siat/var_model_validation.py +444 -0
- build/lib/siat/yf_name.py +811 -0
- siat/__init__.py +0 -0
- siat/allin.py +0 -0
- siat/assets_liquidity.py +0 -0
- siat/beta_adjustment.py +0 -0
- siat/beta_adjustment_china.py +0 -0
- siat/blockchain.py +0 -0
- siat/bond.py +0 -0
- siat/bond_base.py +0 -0
- siat/bond_china.py +0 -0
- siat/bond_zh_sina.py +0 -0
- siat/capm_beta.py +0 -0
- siat/capm_beta2.py +0 -0
- siat/common.py +94 -30
- siat/compare_cross.py +0 -0
- siat/copyrights.py +0 -0
- siat/cryptocurrency.py +0 -0
- siat/economy.py +0 -0
- siat/economy2.py +0 -0
- siat/esg.py +0 -0
- siat/event_study.py +0 -0
- siat/fama_french.py +0 -0
- siat/fin_stmt2_yahoo.py +0 -0
- siat/financial_base.py +0 -0
- siat/financial_statements.py +0 -0
- siat/financials.py +0 -0
- siat/financials2.py +0 -0
- siat/financials_china.py +0 -0
- siat/financials_china2.py +0 -0
- siat/fund.py +0 -0
- siat/fund_china.py +0 -0
- siat/future_china.py +0 -0
- siat/google_authenticator.py +0 -0
- siat/grafix.py +1 -1
- siat/holding_risk.py +0 -0
- siat/luchy_draw.py +0 -0
- siat/market_china.py +7 -1
- siat/markowitz.py +0 -0
- siat/markowitz2.py +240 -39
- siat/markowitz2_20250704.py +2969 -0
- siat/markowitz2_20250705.py +3158 -0
- siat/markowitz_simple.py +0 -0
- siat/ml_cases.py +0 -0
- siat/ml_cases_example.py +0 -0
- siat/option_china.py +0 -0
- siat/option_pricing.py +0 -0
- siat/other_indexes.py +0 -0
- siat/risk_adjusted_return.py +0 -0
- siat/risk_adjusted_return2.py +0 -0
- siat/risk_evaluation.py +0 -0
- siat/risk_free_rate.py +0 -0
- siat/sector_china.py +0 -0
- siat/security_price2.py +0 -0
- siat/security_prices.py +3 -1
- siat/security_trend.py +0 -0
- siat/security_trend2.py +1 -1
- siat/stock.py +4 -2
- siat/stock_advice_linear.py +0 -0
- siat/stock_base.py +0 -0
- siat/stock_china.py +0 -0
- siat/stock_prices_kneighbors.py +0 -0
- siat/stock_prices_linear.py +0 -0
- siat/stock_profile.py +0 -0
- siat/stock_technical.py +0 -0
- siat/stooq.py +0 -0
- siat/transaction.py +0 -0
- siat/translate.py +11 -11
- siat/valuation.py +0 -0
- siat/valuation_china.py +0 -0
- siat/var_model_validation.py +0 -0
- siat/yf_name.py +0 -0
- {siat-3.10.130.dist-info → siat-3.10.132.dist-info}/METADATA +11 -11
- siat-3.10.132.dist-info/RECORD +218 -0
- siat-3.10.132.dist-info/top_level.txt +4 -0
- siat-3.10.130.dist-info/RECORD +0 -76
- siat-3.10.130.dist-info/top_level.txt +0 -1
- {siat-3.10.130.dist-info → siat-3.10.132.dist-info}/WHEEL +0 -0
- {siat-3.10.130.dist-info → siat-3.10.132.dist-info}/licenses/LICENSE +0 -0
@@ -0,0 +1,373 @@
|
|
1
|
+
# -*- coding: utf-8 -*-
|
2
|
+
"""
|
3
|
+
本模块功能:马科维茨投资组合快速示意图
|
4
|
+
所属工具包:证券投资分析工具SIAT
|
5
|
+
SIAT:Security Investment Analysis Tool
|
6
|
+
创建日期:2023年7月8日
|
7
|
+
最新修订日期:2023年7月9日
|
8
|
+
作者:王德宏 (WANG Dehong, Peter)
|
9
|
+
作者单位:北京外国语大学国际商学院
|
10
|
+
作者邮件:wdehong2000@163.com
|
11
|
+
版权所有:王德宏
|
12
|
+
用途限制:仅限研究与教学使用,不可商用!商用需要额外授权。
|
13
|
+
特别声明:作者不对使用本工具进行证券投资导致的任何损益负责!
|
14
|
+
"""
|
15
|
+
|
16
|
+
#==============================================================================
|
17
|
+
#关闭所有警告
|
18
|
+
import warnings; warnings.filterwarnings('ignore')
|
19
|
+
from siat.security_prices import *
|
20
|
+
|
21
|
+
#==============================================================================
|
22
|
+
import matplotlib.pyplot as plt
|
23
|
+
|
24
|
+
#统一设定绘制的图片大小:数值为英寸,1英寸=100像素
|
25
|
+
plt.rcParams['figure.figsize']=(12.8,7.2)
|
26
|
+
plt.rcParams['figure.dpi']=300
|
27
|
+
plt.rcParams['font.size'] = 13
|
28
|
+
plt.rcParams['xtick.labelsize']=11 #横轴字体大小
|
29
|
+
plt.rcParams['ytick.labelsize']=11 #纵轴字体大小
|
30
|
+
|
31
|
+
title_txt_size=16
|
32
|
+
ylabel_txt_size=14
|
33
|
+
xlabel_txt_size=14
|
34
|
+
legend_txt_size=14
|
35
|
+
|
36
|
+
#设置绘图风格:网格虚线
|
37
|
+
plt.rcParams['axes.grid']=True
|
38
|
+
#plt.rcParams['grid.color']='steelblue'
|
39
|
+
#plt.rcParams['grid.linestyle']='dashed'
|
40
|
+
#plt.rcParams['grid.linewidth']=0.5
|
41
|
+
#plt.rcParams['axes.facecolor']='whitesmoke'
|
42
|
+
|
43
|
+
#处理绘图汉字乱码问题
|
44
|
+
import sys; czxt=sys.platform
|
45
|
+
if czxt in ['win32','win64']:
|
46
|
+
plt.rcParams['font.sans-serif'] = ['SimHei'] # 设置默认字体
|
47
|
+
mpfrc={'font.family': 'SimHei'}
|
48
|
+
|
49
|
+
if czxt in ['darwin']: #MacOSX
|
50
|
+
plt.rcParams['font.family']= ['Heiti TC']
|
51
|
+
mpfrc={'font.family': 'Heiti TC'}
|
52
|
+
|
53
|
+
if czxt in ['linux']: #website Jupyter
|
54
|
+
plt.rcParams['font.family']= ['Heiti TC']
|
55
|
+
mpfrc={'font.family':'Heiti TC'}
|
56
|
+
|
57
|
+
# 解决保存图像时'-'显示为方块的问题
|
58
|
+
plt.rcParams['axes.unicode_minus'] = False
|
59
|
+
#==============================================================================
|
60
|
+
|
61
|
+
# 全局引用,函数中无需再import
|
62
|
+
from datetime import date
|
63
|
+
import pandas as pd
|
64
|
+
import numpy as np
|
65
|
+
import scipy.optimize as opt
|
66
|
+
|
67
|
+
import seaborn as sns
|
68
|
+
g=sns.set_style("whitegrid")#横坐标有标线,纵坐标没有标线,背景白色
|
69
|
+
g=sns.set_style("darkgrid") #默认,横纵坐标都有标线,组成一个一个格子,背景稍微深色
|
70
|
+
g=sns.set_style("dark")#背景稍微深色,没有标线线
|
71
|
+
g=sns.set_style("white")#背景白色,没有标线线
|
72
|
+
g=sns.set_style("ticks")#xy轴都有非常短的小刻度
|
73
|
+
g=sns.despine(offset=30,left=True)#去掉上边和右边的轴线,offset=30表示距离轴线(x轴)的距离,left=True表示左边的轴保留
|
74
|
+
g=sns.set(font='SimHei',rc={'figure.figsize':(10,6)})# 图片大小和中文字体设置
|
75
|
+
|
76
|
+
#==============================================================================
|
77
|
+
if __name__=='__main__':
|
78
|
+
components = {
|
79
|
+
'AAPL':'苹果',
|
80
|
+
'AMZN':'亚马逊',
|
81
|
+
'GOOGL':'谷歌',
|
82
|
+
'BABA':'阿里巴巴'
|
83
|
+
}
|
84
|
+
|
85
|
+
start='2022-1-1'
|
86
|
+
end='2022-12-31'
|
87
|
+
|
88
|
+
risk_free=0.015
|
89
|
+
simulation=25000
|
90
|
+
price_trend=True
|
91
|
+
feasible_set=True
|
92
|
+
efficient_frontier=True
|
93
|
+
MOP=True #Markowitz Optimized Point
|
94
|
+
MSR=True #Maximized Sharpe Ratio
|
95
|
+
|
96
|
+
ef_adjust=1.008
|
97
|
+
|
98
|
+
markowitz_sharpe(components,start,end)
|
99
|
+
markowitz_sharpe(components,start,end,ef_adjust=1.008)
|
100
|
+
markowitz_sharpe(components,start,end,MOP=True)
|
101
|
+
markowitz_sharpe(components,start,end,MSR=True)
|
102
|
+
markowitz_sharpe(components,start,end,MOP=True,MSR=True)
|
103
|
+
|
104
|
+
def markowitz_sharpe(components,start,end,risk_free=0.015,simulation=25000, \
|
105
|
+
price_trend=True,feasible_set=True,efficient_frontier=True, \
|
106
|
+
MOP=False,MSR=False,ef_adjust=1.008):
|
107
|
+
"""
|
108
|
+
功能:使用期间内夏普比率寻找马科维茨最优点,绘制可行集、有效边界和最优点
|
109
|
+
components:投资组合成分股票代码与名称,节省搜索股票名称的时间
|
110
|
+
start,end:开始/结束日期
|
111
|
+
risk_free:人工指定无风险利率,节省搜索时间,减少搜索失败概率
|
112
|
+
simulation:生成可行集的模拟次数
|
113
|
+
price_trend:是否绘制各个成分股票的价格走势,采用股价/起点股价的比值,可一图绘制多只股票
|
114
|
+
feasible_set:是否绘制可行集
|
115
|
+
efficient_frontier:是否绘制有效边界
|
116
|
+
MOP:是否标注MOP点,Markowitz Optimized Point,可能与MSR点不同
|
117
|
+
MSR:是否标注MSR点,Maximized Sharpe Ratio,可能与MOP点不同
|
118
|
+
ef_adjust:对有效边界曲线微调,使其处于可行集的上边沿
|
119
|
+
"""
|
120
|
+
#获取股票数据
|
121
|
+
tickers=list(components)
|
122
|
+
|
123
|
+
# 使用Adj Close避免分红分拆引起股价不连续导致结果异常
|
124
|
+
#cprices=get_prices(tickers,start,end)
|
125
|
+
stock_data=get_prices(tickers,start,end)['Adj Close']
|
126
|
+
stock_data.rename(columns=components,inplace=True)
|
127
|
+
|
128
|
+
stock_data=stock_data.iloc[::-1]
|
129
|
+
#stock_data.head()
|
130
|
+
|
131
|
+
# 绘制成分股价格走势,采用股价/起点股价的相对股价,增加可比性
|
132
|
+
if price_trend:
|
133
|
+
(stock_data/stock_data.iloc[0]).plot()
|
134
|
+
titletxt='投资组合的成分股价格走势示意图'
|
135
|
+
plt.xlabel('')
|
136
|
+
plt.ylabel("价格/起点值")
|
137
|
+
plt.title(titletxt)
|
138
|
+
plt.show()
|
139
|
+
|
140
|
+
#------------------------------------------------------------------------------
|
141
|
+
# 计算收益率和风险
|
142
|
+
# 收益率
|
143
|
+
R=stock_data/stock_data.shift(1)-1
|
144
|
+
#R.head()
|
145
|
+
|
146
|
+
# 对数收益率
|
147
|
+
stock_data_shift1=stock_data.shift(1)
|
148
|
+
log_r=np.log(stock_data/stock_data.shift(1))
|
149
|
+
#log_r.head()
|
150
|
+
|
151
|
+
# 年化收益率
|
152
|
+
r_annual=np.exp(log_r.mean()*250)-1
|
153
|
+
#r_annual
|
154
|
+
|
155
|
+
# 风险
|
156
|
+
std = np.sqrt(log_r.var() * 250)#假设协方差为0
|
157
|
+
#std
|
158
|
+
|
159
|
+
#------------------------------------------------------------------------------
|
160
|
+
# 投资组合的收益和风险
|
161
|
+
def gen_weights(n):
|
162
|
+
w=np.random.rand(n)
|
163
|
+
return w /sum(w)
|
164
|
+
|
165
|
+
n=len(list(tickers))
|
166
|
+
#w=gen_weights(n)
|
167
|
+
#list(zip(r_annual.index,w))
|
168
|
+
|
169
|
+
#投资组合收益
|
170
|
+
def port_ret(w):
|
171
|
+
return -np.sum(w*r_annual)
|
172
|
+
#pret=port_ret(w)
|
173
|
+
|
174
|
+
#投资组合的风险
|
175
|
+
def port_std(w):
|
176
|
+
return np.sqrt((w.dot(log_r.cov()*250).dot(w.T)))
|
177
|
+
#pstd=port_std(w)
|
178
|
+
|
179
|
+
#若干投资组合的收益和风险
|
180
|
+
def gen_ports(times):
|
181
|
+
for _ in range(times):#生成不同的组合
|
182
|
+
w=gen_weights(n)#每次生成不同的权重
|
183
|
+
yield (port_std(w),port_ret(w),w)#计算风险和期望收益 以及组合的权重情况
|
184
|
+
|
185
|
+
# 投资组合模拟次数
|
186
|
+
print("\n Generating portfolio feasible set ...")
|
187
|
+
df=pd.DataFrame(gen_ports(25000),columns=["std","ret","w"])
|
188
|
+
#df.head()
|
189
|
+
std_min=df['std'].min()
|
190
|
+
std_max=df['std'].max()
|
191
|
+
|
192
|
+
#------------------------------------------------------------------------------
|
193
|
+
#计算可行集中每个投资组合期间内的夏普比率
|
194
|
+
df['sharpe'] = (df['ret'] - risk_free) / df['std']
|
195
|
+
#list(zip(r_annual.index, df.loc[df.sharpe.idxmax()].w))
|
196
|
+
|
197
|
+
# 画出投资可行集
|
198
|
+
df_ef=df.rename(columns={'std':'收益率标准差','ret':'收益率','sharpe':'夏普比率'})
|
199
|
+
fig, ax = plt.subplots()
|
200
|
+
titletxt="马科维茨投资组合示意图"
|
201
|
+
plt.title(titletxt)
|
202
|
+
|
203
|
+
#df.plot.scatter('std','ret',c='sharpe',s=30,alpha=0.3,cmap='cool',marker='o',ax=ax)
|
204
|
+
df_ef.plot.scatter('收益率标准差','收益率',c='夏普比率',s=30,alpha=0.3,cmap='cool',marker='o',ax=ax)
|
205
|
+
plt.style.use('ggplot')
|
206
|
+
plt.rcParams['axes.unicode_minus'] = False# 显示负号
|
207
|
+
|
208
|
+
#绘制有效边界曲线
|
209
|
+
if efficient_frontier:
|
210
|
+
frontier=pd.DataFrame(columns=['std','ret'])
|
211
|
+
for std in np.linspace(std_min,std_max):
|
212
|
+
res=opt.minimize(lambda x:-port_ret(x),
|
213
|
+
x0=((1/n),)*n,
|
214
|
+
method='SLSQP',
|
215
|
+
bounds=((0,1),)*n,
|
216
|
+
constraints=[
|
217
|
+
{"fun":lambda x:port_std(x)-std,"type":"eq"},
|
218
|
+
{"fun":lambda x:(np.sum(x)-1),"type":"eq"}
|
219
|
+
])
|
220
|
+
if res.success:
|
221
|
+
frontier=frontier._append({"std":std,"ret":-res.fun},ignore_index=True)
|
222
|
+
|
223
|
+
# 略微上调有效边界
|
224
|
+
frontier2=frontier.copy()
|
225
|
+
"""
|
226
|
+
fstd0=frontier2['std'].values[0]
|
227
|
+
frontier2['ret']=frontier2['ret'] * ef_adjust*fstd0/frontier2['std']
|
228
|
+
"""
|
229
|
+
frontier2['ret']=frontier2['ret'] * ef_adjust
|
230
|
+
frontier3=frontier2.rename(columns={'std':'收益率标准差','ret':'收益率'})
|
231
|
+
frontier3.plot('收益率标准差','收益率',label='有效边界',lw=3,c='blue',ax=ax)
|
232
|
+
plt.legend()
|
233
|
+
fig
|
234
|
+
|
235
|
+
#------------------------------------------------------------------------------
|
236
|
+
#单个投资组合的收益和风险
|
237
|
+
def one_ports(w):
|
238
|
+
return (port_std(w),port_ret(w),w)#计算风险和期望收益 以及组合的权重情况
|
239
|
+
|
240
|
+
# 计算最优资产配置情况
|
241
|
+
if MOP:
|
242
|
+
res=opt.minimize(lambda x:-((port_ret(x)-risk_free)/port_std(x)),
|
243
|
+
x0=((1/n),)*n,
|
244
|
+
method='SLSQP',
|
245
|
+
bounds=((0,1),)*n,
|
246
|
+
constraints={"fun":lambda x:(np.sum(x)-1), "type":"eq"})
|
247
|
+
|
248
|
+
ax.scatter(port_std(res.x),port_ret(res.x),label='MOP点',marker="*",c="brown",s=300)
|
249
|
+
ax.legend()
|
250
|
+
fig
|
251
|
+
|
252
|
+
print("\n***马科维茨优化后组合(MOP)配置:")
|
253
|
+
ticker_names=components.values()
|
254
|
+
best_proportion=res.x.round(3)
|
255
|
+
#best_config = dict(zip(tickers, best_proportion))
|
256
|
+
best_config = dict(zip(ticker_names, best_proportion))
|
257
|
+
print(best_config)
|
258
|
+
|
259
|
+
#计算期间内投资组合收益率均值
|
260
|
+
best_std,best_ret,_=one_ports(best_proportion)
|
261
|
+
print("收益率标准差:",round(best_std,4),"\b,投资组合收益率:",round(best_ret,4))
|
262
|
+
|
263
|
+
"""
|
264
|
+
#绘制MOP组合价格走势
|
265
|
+
stock_data2=stock_data.copy()
|
266
|
+
stock_data2['MOP']=stock_data2.dot(best_proportion)
|
267
|
+
(stock_data2/stock_data2.iloc[0]).plot()
|
268
|
+
|
269
|
+
titletxt='投资组合及其成分股价格走势示意图'
|
270
|
+
plt.xlabel('')
|
271
|
+
plt.ylabel("价格/起点值")
|
272
|
+
plt.title(titletxt)
|
273
|
+
plt.show()
|
274
|
+
"""
|
275
|
+
|
276
|
+
if MSR:
|
277
|
+
sharpe_max=df['sharpe'].max()
|
278
|
+
std_msr=df[df['sharpe']==sharpe_max]['std'].values[0]
|
279
|
+
ret_msr=df[df['sharpe']==sharpe_max]['ret'].values[0]
|
280
|
+
w_msr=df[df['sharpe']==sharpe_max]['w'].values[0]
|
281
|
+
|
282
|
+
ax.scatter(std_msr,ret_msr,label='MSR点',marker="*",c="orange",s=300)
|
283
|
+
ax.legend()
|
284
|
+
fig
|
285
|
+
|
286
|
+
print("\n***最大夏普比率组合(MSR)配置:")
|
287
|
+
ticker_names=components.values()
|
288
|
+
best_proportion=w_msr
|
289
|
+
best_config = dict(zip(ticker_names, best_proportion.round(3)))
|
290
|
+
print(best_config)
|
291
|
+
|
292
|
+
#计算期间内投资组合收益率均值
|
293
|
+
best_std,best_ret,_=one_ports(best_proportion)
|
294
|
+
print("收益率标准差:",round(best_std,4),"\b,投资组合收益率:",round(best_ret,4))
|
295
|
+
|
296
|
+
#绘制MOP组合价格走势
|
297
|
+
"""
|
298
|
+
stock_data3=stock_data.copy()
|
299
|
+
stock_data3['MOP']=stock_data3.dot(best_proportion)
|
300
|
+
(stock_data3/stock_data3.iloc[0]).plot()
|
301
|
+
|
302
|
+
titletxt='投资组合及其成分股价格走势示意图'
|
303
|
+
plt.xlabel('')
|
304
|
+
plt.ylabel("价格/起点值")
|
305
|
+
plt.title(titletxt)
|
306
|
+
plt.show()
|
307
|
+
"""
|
308
|
+
|
309
|
+
if MOP or MSR:
|
310
|
+
std_min=df['std'].min()
|
311
|
+
ret_gmvs=df[df['std']==std_min]['ret'].values[0]
|
312
|
+
w_gmvs=df[df['std']==std_min]['w'].values[0]
|
313
|
+
|
314
|
+
ax.scatter(std_min,ret_gmvs,label='LVS点',marker="o",c="green",s=300)
|
315
|
+
ax.legend()
|
316
|
+
fig
|
317
|
+
|
318
|
+
print("\n***最小波动风险组合(LVS)配置:")
|
319
|
+
ticker_names=components.values()
|
320
|
+
best_proportion=w_gmvs
|
321
|
+
best_config = dict(zip(ticker_names, best_proportion.round(3)))
|
322
|
+
print(best_config)
|
323
|
+
|
324
|
+
#计算期间内投资组合收益率均值
|
325
|
+
best_std,best_ret,_=one_ports(best_proportion)
|
326
|
+
print("收益率标准差:",round(best_std,4),"\b,投资组合收益率:",round(best_ret,4))
|
327
|
+
|
328
|
+
#绘制GMVS组合价格走势
|
329
|
+
"""
|
330
|
+
stock_data4=stock_data.copy()
|
331
|
+
stock_data4['GMVS']=stock_data4.dot(best_proportion)
|
332
|
+
(stock_data4/stock_data4.iloc[0]).plot()
|
333
|
+
|
334
|
+
titletxt='投资组合及其成分股价格走势示意图'
|
335
|
+
plt.xlabel('')
|
336
|
+
plt.ylabel("价格/起点值")
|
337
|
+
plt.title(titletxt)
|
338
|
+
plt.show()
|
339
|
+
"""
|
340
|
+
|
341
|
+
return
|
342
|
+
|
343
|
+
|
344
|
+
#------------------------------------------------------------------------------
|
345
|
+
#------------------------------------------------------------------------------
|
346
|
+
#------------------------------------------------------------------------------
|
347
|
+
#------------------------------------------------------------------------------
|
348
|
+
#------------------------------------------------------------------------------
|
349
|
+
#------------------------------------------------------------------------------
|
350
|
+
#------------------------------------------------------------------------------
|
351
|
+
#------------------------------------------------------------------------------
|
352
|
+
#------------------------------------------------------------------------------
|
353
|
+
#------------------------------------------------------------------------------
|
354
|
+
#------------------------------------------------------------------------------
|
355
|
+
|
356
|
+
|
357
|
+
|
358
|
+
|
359
|
+
|
360
|
+
|
361
|
+
|
362
|
+
|
363
|
+
|
364
|
+
|
365
|
+
|
366
|
+
|
367
|
+
|
368
|
+
|
369
|
+
|
370
|
+
|
371
|
+
|
372
|
+
|
373
|
+
|