Skip to content

Constraint on number of assets? #243

Closed

Description

@sword134

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

What data are you using?
SP500 data universe.

Activity

  1. added
    question
    on Jan 7, 2021
  2. changed the title [-]How to [insert question]?[/-] [+]Constraint on number of assets?[/+] on Jan 7, 2021
  3. robertmartin8 commented on Jan 7, 2021

    @robertmartin8
    Collaborator

    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

  4. phschiele commented on Jan 7, 2021

    @phschiele
    Contributor

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

    import cvxpy as cp
    from tests.utilities_for_tests import setup_efficient_frontier
    ef = setup_efficient_frontier(solver=cp.CPLEX)
    booleans = cp.Variable(len(ef.tickers), boolean=True)
    ef.add_constraint(lambda x: x <= booleans)
    ef.add_constraint(lambda x: cp.sum(booleans) <= 10)
    ef.min_volatility()
    ef.weights
    array([0.        , 0.01503686, 0.09891734, 0.12603716, 0.        ,
           0.        , 0.        , 0.17711377, 0.        , 0.11697861,
           0.17732243, 0.        , 0.        , 0.18942864, 0.        ,
           0.00072097, 0.        , 0.08792907, 0.        , 0.01051514])

    Some remarks:

    • These types of problems are generally much harder to solve
    • You should consider Robert's comment about optimization vs. asset selection.
  5. sword134 commented on Jan 7, 2021

    @sword134
    Author

    @phschiele that throws me the following error:

    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.
    

    I have no idea where to add the verbose=True.

  6. phschiele commented on Jan 7, 2021

    @phschiele
    Contributor

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

  7. sword134 commented on Jan 7, 2021

    @sword134
    Author

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

  8. phschiele commented on Jan 7, 2021

    @phschiele
    Contributor

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

  9. sword134 commented on Jan 7, 2021

    @sword134
    Author

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

  10. robertmartin8 commented on Jan 15, 2021

    @robertmartin8
    Collaborator

    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:

    for i in range(1, 20, 2):
        ef = EfficientFrontier(mu, sigma)
        ef.add_objective(objective_functions.L2_reg, gamma=0.05 * i)
        ef.max_sharpe()
        print(f"gamma = {0.05*i}, num nonzero = {sum(ef.weights > 0.001)}")

    Then, you can pick the value of gamma that 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 :/

  11. sword134 commented on Jan 15, 2021

    @sword134
    Author

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

  12. robertmartin8 commented on Jan 15, 2021

    @robertmartin8
    Collaborator

    Hi @sword134,

    gamma does 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:

    gamma = 0.05, num_nonzero = 500
    gamma = 0.1, num_nonzero = 300
    gamma = 0.15, num_nonzero = 200
    ...
    

    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

  13. sword134 commented on Jan 15, 2021

    @sword134
    Author

    @robertmartin8 it seems like you have a table over the approximate gamma to assets list. How big would gamma be for say 10 assets?

  14. 5 remaining items

  15. robertmartin8 commented on Jan 18, 2021

    @robertmartin8
    Collaborator

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

  16. phschiele commented on Jan 22, 2021

    @phschiele
    Contributor

    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.

  17. kayuksel commented on Jan 23, 2021

    @kayuksel

    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?
    optimizer_1
    optimizer

  18. sword134 commented on Jan 23, 2021

    @sword134
    Author

    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?
    optimizer_1
    optimizer

    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?

  19. kayuksel commented on Jan 24, 2021

    @kayuksel

    @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:
    ls_2

  20. sword134 commented on Jan 24, 2021

    @sword134
    Author

    @kayuksel then why post on a library that focuses on 1950's methods?

  21. phschiele commented on Feb 16, 2021

    @phschiele
    Contributor

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

  22. linda390 commented on Feb 18, 2021

    @linda390

    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.

  23. robertmartin8 commented on Feb 19, 2021

    @robertmartin8
    Collaborator

    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?

  24. linked a pull request that will close this issuev1.4.1 #298on Feb 19, 2021
  25. linked a pull request that will close this issuev1.4.1 #299on Feb 19, 2021
  26. ankushkundaliya commented on Jun 4, 2021

    @ankushkundaliya

    Hi, Have anyone tried SCIP solver for cardinality constraint?
    @phschiele @robertmartin8 @sword134

  27. gowombats commented on Dec 7, 2021

    @gowombats

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

    import cvxpy as cp
    from tests.utilities_for_tests import setup_efficient_frontier
    ef = setup_efficient_frontier(solver=cp.CPLEX)
    booleans = cp.Variable(len(ef.tickers), boolean=True)
    ef.add_constraint(lambda x: x <= booleans)
    ef.add_constraint(lambda x: cp.sum(booleans) <= 10)
    ef.min_volatility()
    ef.weights
    array([0.        , 0.01503686, 0.09891734, 0.12603716, 0.        ,
           0.        , 0.        , 0.17711377, 0.        , 0.11697861,
           0.17732243, 0.        , 0.        , 0.18942864, 0.        ,
           0.00072097, 0.        , 0.08792907, 0.        , 0.01051514])

    Some remarks:

    • These types of problems are generally much harder to solve
    • You should consider Robert's comment about optimization vs. asset selection.

    @phschiele Is there a non-community version available for purchase? I can't find anything here: https://www.cvxpy.org/install/

  28. phschiele commented on Dec 11, 2021

    @phschiele
    Contributor

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

    import cvxpy as cp
    from tests.utilities_for_tests import setup_efficient_frontier
    ef = setup_efficient_frontier(solver=cp.CPLEX)
    booleans = cp.Variable(len(ef.tickers), boolean=True)
    ef.add_constraint(lambda x: x <= booleans)
    ef.add_constraint(lambda x: cp.sum(booleans) <= 10)
    ef.min_volatility()
    ef.weights
    array([0.        , 0.01503686, 0.09891734, 0.12603716, 0.        ,
           0.        , 0.        , 0.17711377, 0.        , 0.11697861,
           0.17732243, 0.        , 0.        , 0.18942864, 0.        ,
           0.00072097, 0.        , 0.08792907, 0.        , 0.01051514])

    Some remarks:

    • These types of problems are generally much harder to solve
    • You should consider Robert's comment about optimization vs. asset selection.

    @phschiele Is there a non-community version available for purchase? I can't find anything here: https://www.cvxpy.org/install/

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    question

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions