pyhon非线性规划最优资产组合
作者:互联网
pyhon非线性规划最优资产组合
数据集格式csv
import pandas as pd
import numpy as np
from pylab import mpl,plt
plt.style.use('seaborn')
mpl.rcParams['font.family']='serif'
pd.set_option('display.width', None) # 设置字符显示宽度
pd.set_option('display.max_rows', 50) # 设置显示最大行
filename='tr_eikon_eod_data.csv'
data=pd.read_csv(filename,index_col=0,parse_dates=True)
#print(data)
symbols=["AAPL.O", "MSFT.O" ,"AMZN.O" ,"GDX" , "GLD"]
noa=len(symbols)
data=pd.DataFrame(data[symbols]).dropna()
#(data/data.ix[0]*100).plot()#价格变动
rets=np.log(data/data.shift(1))#日对数收益率
# print(rets.cov()*252)
# rets["AAPL.O"].plot.hist(bins=70)
# plt.show()
# 蒙特卡洛计算出可行性边界————————————————————方法一
ex_return_ratio_list=[]
ex_var_list=[]
ex_sharpe_list=[]
N=2500
for j in range(N):
weights = np.random.random(noa)
weights /= np.sum(weights)
ex_return_ratio = np.sum(rets.mean() * weights) * 252
ex_var = np.dot(weights.T, np.dot(rets.cov() * 252, weights))#dot表示向量点积或是矩阵乘法 T表示转置
ex_return_ratio_list.append(ex_return_ratio)
ex_var_list.append(ex_var)
ex_sharpe_list.append(ex_return_ratio/np.sqrt(ex_var))
ex_return_ratio_list=np.array(ex_return_ratio_list)
ex_var_list=np.array(ex_var_list)
ex_std_list=np.sqrt(ex_var_list)
# plt.scatter(x=ex_std_list,y=ex_return_ratio_list,c=ex_sharpe_list,cmap='coolwarm')
# plt.show()
# 非线性约束规划————————————————————方法二
import scipy.optimize as sco
def get_ex_return_ratio(weights):
return np.sum(rets.mean() * weights) * 252
def get_ex_std(weights):
return np.sqrt(np.dot(weights.T, np.dot(rets.cov() * 252, weights)))
def min_func_sharpe(weights):#(带无风险投资)
# e_f = 0.05
# std_f = 0
return -(get_ex_return_ratio(weights)-e_f)/(get_ex_std(weights)-std_f)
e_f = 0.05
std_f = 0
# 非线性约束规划计算最大夏普
cons=({'type':'eq','fun':lambda x: np.sum(x)-1})#等式约束
bnds=tuple((0,1) for x in range(noa))#参数范围
eweights=np.array(noa*[1./noa])# 等权重向量
opts=sco.minimize(min_func_sharpe,eweights,method='SLSQP',bounds=bnds,constraints=cons)#最优化函数
print(opts)# x表示最优情况下权重weights的array
print(get_ex_return_ratio(opts['x']),get_ex_std(opts['x']))
plt.plot(get_ex_std(opts['x']),get_ex_return_ratio(opts['x']),'ys',std_f,e_f,'bs')
t=np.linspace(-0.05,0.3,50)
plt.plot(t,-1*t*(min_func_sharpe(opts['x']))+e_f)
#有效边界——给定收益率时最小化方差的投资组合——最优投资组合
trets=np.linspace(0,0.25,80)
tvols=[]
weights = np.random.random(noa)
weights /= np.sum(weights)
for tret in trets:
cons=({'type':'eq','fun':lambda x: get_ex_return_ratio(x)-tret},{'type':'eq','fun':lambda x: np.sum(x)-1})#等式约束
bnds=tuple((0,1) for x in range(noa))
eweights = np.array(noa * [1. / noa])
res = sco.minimize(get_ex_std, eweights, method='SLSQP', bounds=bnds, constraints=cons)
tvols.append(res['fun'])
tvols=np.array(tvols)
plt.scatter(x=ex_std_list,y=ex_return_ratio_list,c=ex_sharpe_list,cmap='coolwarm')
plt.plot(tvols,trets)
plt.show()
最优组合以及可行性边界
标签:return,pyhon,非线性,list,weights,ex,np,ratio,最优 来源: https://blog.csdn.net/xic18/article/details/115570465