You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
What are you trying to do?
Setting a max number of assets to allocate weights to. For example observe a universe of 500 stocks, I only want the weights for max 10 stocks and the sum should ofcourse be 100%.
Unfortunately, that's not possible because the constraint is not convex. Please see #45 and #101 for suggestions. As I have mentioned in other threads, my perspective is that portfolio optimisation != asset selection: you should choose which assets you are interested in before using PyPortfolioOpt to optimise weights.
@sword134: as mentioned by @robertmartin8, the cardinality constraint you ask for is not convex.
However, CXPY also supports MILP problems, if you have the required solver installed.
For small problems with less than 1000 variables and constraints, you can use the community version of CPLEX: pip install cplex
Consider this simple example for minimizing the portfolio volatility given a maximum of 10 securities to invest in, with weights between 0 and 1 for each asset. Slight modifications are required if you want to choose different bounds.
Traceback (most recent call last):
File "d:\Finansiering. Modern Portfolio Theory Projekt\MPT. Finansierings projekt.py", line 41, in <module>
weights = ef.min_volatility()
File "D:\Anaconda\envs\Finansiering\lib\site-packages\pypfopt\efficient_frontier.py", line 166, in min_volatility
return self._solve_cvxpy_opt_problem()
File "D:\Anaconda\envs\Finansiering\lib\site-packages\pypfopt\base_optimizer.py", line 222, in _solve_cvxpy_opt_problem
opt.solve(solver=self._solver, verbose=self._verbose)
File "D:\Anaconda\envs\Finansiering\lib\site-packages\cvxpy\problems\problem.py", line 396, in solve
return solve_func(self, *args, **kwargs)
File "D:\Anaconda\envs\Finansiering\lib\site-packages\cvxpy\problems\problem.py", line 754, in _solve
self.unpack_results(solution, solving_chain, inverse_data)
File "D:\Anaconda\envs\Finansiering\lib\site-packages\cvxpy\problems\problem.py", line 1068, in unpack_results
"Try another solver, or solve with verbose=True for more "
cvxpy.error.SolverError: Solver 'CPLEX' failed. Try another solver, or solve with verbose=True for more information.
@sword134 Did you try to reproduce my example or did you add the constraints to your code? As mentioned above, the community version of CPLEX only supports 1000 variables and constraints. Note that this includes the boolean variables as well. It also does not only count the variables defined in CVXPY, but the variables in the canonical form produced by CVXPY. So the S&P 500 optimisation problem might already exceed these limits.
@phschiele so you say 1000 variables, what does this entail? How big can the stock universe be then? I added the code to my own data etc. to see if it worked. I didn't try it out of the box as you posted, because i don't have the "test" folder from which it is pulling the "setup_efficient_frontier" function, so I just added the solver parameter manually.
@sword134 This can easily be verified for your particular problem by excluding n assets from the universe and let n go to 0.
Check out the CVXPY Docs for further information on the problem size.
@phschiele ok I brought down the number assets so it works. However I cant use max_shape()
Traceback (most recent call last):
File "d:\Finansiering. Modern Portfolio Theory Projekt\MPT. Finansierings projekt.py", line 41, in <module>
weights = ef.max_sharpe(risk_free_rate=riskfreerate)
File "D:\Anaconda\envs\Finansiering\lib\site-packages\pypfopt\efficient_frontier.py", line 226, in max_sharpe
self._solve_cvxpy_opt_problem()
File "D:\Anaconda\envs\Finansiering\lib\site-packages\pypfopt\base_optimizer.py", line 226, in _solve_cvxpy_opt_problem
raise exceptions.OptimizationError from e
pypfopt.exceptions.OptimizationError: Please check your objectives/constraints or use a different solver.
I want the optimal tangency portfolio (not min variance) so what solver would I use for sharpe ratio?
Max-Sharpe does not play well with complex constraints, because to find the max-sharpe portfolio, PyPortfolioOpt has to make a change of variables (the maths is a little tricky).
A while ago I was contracted to build max-sharpe portfolios and I was in a similar position to you (had a constraint on the number of assets).
My solution was to vary the L2 reg parameter, which produces different amounts of nonzero portfolios. This short script constructs several max sharpe portfolios and prints the number of assets with more than 0.1% weight:
@robertmartin8 when you say that the value of gamma is the desired number of assets, does that mean that the variable i is what determines the number of assets of is it the value of gamma 0.05 that means 5% assets? Personally, I interpret it as gamma being the min % weight must needed to be part of the portfolio (which means you have to adjust the gamma and see for yourself what the number of assets becomes).
I hope you can clear up my confusion and explain it.
Let's say you wanted 250 nonzero assets, this means you should choose gamma between 0.1 and 0.15. You could do another for loop with a more granular range of gammas if you wanted.
This approach does not work well if you absolutely must have a fixed number of assets. It is more of a heuristic for getting approximately the right number of nonzero-weight assets in your portfolio.
Alternatively, trace out the efficient frontier using multiple efficient_risk() / efficient_risk() calls (+ cardinality constraint) and select the sharpe ratio maximizing portfolio from the resulting portfolios.
I do not argue against the L2 regularization method, but it does more than just changing the cardinality, which is something you might or might not want.
My optimizer quickly optimizes actively rebalanced portfolios of thousand assets on my laptop. You can't unfortunately do that with available optimizers without getting stuck into deceptive local optima(s). (In my method, the asset pre-selection is not necessary but you can still do that or give return estimates to introduce investor bias.) Here is an example QuantConnect back-test since 2009 for such a rebalanced portfolio that is found by my method without a pre-selection. I actually want to integrate a reliable pre-selection method so that I can optimize an universe of ten-thousand assets. What would be the best for that? Hierarchical Risk Parity?
My optimizer quickly optimizes actively rebalanced portfolios of thousand assets on my laptop. You can't unfortunately do that with available optimizers without getting stuck into deceptive local optima(s). (In my method, the asset pre-selection is not necessary but you can still do that or give return estimates to introduce investor bias.) Here is an example QuantConnect back-test since 2009 for such a rebalanced portfolio that is found by my method without a pre-selection. I actually want to integrate a reliable pre-selection method so that I can optimize an universe of ten-thousand assets. What would be the best for that? Hierarchical Risk Parity?
I cant answer your question on pre-selection. However I want to ask you this, is this portfolio made with Markowitz Portfolio optimization or something else?
@robertmartin8 I think the original question has been answered. Do you think the example should be preserved somewhere (I think it has come up multiple times before).
@kayuksel has raised another question about pre-selection and HRP. If that question is still relevant, perhaps a new issue should be opened to keep things organized. My initial view would be that perhaps (methods of) HRP could indeed also be used for pre-selection, e.g. by only choosing only one asset from a very similar cluster, although I have never tried that empirically.
Hi. I just wanted to add that there is a very real use-case for this. Using gamma to set the number of assets is a painful/inefficient way of doing it.
For example- I'm interested in a married put option strategy for my portfolio. Because options contracts have a fixed quantity of 100 underlying securities, I would like to allocate the securities in my portfolio based on multiples of 100s.
It would be great if we could please include the asset number constraint as an enhancement.
Hi @linda390, I am absolutely aware that the constraint on the number of assets is an important feature. Unfortuantely, I am constrained (no pun intended) by the fact that it is a difficult problem mathematically.
It's possible that in a future version, some variant of @phschiele's solution may be built in (e.g ef.add_num_assets_constraint), but a lot of thought needs to go into it to make sure it plays nice with other constraints/bounds.
@phschiele I agree this should be preserved somewhere. Perhaps an FAQ page on the documentation site?
@sword134: as mentioned by @robertmartin8, the cardinality constraint you ask for is not convex. However, CXPY also supports MILP problems, if you have the required solver installed. For small problems with less than 1000 variables and constraints, you can use the community version of CPLEX: pip install cplex Consider this simple example for minimizing the portfolio volatility given a maximum of 10 securities to invest in, with weights between 0 and 1 for each asset. Slight modifications are required if you want to choose different bounds.
@sword134: as mentioned by @robertmartin8, the cardinality constraint you ask for is not convex. However, CXPY also supports MILP problems, if you have the required solver installed. For small problems with less than 1000 variables and constraints, you can use the community version of CPLEX: pip install cplex Consider this simple example for minimizing the portfolio volatility given a maximum of 10 securities to invest in, with weights between 0 and 1 for each asset. Slight modifications are required if you want to choose different bounds.
@gowombats CVXPY is the modeling language, which is completely open-source. It supports multiple solvers, one of them is the above-mentioned CPLEX solver. There are also other solvers which would work. What's the issue that you are facing? Ideally, open a new issue for that, as it seems not directly related to this thread.
Activity
[-]How to [insert question]?[/-][+]Constraint on number of assets?[/+]robertmartin8 commentedon Jan 7, 2021
Hi @sword134,
Unfortunately, that's not possible because the constraint is not convex. Please see #45 and #101 for suggestions. As I have mentioned in other threads, my perspective is that portfolio optimisation != asset selection: you should choose which assets you are interested in before using PyPortfolioOpt to optimise weights.
Best,
Robert
phschiele commentedon Jan 7, 2021
@sword134: as mentioned by @robertmartin8, the cardinality constraint you ask for is not convex.
However, CXPY also supports MILP problems, if you have the required solver installed.
For small problems with less than 1000 variables and constraints, you can use the community version of CPLEX:
pip install cplexConsider this simple example for minimizing the portfolio volatility given a maximum of 10 securities to invest in, with weights between 0 and 1 for each asset. Slight modifications are required if you want to choose different bounds.
Some remarks:
sword134 commentedon Jan 7, 2021
@phschiele that throws me the following error:
I have no idea where to add the verbose=True.
phschiele commentedon Jan 7, 2021
@sword134 Did you try to reproduce my example or did you add the constraints to your code? As mentioned above, the community version of CPLEX only supports 1000 variables and constraints. Note that this includes the boolean variables as well. It also does not only count the variables defined in CVXPY, but the variables in the canonical form produced by CVXPY. So the S&P 500 optimisation problem might already exceed these limits.
sword134 commentedon Jan 7, 2021
@phschiele so you say 1000 variables, what does this entail? How big can the stock universe be then? I added the code to my own data etc. to see if it worked. I didn't try it out of the box as you posted, because i don't have the "test" folder from which it is pulling the "setup_efficient_frontier" function, so I just added the solver parameter manually.
phschiele commentedon Jan 7, 2021
@sword134 This can easily be verified for your particular problem by excluding
nassets from the universe and letngo to 0.Check out the CVXPY Docs for further information on the problem size.
sword134 commentedon Jan 7, 2021
@phschiele ok I brought down the number assets so it works. However I cant use max_shape()
I want the optimal tangency portfolio (not min variance) so what solver would I use for sharpe ratio?
robertmartin8 commentedon Jan 15, 2021
Max-Sharpe does not play well with complex constraints, because to find the max-sharpe portfolio, PyPortfolioOpt has to make a change of variables (the maths is a little tricky).
A while ago I was contracted to build max-sharpe portfolios and I was in a similar position to you (had a constraint on the number of assets).
My solution was to vary the L2 reg parameter, which produces different amounts of nonzero portfolios. This short script constructs several max sharpe portfolios and prints the number of assets with more than 0.1% weight:
Then, you can pick the value of
gammathat corresponds to your desired number of assets.I know it's not ideal, but we are somewhat constrained (no pun intended) by the mathematics here :/
sword134 commentedon Jan 15, 2021
@robertmartin8 when you say that the value of gamma is the desired number of assets, does that mean that the variable i is what determines the number of assets of is it the value of gamma 0.05 that means 5% assets? Personally, I interpret it as gamma being the min % weight must needed to be part of the portfolio (which means you have to adjust the gamma and see for yourself what the number of assets becomes).
I hope you can clear up my confusion and explain it.
robertmartin8 commentedon Jan 15, 2021
Hi @sword134,
gammadoes not directly control weights. It is an indirect way of penalising portfolios with many nonzero weights.Try and run the script I provided, you'll get some output like:
Let's say you wanted 250 nonzero assets, this means you should choose gamma between 0.1 and 0.15. You could do another for loop with a more granular range of gammas if you wanted.
This approach does not work well if you absolutely must have a fixed number of assets. It is more of a heuristic for getting approximately the right number of nonzero-weight assets in your portfolio.
Best,
Robert
sword134 commentedon Jan 15, 2021
@robertmartin8 it seems like you have a table over the approximate gamma to assets list. How big would gamma be for say 10 assets?
5 remaining items
robertmartin8 commentedon Jan 18, 2021
@sword134 it's on the roadmap, but not currently a priority.
Because portfolio optimisation tends to be used on longer time horizons, "for loop backtests" work pretty well in my opinion.
However, this might be something to ask on the Backtrader forums.
phschiele commentedon Jan 22, 2021
Alternatively, trace out the efficient frontier using multiple
efficient_risk()/efficient_risk()calls (+ cardinality constraint) and select the sharpe ratio maximizing portfolio from the resulting portfolios.I do not argue against the L2 regularization method, but it does more than just changing the cardinality, which is something you might or might not want.
kayuksel commentedon Jan 23, 2021
My optimizer quickly optimizes actively rebalanced portfolios of thousand assets on my laptop. You can't unfortunately do that with available optimizers without getting stuck into deceptive local optima(s). (In my method, the asset pre-selection is not necessary but you can still do that or give return estimates to introduce investor bias.) Here is an example QuantConnect back-test since 2009 for such a rebalanced portfolio that is found by my method without a pre-selection. I actually want to integrate a reliable pre-selection method so that I can optimize an universe of ten-thousand assets. What would be the best for that? Hierarchical Risk Parity?


