未定义 Scipy 最小名称'init_weigths'



有人知道我为什么会在最小化函数上出现这个未定义的错误吗?变量init_weights在调用最小化函数之前定义并填充的float数组中。然而,它似乎读不出来

def port_ret(weights):
return ret.dot(weights.T).mean() * 252
# calculate annualized portfolio volatility (based on weights)
def port_vol(weights):
return ret.dot(weights.T).std() * np.sqrt(252)

# define function to be minimized (sco only supports minimize, not maximize)
# -> maximize sharpe ratio == minimize sharpe ratio * (-1)
def min_func_sharpe(weights):
return ((rf - port_ret(weights)) / port_vol(weights)) * -1  # sharpe ratio *

num_stocks = float(len(stocks.columns))
num_stock = len(stocks.columns)
init_weights = []
ueight = float(1/num_stocks)
for i in range(num_stock):
init_weights.append(ueight)

# bounds: all weights shall be between 0 and 1 -> can be changed
bnds = tuple((0, 1) for i in range(num_stock))
# constraint: weights must sum up to 1 -> sum of weights - 1 = 0
cons = ({"type": "eq", "fun": lambda x: np.sum(x) - 1})
# run optimization based on function to be minimized, starting with equal weights and based on respective bounds and constraints
opts = minimize(fun=min_func_sharpe, x0=init_weigths, method="SLSQP",
bounds=bnds, constraints=cons)

eweights = np.array(init_weights)

在传递之前,我必须将普通数组转换为numpy数组,以最小化

最新更新