我有以下两种资产 A 和 B 的权重和股票收益矩阵:
weights = np.array([[.6, .4], [.5, .5], [.4, .6]]) # all elements w: 0 < w < 1
returns = np.array([[1.25, 2.5], [0.64, 0.5], [1.5, 1.6]]).T
我想找到一个新的权重矩阵来优化两个矩阵乘积的对角线乘积,如下所示:
def objective_function(weights, returns):
mat = np.product(np.diag(weights @ returns)) - 1
return mat
>>> 0.5561
我正在努力寻找一个有效的优化包或算法,因为它们似乎都只生成一个优化函数的一维向量。
我尝试压平权重矩阵并在函数中重塑它作为解决方法,如下所示:
import numpy as np
from scipy.optimize import minimize
# Reshape function to take 3x2 matrix
def funct(weights_flat):
weights = weights_flat.reshape((3, 2))
mat = -(np.product(np.diag(weights @ returns)) - 1)
return mat
# Constraints: sum of each column should be 1
constraints = ({'type': 'eq', 'fun': lambda w: np.sum(w, axis=0) - 1})
# Initial guess (1D array)
initial_guess_flat = np.ones(6)
# Perform the optimization using scipy.optimize
result = minimize(funct, initial_guess_flat, method='SLSQP', constraints=constraints)
# Get the optimized weights
optimized_weights = result.x.reshape((3, 2))
print("Optimized Weights:")
print(optimized_weights)
上面的结果只是一个 NaN 值矩阵。
>>> Optimized Weights:
[[nan nan]
[nan nan]
[nan nan]]
任何人都可以建议如何重新配置优化函数以按预期工作或建议适合我的问题的替代包/算法吗?
weights
矩阵的条目从增长到 +/- 无穷大,这会抵消并给出总和为 1 的列,同时将函数减少到负无穷大(当您最小化该函数的值时,不是它的大小!)。我的猜测是你真正想要的是成本函数中的标准mat = np.abs(np.product(np.diag(weights @ returns)) - 1)
,或类似的东西。