0. Backgound
有效前沿是在给定投资范围,return-risk约束条件下同等风险情况下收益最大的的资产配置集合。
说白了,就是给一堆可投资券,求各种配比的组合下,相同return方差最小(或者相同方差return最大)的点集合。
更形象来说,就是在return-σ象限把投资组合的各种配比可能性都点在图上,左上方的edge就是这个有效前沿。
1. 导入模块
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
#用于正常显示中文标签
plt.rcParams["font.sans-serif"]=["SimHei"]
plt.rcParams["axes.unicode_minus"] = False
# 启动windpy接口
from WindPy import w
w.start()
2. 准备函数
def risk_free_rate(date):
r = w.wsd("SHIBOR6M.IR", "close,settle", date, date, "")
if r.ErrorCode !=0:
print("WIND数据读取有误,ErrorCode=" + str(r.ErrorCode))
sys.exit()
r = r.Data[0][0]/100
return r
def stock_close_data(stock_list,start_date,end_date):
stock_input = ",".join(stock_list)
data = w.wsd(stock_input, "close",start_date , end_date, "PriceAdj=F") #使用前复权处理
if data.ErrorCode!=0:
print("WIND数据读取有误,ErrorCode="+r.ErrorCode)
sys.exit()
print(data)
data = pd.DataFrame(data.Data,index = stock_list,columns = data.Times).T
return data
def generate_random_weight(num, stock_list):
weight = np.random.uniform(1,100,size = [num,len(stock_list)])
for i in range(0, num):
a_sum = 0.0
for j in range(0,len(stock_list)):
a_sum = a_sum +weight[i][j]
for k in range(0,len(stock_list)):
weight[i][k]=round(float(weight[i][k]/a_sum),4)
print("随机权重Ready!")
return weight
def portfolio_return(weight, mean, num, stock_list):
portfolio_re = np.random.uniform(0,0,size =num)
for i in range(0,num):
for j in range(0,len(stock_list)):
portfolio_re[i] = portfolio_re[i] + weight[i][j] * mean[j]
print("收益计算OKK!")
return portfolio_re
def portfolio_standard_deviation(weight, cov_matrix, num, stock_list):
portfolio_standard_dev = np.random.uniform(0,0,size=num)
for i in range(0, num):
var = np.dot(weight[i],cov_matrix)
var = np.dot(var,weight[i].T) # 组合方差
portfolio_standard_dev[i] = np.sqrt(var)
print("标准差搞定!")
return portfolio_standard_dev
def max_portfolio_return(p_return):
'''收益最大组合'''
p_return_list = list(p_return)
p_return_max = max(p_return_list)
p_return_max_index = p_return_list.index(p_return_max)
return p_return_max_index, p_return_max
def min_portfolio_std(p_std):
'''方差最小组合'''
p_std_list = list(p_std)
p_std_min = min(p_std_list)
p_std_min_index = p_std_list.index(p_std_min)
return p_std_min_index, p_std_min
def compute_sharp_ratio(returns, s_deviation, rfr):
'''
计算各组合的sharp_r = sharp_ratio_list, max_spr, max_spr_index
'''
sharp_ratio = np.random.uniform(0,0,len(returns))
for i in range(0,len(sharp_ratio)):
sharp_ratio[i] = (returns[i] - rfr) / s_deviation[i]
sharp_ratio_list = list(sharp_ratio)
return sharp_ratio, max(sharp_ratio_list), sharp_ratio_list.index(max(sharp_ratio_list))
def show_frontier(returns, s_deviation, max_return, min_std,sharp_r):
# 设置坐标轴的lable
plt.xlabel(" σ ")
plt.ylabel(" return % ")
colors1 = "#0080FF" #组合点的颜色
colors2 = "#CC0000" #最大收益点
colors3 = "#669900" #最小方差点
colors4 = "#FE9A2E" #最大sharpRatio
s = np.pi * 0.4 ** 2 # 普通组合点的大小
s1 = np.pi * 2 ** 2 # 最大瘦一点、最小方差点大小
plt.title("马科维茨有效前沿")
plt.scatter(s_deviation, returns, c=colors1, alpha=0.2,s=s)
plt.scatter(s_deviation[max_return[0]],max_return[1],c=colors2,alpha=0.8, s=s1, label = "最大收益")
plt.scatter(min_std[1],returns[min_std[0]],c=colors3,alpha=0.8,s=s1, label = "最小方差")
plt.scatter(s_deviation[sharp_r[2]],returns[sharp_r[2]],c=colors4,alpha = 0.8,s=s1, label = "最大SharpRatio")
plt.legend(loc = "best")
plt.plot()
plt.show()
return
3. 取数、作图
stock_list = ["600159.SH","000858.SZ","000615.SZ","300015.SZ","601318.SH"]
start_date = "2019-01-01"
end_date = "2020-04-23"
num = 50000 #生成多少个组合
# 计算一下无风险收益率
r = risk_free_rate("2020-04-23")
data = stock_close_data(stock_list,start_date,end_date)
daily_return = np.log(data/data.shift(1))
# daily_return = daily_return.shift(1)
mean = daily_return.mean() * 252 #年化
cov_matrix = daily_return.cov() * 252
weight = generate_random_weight(num, stock_list)
ptf_return = portfolio_return(weight,mean,num,stock_list)
ptf_std = portfolio_standard_deviation(weight, cov_matrix, num, stock_list)
# 最大收益率和最小方差
max_return= max_portfolio_return(ptf_return)
min_std=min_portfolio_std(ptf_std)
# 找Sharp Ratio
# sharp_r = sharp_ratio_list, max_spr, max_spr_index
sharp_r = compute_sharp_ratio(ptf_return, ptf_std, r)
show_frontier(ptf_return,ptf_std,max_return,min_std,sharp_r)
image.png
4. 总结
stock list乱拉了好多试,发现组合可选的券多起来以后,有效前沿的样子会没有那么完美,但是list短短的时候,样子可能会及其好看(然而并没有什么用处)
num=50000不变的情况下
比如只用3个股票的时候
image.png
用20个股票的时候
image.png
啊这个复杂又魔幻的世界= =