robertmartin8 / PyPortfolioOpt

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

Min/Man number assets nor working well #399

Closed amos-peter closed 1 year ago

amos-peter commented 2 years ago

Please guide me on how to get the right min/max value for the number of assets. I am working to maximize a set of score objectives with a min/max number of assets constraints.

# Construct efficient frontier
from pypfopt.risk_models import CovarianceShrinkage
import math

# Construct efficient frontier
mu = expected_returns.mean_historical_return(prices)
S = risk_models.sample_cov(prices)

#['CVXOPT', 'ECOS', 'ECOS_BB', 'GLPK', 'GLPK_MI', 'OSQP', 'SCIPY', 'SCS']
ef = EfficientFrontier(mu, S,weight_bounds=(0, 1),solver='ECOS_BB')

#min num assets
b = cp.Variable(len(ef.tickers), boolean=True)
ef.add_constraint(lambda x: x <= booleans)
ef.add_constraint(lambda x: cp.sum(booleans) == 6)

#min 0
ef.add_constraint(lambda x: x >= min_zero)
score_rank = mu.rank(pct = True)

#Max 0.4 
for i in range(len(prices.columns)):
    ef.add_constraint(lambda w: w[i] <= 0.4)

#wgt = ef.min_volatility()
wgt = ef.convex_objective(comp_score_obj, score=score_rank)
w_list = list(wgt.values())
clean_wgt = dict(ef.clean_weights())

#clean manually 
round_wgt = [round(num,3) for num in w_list]
round_wgt
phschiele commented 2 years ago

@amos-peter Can you specify what you mean by "right" min/max value for the number of assets?

amos-peter commented 2 years ago

@phschiele It is working no problem using default objectives such min_vol or max_sharpe. However it is not working when i try using convex objective such as maximize a set of scores.

amos-peter commented 2 years ago

@phschiele i added this code:

booleans = cp.Variable(len(ef.tickers), boolean=True)
ef.add_constraint(lambda x: x <= booleans)
ef.add_constraint(lambda x: cp.sum(booleans) >= 3)

However it is not working if using convex objectives.

phschiele commented 2 years ago

@amos-peter Happy to take a look if you can provide a full MWE