PyPortfolioOpt icon indicating copy to clipboard operation
PyPortfolioOpt copied to clipboard

Min/Man number assets nor working well

Open amos-peter opened this issue 3 years ago • 4 comments

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

amos-peter avatar Dec 05 '21 12:12 amos-peter

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

phschiele avatar Jan 26 '22 21:01 phschiele

@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 avatar Feb 05 '22 16:02 amos-peter

@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.

amos-peter avatar Feb 05 '22 16:02 amos-peter

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

phschiele avatar Feb 06 '22 15:02 phschiele