我使用xlwings在Excel中实现Python代码。我将下面的代码放在Spyder中,并使用xlwings将其导入Excel,以便对金融资产的7资产组合执行scipy优化
@xw.func
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]
weights = np.matrix(weights)
#Calculate portfolio st_dev
portfolio_stdev = calculate_portfolio_risk(weights,covariances)
#Calculate risk contributions
assets_risk_contribution = calculate_risk_contribution(weights,covariances)
#Calculate desired risk contribution of each asset
assets_risk_target = np.multiply(portfolio_stdev,assets_risk_budget).astype(float)
#Calculate error between desired contribution and calculated distribution of each asset
squared_error = np.square(assets_risk_contribution-assets_risk_target.T)
sse = sum(squared_error)
return sse
@xw.func
def erc_weights(covariances,assets_risk_budget, num_assets):
#Constraints to optimization
cons = ({'type':'eq','fun':lambda x: np.sum(x) - 1.5},
{'type':'ineq','fun':lambda x: x})
bounds = ((0,.50),(0,None),(0,None),(0,None),(0,None),(0,.50),(0,None),(0,.10),(0,.25))
init_weights = [.5]*num_assets
#Optimization in scipy
optimize_result = minimize(risk_budget_objective_error,
x0 = init_weights,
method = 'SLSQP',
args = (covariances, assets_risk_budget),
constraints = cons,
options = {'disp':True,'ftol':1e-50}
)
#Get optimized weights
weights = optimize_result.x
return weights
我的问题是erc\ U权重函数。我试着让投资组合中的资产数量成为函数中的一个参数
反过来,我把numèassets作为一个参数,它是投资组合中的资产数量(下面显示的是经过编辑的代码),但是每次我把它作为一个参数添加时,这个函数就会崩溃并产生一个错误。要清楚的是,下面代码中唯一的更改是将num\u assets包含为参数,并将init\u weights的公式更改为[.5]*num\u assets
当我试图使其他参数内生时也会发生同样的情况。例:总重量上限,界限等,所以任何解决这个问题的方法在这些领域也一定有用。谢谢
@xw.func
def erc_weights(covariances,assets_risk_budget, num_assets):
#Constraints to optimization
cons = ({'type':'eq','fun':lambda x: np.sum(x) - 1.5},
{'type':'ineq','fun':lambda x: x})
bounds = ((0,.50),(0,None),(0,None),(0,None),(0,None),(0,.50),(0,None),(0,.10),(0,.25))
init_weights = [.5]*num_assets
#Optimization in scipy
optimize_result = minimize(risk_budget_objective_error,
x0 = init_weights,
method = 'SLSQP',
args = (covariances, assets_risk_budget),
constraints = cons,
options = {'disp':True,'ftol':1e-50}
)
#Get optimized weights
weights = optimize_result.x
return weights
目前没有回答
相关问题 更多 >
编程相关推荐