import pandas as pd
import numpy as np
from scipy.optimize import shgo
def my_function(w, *args):
P = X @ w
print(np.mean(P))
print(w)
return -np.mean(P)
file_path = "stock returns data of e.g. 10 companies.xlsx"
df = pd.ExcelFile(file_path).parse('Sheet1', header=6, index_col=0)
X = df.to_numpy()
cons = {'type': 'eq', 'fun': lambda w: 1 - np.sum(w)}
w0 = []
for i in range(df.shape[1]):
w0.append(1 / df.shape[1])
b = (0, 1)
bnds = []
for i in range(df.shape[1]):
bnds.append(b)
optimal = shgo(my_function, bounds=bnds, args=X, constraints=cons)
为了查看发生了什么,该脚本会在每次迭代中打印出值和权重。它尝试权重[0,0,0,0,0,0,0,0,0,0,0]和[1,1, 1,1,1,1,1,1,1,1]。为什么这样做呢?似乎在函数的所有边界都测试了值,即使它们不遵守约束。随着投资组合中资产数量的增加,这似乎使迭代次数几乎无限。