siat 2.2.6__py3-none-any.whl → 2.3.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- siat/allin.py +3 -0
- siat/markowitz_simple.py +360 -0
- siat/test_markowitz_simple.py +198 -0
- siat/test_markowitz_simple_revised.py +215 -0
- siat/test_markowitz_simple_revised2.py +218 -0
- {siat-2.2.6.dist-info → siat-2.3.0.dist-info}/METADATA +1 -1
- {siat-2.2.6.dist-info → siat-2.3.0.dist-info}/RECORD +9 -5
- {siat-2.2.6.dist-info → siat-2.3.0.dist-info}/WHEEL +0 -0
- {siat-2.2.6.dist-info → siat-2.3.0.dist-info}/top_level.txt +0 -0
siat/allin.py
CHANGED
siat/markowitz_simple.py
ADDED
@@ -0,0 +1,360 @@
|
|
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
|
+
import seaborn as sns
|
67
|
+
|
68
|
+
#==============================================================================
|
69
|
+
if __name__=='__main__':
|
70
|
+
components = {
|
71
|
+
'AAPL':'苹果',
|
72
|
+
'AMZN':'亚马逊',
|
73
|
+
'GOOGL':'谷歌',
|
74
|
+
'BABA':'阿里巴巴'
|
75
|
+
}
|
76
|
+
|
77
|
+
start='2016-1-1'
|
78
|
+
end='2017-12-31'
|
79
|
+
|
80
|
+
risk_free=0.015
|
81
|
+
simulation=25000
|
82
|
+
price_trend=True
|
83
|
+
feasible_set=True
|
84
|
+
efficient_frontier=True
|
85
|
+
MOP=True #Markowitz Optimized Point
|
86
|
+
MSR=True #Maximized Sharpe Ratio
|
87
|
+
|
88
|
+
ef_adjust=1.008
|
89
|
+
|
90
|
+
markowitz_sharpe(components,start,end)
|
91
|
+
markowitz_sharpe(components,start,end,ef_adjust=1.008)
|
92
|
+
markowitz_sharpe(components,start,end,MOP=True)
|
93
|
+
markowitz_sharpe(components,start,end,MSR=True)
|
94
|
+
markowitz_sharpe(components,start,end,MOP=True,MSR=True)
|
95
|
+
|
96
|
+
def markowitz_sharpe(components,start,end,risk_free=0.015,simulation=25000, \
|
97
|
+
price_trend=True,feasible_set=True,efficient_frontier=True, \
|
98
|
+
MOP=False,MSR=False,ef_adjust=1.008):
|
99
|
+
"""
|
100
|
+
功能:使用期间内夏普比率寻找马科维茨最优点,绘制可行集、有效边界和最优点
|
101
|
+
components:投资组合成分股票代码与名称,节省搜索股票名称的时间
|
102
|
+
start,end:开始/结束日期
|
103
|
+
risk_free:人工指定无风险利率,节省搜索时间,减少搜索失败概率
|
104
|
+
simulation:生成可行集的模拟次数
|
105
|
+
price_trend:是否绘制各个成分股票的价格走势,采用股价/起点股价的比值,可一图绘制多只股票
|
106
|
+
feasible_set:是否绘制可行集
|
107
|
+
efficient_frontier:是否绘制有效边界
|
108
|
+
MOP:是否标注MOP点,Markowitz Optimized Point,可能与MSR点不同
|
109
|
+
MSR:是否标注MSR点,Maximized Sharpe Ratio,可能与MOP点不同
|
110
|
+
ef_adjust:对有效边界曲线微调,使其处于可行集的上边沿
|
111
|
+
"""
|
112
|
+
#获取股票数据
|
113
|
+
tickers=list(components)
|
114
|
+
stock_data=get_prices(tickers,start,end)['Close']
|
115
|
+
stock_data.rename(columns=components,inplace=True)
|
116
|
+
|
117
|
+
stock_data=stock_data.iloc[::-1]
|
118
|
+
#stock_data.head()
|
119
|
+
|
120
|
+
#画出收盘价走势图
|
121
|
+
sns.set_style("whitegrid")#横坐标有标线,纵坐标没有标线,背景白色
|
122
|
+
sns.set_style("darkgrid") #默认,横纵坐标都有标线,组成一个一个格子,背景稍微深色
|
123
|
+
sns.set_style("dark")#背景稍微深色,没有标线线
|
124
|
+
sns.set_style("white")#背景白色,没有标线线
|
125
|
+
sns.set_style("ticks")#xy轴都有非常短的小刻度
|
126
|
+
sns.despine(offset=30,left=True)#去掉上边和右边的轴线,offset=30表示距离轴线(x轴)的距离,left=True表示左边的轴保留
|
127
|
+
sns.set(font='SimHei',rc={'figure.figsize':(10,6)})# 图片大小和中文字体设置
|
128
|
+
|
129
|
+
# 绘制各个成分股票的价格走势,采用股价/起点股价的比值,可一图绘制多只股票
|
130
|
+
if price_trend:
|
131
|
+
(stock_data/stock_data.iloc[0]).plot()
|
132
|
+
titletxt='投资组合的成分股价格走势示意图'
|
133
|
+
plt.xlabel('')
|
134
|
+
plt.ylabel("价格/起点值")
|
135
|
+
plt.title(titletxt)
|
136
|
+
plt.show()
|
137
|
+
|
138
|
+
#------------------------------------------------------------------------------
|
139
|
+
# 计算收益率和风险
|
140
|
+
# 收益率
|
141
|
+
R=stock_data/stock_data.shift(1)-1
|
142
|
+
#R.head()
|
143
|
+
|
144
|
+
# 对数收益率
|
145
|
+
log_r=np.log(stock_data/stock_data.shift(1))
|
146
|
+
#log_r.head()
|
147
|
+
|
148
|
+
# 年化收益率
|
149
|
+
r_annual=np.exp(log_r.mean()*250)-1
|
150
|
+
#r_annual
|
151
|
+
|
152
|
+
# 风险
|
153
|
+
std = np.sqrt(log_r.var() * 250)#假设协方差为0
|
154
|
+
#std
|
155
|
+
|
156
|
+
#------------------------------------------------------------------------------
|
157
|
+
# 投资组合的收益和风险
|
158
|
+
def gen_weights(n):
|
159
|
+
w=np.random.rand(n)
|
160
|
+
return w /sum(w)
|
161
|
+
|
162
|
+
n=len(list(tickers))
|
163
|
+
w=gen_weights(n)
|
164
|
+
#list(zip(r_annual.index,w))
|
165
|
+
|
166
|
+
#投资组合收益
|
167
|
+
def port_ret(w):
|
168
|
+
return -np.sum(w*r_annual)
|
169
|
+
#port_ret(w)
|
170
|
+
|
171
|
+
#投资组合的风险
|
172
|
+
def port_std(w):
|
173
|
+
return np.sqrt((w.dot(log_r.cov()*250).dot(w.T)))
|
174
|
+
#port_std(w)
|
175
|
+
|
176
|
+
#若干投资组合的收益和风险
|
177
|
+
def gen_ports(times):
|
178
|
+
for _ in range(times):#生成不同的组合
|
179
|
+
w=gen_weights(n)#每次生成不同的权重
|
180
|
+
yield (port_std(w),port_ret(w),w)#计算风险和期望收益 以及组合的权重情况
|
181
|
+
|
182
|
+
# 投资组合模拟次数
|
183
|
+
print("\n Generating portfolio feasible set ...")
|
184
|
+
df=pd.DataFrame(gen_ports(25000),columns=["std","ret","w"])
|
185
|
+
#df.head()
|
186
|
+
std_min=df['std'].min()
|
187
|
+
std_max=df['std'].max()
|
188
|
+
|
189
|
+
#------------------------------------------------------------------------------
|
190
|
+
#计算可行集中每个投资组合期间内的夏普比率
|
191
|
+
df['sharpe'] = (df['ret'] - risk_free) / df['std']
|
192
|
+
#list(zip(r_annual.index, df.loc[df.sharpe.idxmax()].w))
|
193
|
+
|
194
|
+
# 画出投资可行集
|
195
|
+
df_ef=df.rename(columns={'std':'收益率标准差','ret':'收益率','sharpe':'夏普比率'})
|
196
|
+
fig, ax = plt.subplots()
|
197
|
+
titletxt="马科维茨投资组合示意图"
|
198
|
+
plt.title(titletxt)
|
199
|
+
|
200
|
+
#df.plot.scatter('std','ret',c='sharpe',s=30,alpha=0.3,cmap='cool',marker='o',ax=ax)
|
201
|
+
df_ef.plot.scatter('收益率标准差','收益率',c='夏普比率',s=30,alpha=0.3,cmap='cool',marker='o',ax=ax)
|
202
|
+
plt.style.use('ggplot')
|
203
|
+
plt.rcParams['axes.unicode_minus'] = False# 显示负号
|
204
|
+
|
205
|
+
#绘制有效边界曲线
|
206
|
+
if efficient_frontier:
|
207
|
+
frontier=pd.DataFrame(columns=['std','ret'])
|
208
|
+
for std in np.linspace(std_min,std_max):
|
209
|
+
res=opt.minimize(lambda x:-port_ret(x),
|
210
|
+
x0=((1/n),)*n,
|
211
|
+
method='SLSQP',
|
212
|
+
bounds=((0,1),)*n,
|
213
|
+
constraints=[
|
214
|
+
{"fun":lambda x:port_std(x)-std,"type":"eq"},
|
215
|
+
{"fun":lambda x:(np.sum(x)-1),"type":"eq"}
|
216
|
+
])
|
217
|
+
if res.success:
|
218
|
+
frontier=frontier.append({"std":std,"ret":-res.fun},ignore_index=True)
|
219
|
+
|
220
|
+
# 略微上调有效边界
|
221
|
+
frontier2=frontier.copy()
|
222
|
+
"""
|
223
|
+
fstd0=frontier2['std'].values[0]
|
224
|
+
frontier2['ret']=frontier2['ret'] * ef_adjust*fstd0/frontier2['std']
|
225
|
+
"""
|
226
|
+
frontier2['ret']=frontier2['ret'] * ef_adjust
|
227
|
+
frontier3=frontier2.rename(columns={'std':'收益率标准差','ret':'收益率'})
|
228
|
+
frontier3.plot('收益率标准差','收益率',label='有效边界',lw=3,c='blue',ax=ax)
|
229
|
+
plt.legend()
|
230
|
+
fig
|
231
|
+
|
232
|
+
#------------------------------------------------------------------------------
|
233
|
+
#单个投资组合的收益和风险
|
234
|
+
def one_ports(w):
|
235
|
+
return (port_std(w),port_ret(w),w)#计算风险和期望收益 以及组合的权重情况
|
236
|
+
|
237
|
+
# 计算最优资产配置情况
|
238
|
+
if MOP:
|
239
|
+
res=opt.minimize(lambda x:-((port_ret(x)-risk_free)/port_std(x)),
|
240
|
+
x0=((1/n),)*n,
|
241
|
+
method='SLSQP',
|
242
|
+
bounds=((0,1),)*n,
|
243
|
+
constraints={"fun":lambda x:(np.sum(x)-1), "type":"eq"})
|
244
|
+
|
245
|
+
ax.scatter(port_std(res.x),port_ret(res.x),label='MOP点',marker="*",c="green",s=300)
|
246
|
+
ax.legend()
|
247
|
+
fig
|
248
|
+
|
249
|
+
print("\n**MOP portfolio configuration:")
|
250
|
+
best_proportion=res.x.round(3)
|
251
|
+
best_config = dict(zip(tickers, best_proportion))
|
252
|
+
print(best_config)
|
253
|
+
|
254
|
+
#计算期间内投资组合收益率均值
|
255
|
+
best_std,best_ret,_=one_ports(best_proportion)
|
256
|
+
print("std =",round(best_std,4),"return =",round(best_ret,2))
|
257
|
+
|
258
|
+
#绘制MOP组合价格走势
|
259
|
+
stock_data2=stock_data.copy()
|
260
|
+
stock_data2['MOP']=stock_data2.dot(best_proportion)
|
261
|
+
(stock_data2/stock_data2.iloc[0]).plot()
|
262
|
+
|
263
|
+
titletxt='投资组合及其成分股价格走势示意图'
|
264
|
+
plt.xlabel('')
|
265
|
+
plt.ylabel("价格/起点值")
|
266
|
+
plt.title(titletxt)
|
267
|
+
plt.show()
|
268
|
+
|
269
|
+
if MSR:
|
270
|
+
sharpe_max=df['sharpe'].max()
|
271
|
+
std_msr=df[df['sharpe']==sharpe_max]['std'].values[0]
|
272
|
+
ret_msr=df[df['sharpe']==sharpe_max]['ret'].values[0]
|
273
|
+
w_msr=df[df['sharpe']==sharpe_max]['w'].values[0]
|
274
|
+
|
275
|
+
ax.scatter(std_msr,ret_msr,label='MSR点',marker="*",c="black",s=300)
|
276
|
+
ax.legend()
|
277
|
+
fig
|
278
|
+
|
279
|
+
print("\n**MSR portfolio configuration:")
|
280
|
+
best_proportion=w_msr
|
281
|
+
best_config = dict(zip(tickers, best_proportion))
|
282
|
+
print(best_config)
|
283
|
+
|
284
|
+
#计算期间内投资组合收益率均值
|
285
|
+
best_std,best_ret,_=one_ports(best_proportion)
|
286
|
+
print("std =",round(best_std,4),"return =",round(best_ret,2))
|
287
|
+
|
288
|
+
#绘制MOP组合价格走势
|
289
|
+
stock_data3=stock_data.copy()
|
290
|
+
stock_data3['MOP']=stock_data3.dot(best_proportion)
|
291
|
+
(stock_data3/stock_data3.iloc[0]).plot()
|
292
|
+
|
293
|
+
titletxt='投资组合及其成分股价格走势示意图'
|
294
|
+
plt.xlabel('')
|
295
|
+
plt.ylabel("价格/起点值")
|
296
|
+
plt.title(titletxt)
|
297
|
+
plt.show()
|
298
|
+
|
299
|
+
if MOP or MSR:
|
300
|
+
std_min=df['std'].min()
|
301
|
+
ret_gmvs=df[df['std']==std_min]['ret'].values[0]
|
302
|
+
w_gmvs=df[df['std']==std_min]['w'].values[0]
|
303
|
+
|
304
|
+
ax.scatter(std_min,ret_gmvs,label='GMVS点',marker="^",c="orange",s=300)
|
305
|
+
ax.legend()
|
306
|
+
fig
|
307
|
+
|
308
|
+
print("\n**GMVS portfolio configuration:")
|
309
|
+
best_proportion=w_gmvs
|
310
|
+
best_config = dict(zip(tickers, best_proportion.round(3)))
|
311
|
+
print(best_config)
|
312
|
+
|
313
|
+
#计算期间内投资组合收益率均值
|
314
|
+
best_std,best_ret,_=one_ports(best_proportion)
|
315
|
+
print("std =",round(best_std,4),"return =",round(best_ret,2))
|
316
|
+
|
317
|
+
#绘制GMVS组合价格走势
|
318
|
+
stock_data4=stock_data.copy()
|
319
|
+
stock_data4['GMVS']=stock_data4.dot(best_proportion)
|
320
|
+
(stock_data4/stock_data4.iloc[0]).plot()
|
321
|
+
|
322
|
+
titletxt='投资组合及其成分股价格走势示意图'
|
323
|
+
plt.xlabel('')
|
324
|
+
plt.ylabel("价格/起点值")
|
325
|
+
plt.title(titletxt)
|
326
|
+
plt.show()
|
327
|
+
|
328
|
+
return
|
329
|
+
|
330
|
+
|
331
|
+
#------------------------------------------------------------------------------
|
332
|
+
#------------------------------------------------------------------------------
|
333
|
+
#------------------------------------------------------------------------------
|
334
|
+
#------------------------------------------------------------------------------
|
335
|
+
#------------------------------------------------------------------------------
|
336
|
+
#------------------------------------------------------------------------------
|
337
|
+
#------------------------------------------------------------------------------
|
338
|
+
#------------------------------------------------------------------------------
|
339
|
+
#------------------------------------------------------------------------------
|
340
|
+
#------------------------------------------------------------------------------
|
341
|
+
#------------------------------------------------------------------------------
|
342
|
+
|
343
|
+
|
344
|
+
|
345
|
+
|
346
|
+
|
347
|
+
|
348
|
+
|
349
|
+
|
350
|
+
|
351
|
+
|
352
|
+
|
353
|
+
|
354
|
+
|
355
|
+
|
356
|
+
|
357
|
+
|
358
|
+
|
359
|
+
|
360
|
+
|
@@ -0,0 +1,198 @@
|
|
1
|
+
# -*- coding: utf-8 -*-
|
2
|
+
|
3
|
+
|
4
|
+
"""
|
5
|
+
马科维茨有效投资投资边界的基本思想
|
6
|
+
通过对资产组合当中不同资产的配置情况进行调整,达到在既定风险水平下的收益最大化,
|
7
|
+
或者既定收益水平下的风险最小化。
|
8
|
+
"""
|
9
|
+
|
10
|
+
from datetime import date
|
11
|
+
import pandas_datareader.data as web
|
12
|
+
import matplotlib.pyplot as plt
|
13
|
+
import numpy as np
|
14
|
+
import seaborn as sns
|
15
|
+
import warnings
|
16
|
+
warnings.filterwarnings("ignore")
|
17
|
+
%matplotlib inline
|
18
|
+
|
19
|
+
#获取股票数据
|
20
|
+
tickers = {
|
21
|
+
'AAPL':'苹果',
|
22
|
+
'AMZN':'亚马逊',
|
23
|
+
'GOOGL':'谷歌',
|
24
|
+
'BABA':'阿里巴巴'
|
25
|
+
}
|
26
|
+
|
27
|
+
data_source = 'stooq'#定义数据源的参数
|
28
|
+
|
29
|
+
start = date(2016,1,1)#起始时间
|
30
|
+
|
31
|
+
end = date(2017,12,31)#结束时间
|
32
|
+
|
33
|
+
stock_data = web.DataReader(list(tickers), data_source,start,end)["Close"]
|
34
|
+
|
35
|
+
stock_data.rename(columns=tickers,inplace=True)
|
36
|
+
|
37
|
+
stock_data=stock_data.iloc[::-1]
|
38
|
+
stock_data.head()
|
39
|
+
|
40
|
+
#画出收盘价走势图
|
41
|
+
sns.set_style("whitegrid")#横坐标有标线,纵坐标没有标线,背景白色
|
42
|
+
sns.set_style("darkgrid") #默认,横纵坐标都有标线,组成一个一个格子,背景稍微深色
|
43
|
+
sns.set_style("dark")#背景稍微深色,没有标线线
|
44
|
+
sns.set_style("white")#背景白色,没有标线线
|
45
|
+
sns.set_style("ticks")#xy轴都有非常短的小刻度
|
46
|
+
sns.despine(offset=30,left=True)#去掉上边和右边的轴线,offset=30表示距离轴线(x轴)的距离,left=True表示左边的轴保留
|
47
|
+
|
48
|
+
|
49
|
+
sns.set(font='SimHei',rc={'figure.figsize':(10,6)})# 图片大小和中文字体设置
|
50
|
+
# 图形展示
|
51
|
+
|
52
|
+
# name=input("股票名字")
|
53
|
+
# stock_data.iloc[0]含有字样Symbols
|
54
|
+
(stock_data/stock_data.iloc[0]).plot()
|
55
|
+
|
56
|
+
|
57
|
+
#------------------------------------------------------------------------------
|
58
|
+
# 计算收益率和风险
|
59
|
+
# 收益率
|
60
|
+
R=stock_data/stock_data.shift(1)-1
|
61
|
+
R.head()
|
62
|
+
|
63
|
+
# 对数收益率
|
64
|
+
log_r=np.log(stock_data/stock_data.shift(1))
|
65
|
+
log_r.head()
|
66
|
+
|
67
|
+
# 年化收益率
|
68
|
+
r_annual=np.exp(log_r.mean()*250)-1
|
69
|
+
r_annual
|
70
|
+
|
71
|
+
#------------------------------------------------------------------------------
|
72
|
+
# 风险
|
73
|
+
std = np.sqrt(log_r.var() * 250)#假设协方差为0
|
74
|
+
std
|
75
|
+
|
76
|
+
#------------------------------------------------------------------------------
|
77
|
+
# 投资组合的收益和风险
|
78
|
+
def gen_weights(n):
|
79
|
+
w=np.random.rand(n)
|
80
|
+
return w /sum(w)
|
81
|
+
|
82
|
+
n=len(list(tickers))
|
83
|
+
w=gen_weights(n)
|
84
|
+
list(zip(r_annual.index,w))
|
85
|
+
|
86
|
+
#投资组合收益
|
87
|
+
def port_ret(w):
|
88
|
+
return np.sum(w*r_annual)
|
89
|
+
port_ret(w)
|
90
|
+
|
91
|
+
#投资组合的风险
|
92
|
+
def port_std(w):
|
93
|
+
return np.sqrt((w.dot(log_r.cov()*250).dot(w.T)))
|
94
|
+
port_std(w)
|
95
|
+
|
96
|
+
#若干投资组合的收益和风险
|
97
|
+
def gen_ports(times):
|
98
|
+
for _ in range(times):#生成不同的组合
|
99
|
+
w=gen_weights(n)#每次生成不同的权重
|
100
|
+
yield (port_std(w),port_ret(w),w)#计算风险和期望收益 以及组合的权重情况
|
101
|
+
|
102
|
+
import pandas as pd
|
103
|
+
# 投资组合模拟次数
|
104
|
+
df=pd.DataFrame(gen_ports(25000),columns=["std","ret","w"])
|
105
|
+
df.head()
|
106
|
+
|
107
|
+
|
108
|
+
|
109
|
+
#------------------------------------------------------------------------------
|
110
|
+
|
111
|
+
# 引入夏普比率
|
112
|
+
# 假设无风险利率为0.03,画出投资有效边界
|
113
|
+
df['sharpe'] = (df['ret'] - 0.015) / df['std']#定义夏普比率
|
114
|
+
fig, ax = plt.subplots()
|
115
|
+
df.plot.scatter('std', 'ret', c='sharpe',s=30, alpha=0.3, cmap='cool',marker='o', ax=ax)
|
116
|
+
plt.style.use('ggplot')
|
117
|
+
plt.rcParams['axes.unicode_minus'] = False# 显示负号
|
118
|
+
|
119
|
+
list(zip(r_annual.index, df.loc[df.sharpe.idxmax()].w))
|
120
|
+
|
121
|
+
|
122
|
+
import scipy.optimize as opt
|
123
|
+
frontier=pd.DataFrame(columns=['std','ret'])
|
124
|
+
|
125
|
+
# std的范围:0.16,0.25
|
126
|
+
for std in np.linspace(0.16,0.25):
|
127
|
+
#for std in np.linspace(0.16,0.26):
|
128
|
+
res=opt.minimize(lambda x:-port_ret(x),
|
129
|
+
x0=((1/n),)*n,
|
130
|
+
method='SLSQP',
|
131
|
+
bounds=((0,1),)*n,
|
132
|
+
constraints=[
|
133
|
+
{"fun":lambda x:port_std(x)-std,"type":"eq"},
|
134
|
+
{"fun":lambda x:(np.sum(x)-1),"type":"eq"}
|
135
|
+
])
|
136
|
+
if res.success:
|
137
|
+
frontier=frontier.append({"std":std,"ret":-res.fun},ignore_index=True)
|
138
|
+
frontier.plot('std','ret',lw=3,c='blue',ax=ax)
|
139
|
+
|
140
|
+
fig
|
141
|
+
|
142
|
+
|
143
|
+
|
144
|
+
#------------------------------------------------------------------------------
|
145
|
+
# 计算最优资产配置情况
|
146
|
+
|
147
|
+
res=opt.minimize(lambda x:-((port_ret(x)-0.03)/port_std(x)),
|
148
|
+
x0=((1/n),)*n,
|
149
|
+
method='SLSQP',
|
150
|
+
bounds=((0,1),)*n,
|
151
|
+
constraints={"fun":lambda x:(np.sum(x)-1), "type":"eq"})
|
152
|
+
|
153
|
+
res.x.round(3)
|
154
|
+
|
155
|
+
ax.scatter(port_std(res.x),port_ret(res.x),marker="*",c="black",s=300)
|
156
|
+
fig
|
157
|
+
|
158
|
+
#------------------------------------------------------------------------------
|
159
|
+
# 绘制资本市场线CML=Capital Market Line
|
160
|
+
ax.plot((0,.27),(.03,-res.fun*.27+.03))
|
161
|
+
fig
|
162
|
+
|
163
|
+
"""
|
164
|
+
在上图的所示资本市场线上,星号左边表示将资本用于投资一部分无风险资产和一部分风险资产组合,
|
165
|
+
而在星号处代表将所有的资本都用于投资风险资产组合,
|
166
|
+
星号右边意味着借入无风险资产并投资于风险资产组合,可以在相同的风险水平下获得更高的收益。
|
167
|
+
|
168
|
+
"""
|
169
|
+
#------------------------------------------------------------------------------
|
170
|
+
#------------------------------------------------------------------------------
|
171
|
+
#------------------------------------------------------------------------------
|
172
|
+
#------------------------------------------------------------------------------
|
173
|
+
#------------------------------------------------------------------------------
|
174
|
+
#------------------------------------------------------------------------------
|
175
|
+
#------------------------------------------------------------------------------
|
176
|
+
#------------------------------------------------------------------------------
|
177
|
+
#------------------------------------------------------------------------------
|
178
|
+
#------------------------------------------------------------------------------
|
179
|
+
#------------------------------------------------------------------------------
|
180
|
+
|
181
|
+
|
182
|
+
|
183
|
+
|
184
|
+
|
185
|
+
|
186
|
+
|
187
|
+
|
188
|
+
|
189
|
+
|
190
|
+
|
191
|
+
|
192
|
+
|
193
|
+
|
194
|
+
|
195
|
+
|
196
|
+
|
197
|
+
|
198
|
+
|
@@ -0,0 +1,215 @@
|
|
1
|
+
# -*- coding: utf-8 -*-
|
2
|
+
|
3
|
+
#==============================================================================
|
4
|
+
%matplotlib inline
|
5
|
+
|
6
|
+
# 小函数,使得过程逻辑更加清晰
|
7
|
+
def gen_weights(n):
|
8
|
+
"""
|
9
|
+
产生投资组合各个成分股的随机权重
|
10
|
+
"""
|
11
|
+
import numpy as np
|
12
|
+
w=np.random.rand(n)
|
13
|
+
return w /sum(w)
|
14
|
+
|
15
|
+
def port_ret(w,r_annual):
|
16
|
+
"""
|
17
|
+
计算投资组合的年化收益率
|
18
|
+
"""
|
19
|
+
import numpy as np
|
20
|
+
return np.sum(w*r_annual)
|
21
|
+
|
22
|
+
def port_std(w,log_r):
|
23
|
+
"""
|
24
|
+
计算投资组合的年化标准差
|
25
|
+
"""
|
26
|
+
import numpy as np
|
27
|
+
return np.sqrt((w.dot(log_r.cov()*250).dot(w.T)))
|
28
|
+
|
29
|
+
|
30
|
+
def gen_ports(n,times,log_r,r_annual):
|
31
|
+
#生成若干投资组合的收益和风险
|
32
|
+
for _ in range(times):#生成不同的组合
|
33
|
+
w=gen_weights(n)#每次生成不同的权重
|
34
|
+
yield (port_std(w,log_r),port_ret(w,r_annual),w)#计算风险和期望收益 以及组合的权重情况
|
35
|
+
|
36
|
+
#------------------------------------------------------------------------------
|
37
|
+
|
38
|
+
if __name__=='__main__':
|
39
|
+
components = {
|
40
|
+
'AAPL':'苹果',
|
41
|
+
'AMZN':'亚马逊',
|
42
|
+
'GOOGL':'谷歌',
|
43
|
+
'BABA':'阿里巴巴'
|
44
|
+
}
|
45
|
+
|
46
|
+
start='2016-1-1'
|
47
|
+
end='2017-12-31'
|
48
|
+
|
49
|
+
rf=0.015
|
50
|
+
simulation=25000
|
51
|
+
trend=True
|
52
|
+
ef=True
|
53
|
+
MSR=True
|
54
|
+
CML=True
|
55
|
+
|
56
|
+
markowitz_simple(components,start,end)
|
57
|
+
|
58
|
+
def markowitz_simple(components,start,end,rf=0.015,simulation=25000, \
|
59
|
+
trend=True,ef=True,MSR=True,CML=False):
|
60
|
+
"""
|
61
|
+
马科维茨有效投资投资边界的基本思想
|
62
|
+
通过对资产组合当中不同资产的配置情况进行调整,达到在既定风险水平下的收益最大化,
|
63
|
+
或者既定收益水平下的风险最小化。
|
64
|
+
"""
|
65
|
+
|
66
|
+
from datetime import date
|
67
|
+
import pandas_datareader.data as web
|
68
|
+
import matplotlib.pyplot as plt
|
69
|
+
import numpy as np
|
70
|
+
import seaborn as sns
|
71
|
+
import warnings
|
72
|
+
warnings.filterwarnings("ignore")
|
73
|
+
|
74
|
+
# 步骤1:获取股价
|
75
|
+
tickers=list(components)
|
76
|
+
stock_data=get_prices(tickers,start,end)['Close']
|
77
|
+
stock_data.rename(columns=components,inplace=True)
|
78
|
+
stock_data=stock_data.iloc[::-1]
|
79
|
+
|
80
|
+
#画出收盘价走势图
|
81
|
+
if trend:
|
82
|
+
sns.set_style("whitegrid")#横坐标有标线,纵坐标没有标线,背景白色
|
83
|
+
sns.set_style("darkgrid") #默认,横纵坐标都有标线,组成一个一个格子,背景稍微深色
|
84
|
+
sns.set_style("dark")#背景稍微深色,没有标线线
|
85
|
+
sns.set_style("white")#背景白色,没有标线线
|
86
|
+
sns.set_style("ticks")#xy轴都有非常短的小刻度
|
87
|
+
sns.despine(offset=30,left=True)#去掉上边和右边的轴线,offset=30表示距离轴线(x轴)的距离,left=True表示左边的轴保留
|
88
|
+
sns.set(font='SimHei',rc={'figure.figsize':(10,6)})# 图片大小和中文字体设置
|
89
|
+
|
90
|
+
# 图形展示
|
91
|
+
# stock_data.iloc[0]含有字样Symbols
|
92
|
+
(stock_data/stock_data.iloc[0]).plot()
|
93
|
+
|
94
|
+
#------------------------------------------------------------------------------
|
95
|
+
# 步骤2:计算股票的收益率和风险,假定每年有250个交易日
|
96
|
+
# 收益率
|
97
|
+
R=stock_data/stock_data.shift(1)-1
|
98
|
+
|
99
|
+
# 对数收益率
|
100
|
+
log_r=np.log(stock_data/stock_data.shift(1))
|
101
|
+
|
102
|
+
# 年化收益率
|
103
|
+
r_annual=np.exp(log_r.mean()*250)-1
|
104
|
+
|
105
|
+
# 风险
|
106
|
+
std = np.sqrt(log_r.var() * 250)#假设协方差为0
|
107
|
+
|
108
|
+
#------------------------------------------------------------------------------
|
109
|
+
# 步骤3:投资组合的收益和风险
|
110
|
+
|
111
|
+
n=len(list(tickers))
|
112
|
+
w=gen_weights(n)
|
113
|
+
#list(zip(r_annual.index,w))
|
114
|
+
|
115
|
+
import pandas as pd
|
116
|
+
# 投资组合模拟次数
|
117
|
+
df=pd.DataFrame(gen_ports(n,simulation,log_r,r_annual),columns=["std","ret","w"])
|
118
|
+
|
119
|
+
#------------------------------------------------------------------------------
|
120
|
+
|
121
|
+
# 步骤4:画出投资有效边界,假设无风险利率为rf
|
122
|
+
# 引入夏普比率
|
123
|
+
df['sharpe'] = (df['ret'] - rf) / df['std']#定义夏普比率
|
124
|
+
fig, ax = plt.subplots()
|
125
|
+
df.plot.scatter('std', 'ret', c='sharpe',s=30, alpha=0.3, cmap='cool',marker='o', ax=ax)
|
126
|
+
plt.style.use('ggplot')
|
127
|
+
plt.rcParams['axes.unicode_minus'] = False# 显示负号
|
128
|
+
|
129
|
+
#list(zip(r_annual.index, df.loc[df.sharpe.idxmax()].w))
|
130
|
+
|
131
|
+
|
132
|
+
import scipy.optimize as opt
|
133
|
+
frontier=pd.DataFrame(columns=['std','ret'])
|
134
|
+
|
135
|
+
# std的范围:0.16,0.25
|
136
|
+
std_min=round(df['std'].min(),2)
|
137
|
+
std_max=round(df['std'].max(),2)
|
138
|
+
#for std in np.linspace(0.16,0.25):
|
139
|
+
for std in np.linspace(std_min,std_max):
|
140
|
+
res=opt.minimize(lambda x:-port_ret(x,r_annual),
|
141
|
+
x0=((1/n),)*n,
|
142
|
+
method='SLSQP',
|
143
|
+
bounds=((0,1),)*n,
|
144
|
+
constraints=[
|
145
|
+
{"fun":lambda x:port_std(x,log_r)-std,"type":"eq"},
|
146
|
+
{"fun":lambda x:(np.sum(x)-1),"type":"eq"}
|
147
|
+
])
|
148
|
+
if res.success:
|
149
|
+
frontier=frontier.append({"std":std,"ret":-res.fun},ignore_index=True)
|
150
|
+
|
151
|
+
if ef:
|
152
|
+
frontier.plot('std','ret',lw=3,c='blue',ax=ax)
|
153
|
+
fig
|
154
|
+
|
155
|
+
#------------------------------------------------------------------------------
|
156
|
+
# 步骤5:计算最优资产配置情况
|
157
|
+
|
158
|
+
res=opt.minimize(lambda x:-((port_ret(x,r_annual)-0.03)/port_std(x,log_r)),
|
159
|
+
x0=((1/n),)*n,
|
160
|
+
method='SLSQP',
|
161
|
+
bounds=((0,1),)*n,
|
162
|
+
constraints={"fun":lambda x:(np.sum(x)-1), "type":"eq"})
|
163
|
+
|
164
|
+
print(res.x.round(3))
|
165
|
+
|
166
|
+
if MSR:
|
167
|
+
ax.scatter(port_std(res.x,log_r),port_ret(res.x,r_annual),marker="*",c="black",s=300)
|
168
|
+
fig
|
169
|
+
|
170
|
+
#------------------------------------------------------------------------------
|
171
|
+
# 步骤6:绘制资本市场线CML=Capital Market Line
|
172
|
+
if CML:
|
173
|
+
ax.plot((0,.27),(.03,-res.fun*.27+.03))
|
174
|
+
fig
|
175
|
+
|
176
|
+
"""
|
177
|
+
在上图的所示资本市场线上,星号左边表示将资本用于投资一部分无风险资产和一部分风险资产组合,
|
178
|
+
而在星号处代表将所有的资本都用于投资风险资产组合,
|
179
|
+
星号右边意味着借入无风险资产并投资于风险资产组合,可以在相同的风险水平下获得更高的收益。
|
180
|
+
|
181
|
+
"""
|
182
|
+
|
183
|
+
return
|
184
|
+
|
185
|
+
|
186
|
+
#------------------------------------------------------------------------------
|
187
|
+
#------------------------------------------------------------------------------
|
188
|
+
#------------------------------------------------------------------------------
|
189
|
+
#------------------------------------------------------------------------------
|
190
|
+
#------------------------------------------------------------------------------
|
191
|
+
#------------------------------------------------------------------------------
|
192
|
+
#------------------------------------------------------------------------------
|
193
|
+
#------------------------------------------------------------------------------
|
194
|
+
#------------------------------------------------------------------------------
|
195
|
+
#------------------------------------------------------------------------------
|
196
|
+
#------------------------------------------------------------------------------
|
197
|
+
|
198
|
+
|
199
|
+
|
200
|
+
|
201
|
+
|
202
|
+
|
203
|
+
|
204
|
+
|
205
|
+
|
206
|
+
|
207
|
+
|
208
|
+
|
209
|
+
|
210
|
+
|
211
|
+
|
212
|
+
|
213
|
+
|
214
|
+
|
215
|
+
|
@@ -0,0 +1,218 @@
|
|
1
|
+
# -*- coding: utf-8 -*-
|
2
|
+
|
3
|
+
|
4
|
+
|
5
|
+
#------------------------------------------------------------------------------
|
6
|
+
# 全局引用,函数中无需再import
|
7
|
+
from datetime import date
|
8
|
+
import pandas_datareader.data as web
|
9
|
+
import matplotlib.pyplot as plt
|
10
|
+
import numpy as np
|
11
|
+
import seaborn as sns
|
12
|
+
import warnings
|
13
|
+
warnings.filterwarnings("ignore")
|
14
|
+
%matplotlib inline
|
15
|
+
|
16
|
+
#------------------------------------------------------------------------------
|
17
|
+
if __name__=='__main__':
|
18
|
+
components = {
|
19
|
+
'AAPL':'苹果',
|
20
|
+
'AMZN':'亚马逊',
|
21
|
+
'GOOGL':'谷歌',
|
22
|
+
'BABA':'阿里巴巴'
|
23
|
+
}
|
24
|
+
|
25
|
+
start='2016-1-1'
|
26
|
+
end='2017-12-31'
|
27
|
+
|
28
|
+
risk_free=0.015
|
29
|
+
simulation=25000
|
30
|
+
price_trend=True
|
31
|
+
feasible_set=True
|
32
|
+
efficient_frontier=True
|
33
|
+
MSR=True
|
34
|
+
CML=True
|
35
|
+
|
36
|
+
|
37
|
+
"""
|
38
|
+
马科维茨有效投资投资边界的基本思想
|
39
|
+
通过对资产组合当中不同资产的配置情况进行调整,达到在既定风险水平下的收益最大化,
|
40
|
+
或者既定收益水平下的风险最小化。
|
41
|
+
"""
|
42
|
+
|
43
|
+
#------------------------------------------------------------------------------
|
44
|
+
|
45
|
+
#获取股票数据
|
46
|
+
tickers=list(components)
|
47
|
+
stock_data=get_prices(tickers,start,end)['Close']
|
48
|
+
stock_data.rename(columns=components,inplace=True)
|
49
|
+
|
50
|
+
stock_data=stock_data.iloc[::-1]
|
51
|
+
|
52
|
+
#画出收盘价走势图
|
53
|
+
if price_trend:
|
54
|
+
print("\n Illustrating price trend ...")
|
55
|
+
|
56
|
+
sns.set_style("whitegrid")#横坐标有标线,纵坐标没有标线,背景白色
|
57
|
+
sns.set_style("darkgrid") #默认,横纵坐标都有标线,组成一个一个格子,背景稍微深色
|
58
|
+
sns.set_style("dark")#背景稍微深色,没有标线线
|
59
|
+
sns.set_style("white")#背景白色,没有标线线
|
60
|
+
sns.set_style("ticks")#xy轴都有非常短的小刻度
|
61
|
+
sns.despine(offset=30,left=True)#去掉上边和右边的轴线,offset=30表示距离轴线(x轴)的距离,left=True表示左边的轴保留
|
62
|
+
sns.set(font='SimHei',rc={'figure.figsize':(10,6)})# 图片大小和中文字体设置
|
63
|
+
|
64
|
+
# 图形展示
|
65
|
+
(stock_data/stock_data.iloc[0]).plot()
|
66
|
+
|
67
|
+
#------------------------------------------------------------------------------
|
68
|
+
# 计算收益率和风险
|
69
|
+
# 收益率
|
70
|
+
R=stock_data/stock_data.shift(1)-1
|
71
|
+
|
72
|
+
# 对数收益率
|
73
|
+
log_r=np.log(stock_data/stock_data.shift(1))
|
74
|
+
|
75
|
+
# 年化收益率
|
76
|
+
r_annual=np.exp(log_r.mean()*250)-1
|
77
|
+
|
78
|
+
# 风险
|
79
|
+
std = np.sqrt(log_r.var() * 250)#假设协方差为0
|
80
|
+
|
81
|
+
#------------------------------------------------------------------------------
|
82
|
+
# 投资组合的收益和风险
|
83
|
+
def gen_weights(n):
|
84
|
+
#投资组合的权重
|
85
|
+
import numpy as np
|
86
|
+
w=np.random.rand(n)
|
87
|
+
return w /sum(w)
|
88
|
+
|
89
|
+
n=len(list(tickers))
|
90
|
+
w=gen_weights(n)
|
91
|
+
#list(zip(r_annual.index,w))
|
92
|
+
|
93
|
+
def port_ret(w,r_annual):
|
94
|
+
#投资组合收益
|
95
|
+
import numpy as np
|
96
|
+
return np.sum(w*r_annual)
|
97
|
+
#port_ret(w,r_annual)
|
98
|
+
|
99
|
+
def port_std(w,log_r):
|
100
|
+
#投资组合的风险
|
101
|
+
import numpy as np
|
102
|
+
return np.sqrt((w.dot(log_r.cov()*250).dot(w.T)))
|
103
|
+
#port_std(w,log_r)
|
104
|
+
|
105
|
+
def gen_ports(times,n,log_r,r_annual):
|
106
|
+
#若干投资组合的收益和风险
|
107
|
+
import pandas as pd
|
108
|
+
dft=pd.DataFrame(columns=["std","ret","w"])
|
109
|
+
for _ in range(times):#生成不同的组合
|
110
|
+
w=gen_weights(n)#每次生成不同的权重
|
111
|
+
dft=dft.append({"std":port_std(w,log_r),"ret":-port_ret(w,r_annual),"w":w},ignore_index=True)
|
112
|
+
#yield (port_std(w,log_r),port_ret(w,r_annual),w)#计算风险和期望收益 以及组合的权重情况
|
113
|
+
return dft
|
114
|
+
|
115
|
+
# 投资组合模拟次数
|
116
|
+
print("\n Generating portfolio feasible set ...")
|
117
|
+
df=gen_ports(simulation,n,log_r,r_annual)
|
118
|
+
std_min=df['std'].min()
|
119
|
+
std_max=df['std'].max()
|
120
|
+
#df.head()
|
121
|
+
|
122
|
+
#------------------------------------------------------------------------------
|
123
|
+
|
124
|
+
# 画出投资组合可行集
|
125
|
+
df['sharpe'] = (df['ret'] - risk_free) / df['std']#定义夏普比率
|
126
|
+
sharpe_max=df['sharpe'].max()
|
127
|
+
|
128
|
+
if feasible_set:
|
129
|
+
fig, ax = plt.subplots()
|
130
|
+
df.plot.scatter('std','ret',c='sharpe',s=30,alpha=0.3,cmap='cool',marker='o',ax=ax)
|
131
|
+
plt.style.use('ggplot')
|
132
|
+
plt.rcParams['axes.unicode_minus'] = False# 显示负号
|
133
|
+
|
134
|
+
#list(zip(r_annual.index, df.loc[df.sharpe.idxmax()].w))
|
135
|
+
|
136
|
+
# 画出投资组合有效集/有效边界
|
137
|
+
import scipy.optimize as opt
|
138
|
+
frontier=pd.DataFrame(columns=['std','ret'])
|
139
|
+
|
140
|
+
print("\n Calculating portfolio efficient frontier ...")
|
141
|
+
# std的范围:0.16,0.25
|
142
|
+
#for std in np.linspace(0.16,0.25):
|
143
|
+
for std in np.linspace(std_min,std_max):
|
144
|
+
res=opt.minimize(lambda x:port_ret(x,r_annual),
|
145
|
+
x0=((1/n),)*n,
|
146
|
+
method='SLSQP',
|
147
|
+
bounds=((0,1),)*n,
|
148
|
+
constraints=[
|
149
|
+
{"fun":lambda x:port_std(x,log_r)-std,"type":"eq"},
|
150
|
+
{"fun":lambda x:(np.sum(x)-1),"type":"eq"}
|
151
|
+
])
|
152
|
+
if res.success:
|
153
|
+
frontier=frontier.append({"std":std,"ret":-res.fun},ignore_index=True)
|
154
|
+
|
155
|
+
if efficient_frontier:
|
156
|
+
frontier.plot('std','ret',lw=3,c='blue',ax=ax)
|
157
|
+
fig
|
158
|
+
|
159
|
+
#------------------------------------------------------------------------------
|
160
|
+
# 计算最优资产配置情况
|
161
|
+
std_msr=df[df['sharpe']==sharpe_max]['std'].values[0]
|
162
|
+
ret_msr=df[df['sharpe']==sharpe_max]['ret'].values[0]
|
163
|
+
w_msr=df[df['sharpe']==sharpe_max]['w'].values[0]
|
164
|
+
res=opt.minimize(lambda x:-((port_ret(x,r_annual)-0.03)/port_std(x,log_r)),
|
165
|
+
x0=((1/n),)*n,
|
166
|
+
method='SLSQP',
|
167
|
+
bounds=((0,1),)*n,
|
168
|
+
constraints={"fun":lambda x:(np.sum(x)-1), "type":"eq"})
|
169
|
+
|
170
|
+
res.x.round(3)
|
171
|
+
|
172
|
+
if MSR:
|
173
|
+
#ax.scatter(port_std(res.x,log_r),-port_ret(res.x,r_annual),marker="*",c="black",s=300)
|
174
|
+
ax.scatter(std_msr,ret_msr,marker="*",c="black",s=300)
|
175
|
+
fig
|
176
|
+
|
177
|
+
#------------------------------------------------------------------------------
|
178
|
+
# 绘制资本市场线CML=Capital Market Line
|
179
|
+
if CML:
|
180
|
+
ax.plot((0,.27),(.03,-res.fun*.27+.03))
|
181
|
+
fig
|
182
|
+
|
183
|
+
"""
|
184
|
+
在上图的所示资本市场线上,星号左边表示将资本用于投资一部分无风险资产和一部分风险资产组合,
|
185
|
+
而在星号处代表将所有的资本都用于投资风险资产组合,
|
186
|
+
星号右边意味着借入无风险资产并投资于风险资产组合,可以在相同的风险水平下获得更高的收益。
|
187
|
+
|
188
|
+
"""
|
189
|
+
#------------------------------------------------------------------------------
|
190
|
+
#------------------------------------------------------------------------------
|
191
|
+
#------------------------------------------------------------------------------
|
192
|
+
#------------------------------------------------------------------------------
|
193
|
+
#------------------------------------------------------------------------------
|
194
|
+
#------------------------------------------------------------------------------
|
195
|
+
#------------------------------------------------------------------------------
|
196
|
+
#------------------------------------------------------------------------------
|
197
|
+
#------------------------------------------------------------------------------
|
198
|
+
#------------------------------------------------------------------------------
|
199
|
+
#------------------------------------------------------------------------------
|
200
|
+
|
201
|
+
|
202
|
+
|
203
|
+
|
204
|
+
|
205
|
+
|
206
|
+
|
207
|
+
|
208
|
+
|
209
|
+
|
210
|
+
|
211
|
+
|
212
|
+
|
213
|
+
|
214
|
+
|
215
|
+
|
216
|
+
|
217
|
+
|
218
|
+
|
@@ -1,5 +1,5 @@
|
|
1
1
|
siat/__init__.py,sha256=2dNozwJxztiXwgRY76YQjykPJwAK1SnpN1nNON42c4k,840
|
2
|
-
siat/allin.py,sha256=
|
2
|
+
siat/allin.py,sha256=ZhmWuTZvotYUj4nRd3ZJXd2QL81qfJafSut4KvDOD8A,2209
|
3
3
|
siat/alpha_vantage_test.py,sha256=tKr-vmuFH3CZAqwmISz6jzjPHzV1JJl3sPfZdz8aTfM,747
|
4
4
|
siat/assets_liquidity.py,sha256=ma-1rO_t_Mg3j_suWcySHkBoAl-H71CR1dm7iEGAfwM,28555
|
5
5
|
siat/assets_liquidity_test.py,sha256=UWk6HIUlizU7LQZ890fGx8LwU1jMMrIZswg8cFUJWZ8,1285
|
@@ -64,6 +64,7 @@ siat/markowitz.py,sha256=g3P-UripHV_VwtQetdGaPtfmRsFUxQICqmtF4Pp6C3k,95641
|
|
64
64
|
siat/markowitz_ccb_test.py,sha256=xBkkoaNHdq9KSUrNuHGgKTdNYUvgi84kNYcf719eoyE,1593
|
65
65
|
siat/markowitz_ef_test.py,sha256=wjNlICkgRIqnonPeSIHo4Mu2GRtb9dr21wDt2kMNEcI,4032
|
66
66
|
siat/markowitz_old.py,sha256=Lf7O_4QWT8RsdkHiUyc_7kKY3eZjKDtFR89Fz3pwYnY,33046
|
67
|
+
siat/markowitz_simple.py,sha256=tHmk7DnqoJWVBBXdcY3ezKwUVdNdu_Tm5QpJvBMGOT0,13748
|
67
68
|
siat/markowitz_test.py,sha256=fDXoPp6DrKeneYjd0lbb0KfYUJj-VcOvVaPlfsIOstw,5818
|
68
69
|
siat/markowitz_test2.py,sha256=FcVZqYU5va4567WGUVUJ7cMQdVbBGxeBAz82Y3BhCTI,2193
|
69
70
|
siat/ml_cases.py,sha256=FYDk0O7l9hhHlbrlOVGgbH-h2DA503lhKFi9XugH1f0,86874
|
@@ -104,6 +105,9 @@ siat/stock_test.py,sha256=E9YJAvOw1VEGJSDI4IZuEjl0tGoisOIlN-g9UqA_IZE,19475
|
|
104
105
|
siat/temp.py,sha256=gbJ0ioauuo4koTPH6WKUkqcXiQPafnbhU5eKJ6lpdLA,1571
|
105
106
|
siat/test2_graphviz.py,sha256=05w2YJuIBH0LsJjdA60EFn7rL0vCo-CA6EVJEQOXNE4,16648
|
106
107
|
siat/test_graphviz.py,sha256=CETKpDL8PnysS-PD3fHkeAgagUxjaUl0CsXPiadQySg,16999
|
108
|
+
siat/test_markowitz_simple.py,sha256=jAgwpkdMGxvjlfEg0I8qbyLQHDd5rErWqHgiqVvOJlY,6122
|
109
|
+
siat/test_markowitz_simple_revised.py,sha256=Tq44VTIjc75RR4_AMEWmU3-EW7TH4ZNEC6Zcer3fbmk,7407
|
110
|
+
siat/test_markowitz_simple_revised2.py,sha256=r0KzW9zvaP9BTdXyB2M3MhRKtzHDIituAflT9ZTR9bs,7361
|
107
111
|
siat/transaction.py,sha256=foTWS1qYXQFuzNTG2m7ec6aDgsJjzpKmyAbyxKcE8KU,14492
|
108
112
|
siat/transaction_test.py,sha256=Z8g1LJCN4-mnUByXMUMoFmN0t105cbmsz2QmvSuIkbU,18580
|
109
113
|
siat/translate-20230125.py,sha256=NPPSXhT38s5t9fzMvl_fvi4ckSB73ThLmZetVI-xGdU,117953
|
@@ -114,7 +118,7 @@ siat/universal_test.py,sha256=CDAOffW1Rvs-TcNN5giWVvHMlch1w4dp-w5SIV9jXL0,3936
|
|
114
118
|
siat/valuation_china.py,sha256=gYYXeT9bBPyQ251TCsYlibWcu6JA8x-YOKqLUEeLE7U,51342
|
115
119
|
siat/valuation_market_china_test.py,sha256=gbJ0ioauuo4koTPH6WKUkqcXiQPafnbhU5eKJ6lpdLA,1571
|
116
120
|
siat/var_model_validation.py,sha256=zB_Skk_tmzIR15l6oAW3am4HBGVIG-eZ8gJhCdXZ8Qw,14859
|
117
|
-
siat-2.
|
118
|
-
siat-2.
|
119
|
-
siat-2.
|
120
|
-
siat-2.
|
121
|
+
siat-2.3.0.dist-info/METADATA,sha256=HEihRI_gQaEfp2RJSCIMinGACKDI4zOAa4uB63nx-GM,1429
|
122
|
+
siat-2.3.0.dist-info/WHEEL,sha256=2wepM1nk4DS4eFpYrW1TTqPcoGNfHhhO_i5m4cOimbo,92
|
123
|
+
siat-2.3.0.dist-info/top_level.txt,sha256=r1cVyL7AIKqeAmEJjNR8FMT20OmEzufDstC2gv3NvEY,5
|
124
|
+
siat-2.3.0.dist-info/RECORD,,
|
File without changes
|
File without changes
|