sword134 commentedon Jan 23, 2021
I cant answer your question on pre-selection. However I want to ask you this, is this portfolio made with Markowitz Portfolio optimization or something else?
kayuksel commentedon Jan 24, 2021
@sword134 I don't use methods from 1950. I develop ones for 2050.

I have done the stock pre-selection. Here is a long-short 3000 stocks:
sword134 commentedon Jan 24, 2021
@kayuksel then why post on a library that focuses on 1950's methods?
phschiele commentedon Feb 16, 2021
@robertmartin8 I think the original question has been answered. Do you think the example should be preserved somewhere (I think it has come up multiple times before).
@kayuksel has raised another question about pre-selection and HRP. If that question is still relevant, perhaps a new issue should be opened to keep things organized. My initial view would be that perhaps (methods of) HRP could indeed also be used for pre-selection, e.g. by only choosing only one asset from a very similar cluster, although I have never tried that empirically.
linda390 commentedon Feb 18, 2021
Hi. I just wanted to add that there is a very real use-case for this. Using gamma to set the number of assets is a painful/inefficient way of doing it.
For example- I'm interested in a married put option strategy for my portfolio. Because options contracts have a fixed quantity of 100 underlying securities, I would like to allocate the securities in my portfolio based on multiples of 100s.
It would be great if we could please include the asset number constraint as an enhancement.
Thank you so very much.
robertmartin8 commentedon Feb 19, 2021
Hi @linda390, I am absolutely aware that the constraint on the number of assets is an important feature. Unfortuantely, I am constrained (no pun intended) by the fact that it is a difficult problem mathematically.
It's possible that in a future version, some variant of @phschiele's solution may be built in (e.g
ef.add_num_assets_constraint), but a lot of thought needs to go into it to make sure it plays nice with other constraints/bounds.@phschiele I agree this should be preserved somewhere. Perhaps an FAQ page on the documentation site?
ankushkundaliya commentedon Jun 4, 2021
Hi, Have anyone tried SCIP solver for cardinality constraint?
@phschiele @robertmartin8 @sword134
gowombats commentedon Dec 7, 2021
@phschiele Is there a non-community version available for purchase? I can't find anything here: https://www.cvxpy.org/install/
phschiele commentedon Dec 11, 2021
@gowombats CVXPY is the modeling language, which is completely open-source. It supports multiple solvers, one of them is the above-mentioned CPLEX solver. There are also other solvers which would work. What's the issue that you are facing? Ideally, open a new issue for that, as it seems not directly related to this thread.