robertmartin8 / PyPortfolioOpt

Financial portfolio optimisation in python, including classical efficient frontier, Black-Litterman, Hierarchical Risk Parity
https://pyportfolioopt.readthedocs.io/
MIT License
4.38k stars 940 forks source link

Maximize objective function in cvxpy #354

Closed amos-peter closed 3 years ago

amos-peter commented 3 years ago

Hi could you please show me how to maximize a set score in pyportfolio "ef.add_objective(objective_functions.L2_reg, gamma=2)". I have done a manual cvxpy. However, i am not sure how to implement using add_objective funcitions.

import cvxpy as cp

mu = expected_returns.capm_return(df)
S = risk_models.CovarianceShrinkage(df).ledoit_wolf()

w = cp.Variable(ef.n_assets) # weights to optimize
problem = cp.Problem(objective=cp.Maximize(w @ comp_score),
                     constraints=[
                         w >= 0,
                         cp.sum(w) == 1,
                         cp.quad_form(w, S) <= 0.20 ** 2,
                     ],
                    )
problem.solve()
weights = w.value
weights
amos-peter commented 3 years ago

Hi, I think I manage to code to maximize a set of score objective. Could you please review if I code it in the right way?

comp_scores = np.array(comp_score).reshape(-1,1)

def comp_score_obj(w, score):
    return w @ -score

ef = EfficientFrontier(mu, S, weight_bounds=(0, 1))
ef.convex_objective(comp_score_obj, score=comp_scores )
weights = ef.clean_weights()
weights
robertmartin8 commented 3 years ago

Looks good!