python - 未定义 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)
解决方案
eweights = np.array(init_weights)
在传递它以最小化之前,我必须将普通数组转换为 numpy 数组
推荐阅读
- java - janino 编译 Java 代码抛出“找不到类异常”
- c - 为什么 timerfd 定期 Linux 定时器的到期时间比预期的要早一点?
- angular - Ng-bootstrap 模式窗口在订阅的错误部分不起作用
- html - 是否可以使用重复线性渐变属性设置边框图像和背景?
- javascript - 将 .css 文件中的 CSS 添加到材质组件
- wordpress - 在产品画廊阵容中 - 使简短的摘录成为最小长度
- apache-spark - Exception while starting Spark History Server
- google-chrome - 如何在 cypress 中为 chrome 浏览器设置代理
- javascript - 如何在 stackblitz 示例中的每次单击时创建新的 ReplaySubjects?
- .net-core - 从 (3.1.101 x64 ) 升级/迁移 dotnet core Blazor 解决方案