我正试图在本文(https://quantdare.com/risk-parity-in-python/)之后创建一个用于均等风险贡献投资组合的工具,但由于scipy优化器无法正常工作,它在最后一步(def risk_parity_weights)失败了。它一直给我初始权重作为优化权重,而且我知道它们不是优化权重,因为即使Excel Solver也能够优化此权重。所有其他功能均已检查并且正确。不确定我在做什么错-请帮忙!
adSetsTable.rows().invalidate().draw();
#Calculate portfolio st.dev
portfolio_stdev = np.sqrt(weights*covariances*weights.T)[0,0]
#Calculate Marginal Risk Contribution of each asset
MRC = covariances*weights.T/portfolio_stdev
#Calculate Risk Contribution of each asset
RC = np.multiply(MRC,weights.T)
return RC
def risk_budget_objective_error(weights,*args):
#Covariance table occupies the first position in args variable
covariances = args[0]
#State risk budgets
assets_risk_budget = args[1]
#Convert weights array to numpy matrix
weights = np.matrix(weights)
#Calculate portfolio st_dev
portfolio_stdev = calculate_portfolio_stdev(ca_begweights,ca_cov)
#Calculate risk contributions
assets_risk_contribution = calculate_risk_contribution(ca_begweights,ca_cov)
#Calculate desired risk contribution of each asset
assets_risk_target = np.asmatrix(np.multiply(portfolio_stdev,assets_risk_budget))
#Calculate error between desired contribution and calculated distribution of each asset
error = sum(np.square(assets_risk_contribution - assets_risk_target.T))[0,0]
return error
def risk_parity_weights(covariances,assets_risk_budget, initial_weights):
#Constraints to optimization
#sum equals 100%
cons = ({'type':'eq','fun':lambda x: np.sum(x) - 1.0},
{'type':'ineq','fun':lambda x: x})
#Optimization in scipy
optimize_result = minimize(risk_budget_objective_error,
x0 = initial_weights,
args = (covariances, assets_risk_budget),
method = 'SLSQP',
constraints = cons,
tol = Tolerance,
options = {'disp':True})
#Get optimized weights
weights = optimize_result.x
return weights
给了我
risk_parity_weights(ca_cov,risk_budget_all, ca_begweights)
请参见下面的变量数据
Optimization terminated successfully. (Exit mode 0)
Current function value: 9.54000328523598e-07
Iterations: 1
Function evaluations: 5
Gradient evaluations: 1