股票组合投资的风险平价策略

发布时间 2023-06-09 14:16:01作者: 方木--数据分析与挖掘

导入每只股票的净值数据:

import pandas as pd
import numpy as np
from scipy.optimize import minimize
StockPrices = pd.DataFrame()
StockPrices = pd.read_excel('zuhe.xlsx',index_col=[0])
StockPrices.index.name = '日期'
StockPrices.head()

提取每只股票的名称:

codes=StockPrices.columns.tolist()
codes

计算股票的每日收益率:

StockReturns = StockPrices.pct_change().dropna()
StockReturns

计算他们的协方差:

R_cov = StockReturns.cov()
cov= np.array(R_cov)

构建风险平价组合:

def risk_budget_objective(weights,cov):
    weights = np.array(weights) 
    sigma = np.sqrt(np.dot(weights, np.dot(cov, weights))) 
    MRC = np.dot(cov,weights)/sigma  
    TRC = weights * MRC
    delta_TRC = [sum((i - TRC)**2) for i in TRC]
    return sum(delta_TRC)

def total_weight_constraint(x):
    return np.sum(x)-1.0
     
x0 = np.ones(cov.shape[0]) / cov.shape[0]
bnds = tuple((0,None) for x in x0)
cons = ({'type': 'eq', 'fun': total_weight_constraint})
options={'disp':False, 'maxiter':1000, 'ftol':1e-20} 

solution = minimize(risk_budget_objective, x0,args=(cov), bounds=bnds, constraints=cons, method='SLSQP', options=options)
final_weights = solution.x 
for i in range(len(final_weights)):
    print(f'{final_weights[i]:.1%}投资于{R_cov.columns[i]}')