首页 > 解决方案 > 未定义 Scipy 最小化名称“init_weigths”

问题描述

任何人都知道为什么我在最小化函数上得到这个未定义的错误?在调用最小化函数之前定义和填充的浮点数组中的变量 init_weights。但是它似乎没有阅读它

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)



标签: pythonpandasscipy

解决方案


eweights = np.array(init_weights)

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


推荐阅读