基于此材料(see 5/6),我实现了以下功能:
import pandas as pd
def optm_cvar(return_df, beta):
import cvxpy
from cvxpy import Variable
from cvxpy import Minimize
from cvxpy import Problem
assert isinstance(return_df, pd.DataFrame)
assert isinstance(beta, float)
period, stock_num = return_df.shape
weight = Variable(stock_num)
value_at_risk = Variable()
u = Variable(period)
obj = Minimize(value_at_risk + (1 / ((1 - beta) * period)) * cvxpy.sum(u))
constraint_l = list()
constraint_l.append(weight >= 0)
constraint_l.append(u >= 0)
constraint_l.append(cvxpy.sum(weight) == 1)
for i in range(period):
constraint_l.append(u[i] + value_at_risk + cvxpy.sum(cvxpy.multiply(weight, return_df.iloc[i, :])) >= 0)
problem = Problem(obj, constraint_l)
#result = problem.solve()
result = problem.solve(cvxpy.CVXOPT)
#result = problem.solve(cvxpy.SCS)
print(problem.status)
print(result)
return weight.value
此功能运行良好 但是我认为这个约束代码
for i in range(period):
constraint_l.append(u[i] + value_at_risk + cvxpy.sum(cvxpy.multiply(weight, return_df.iloc[i, :])) >= 0)
效率不高,与cvxpy方式不匹配。 如何改善我的代码?