robertmartin8 / PyPortfolioOpt

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

Error when adding sector constraints to EfficientCVaR Class #517

Open NiciNikolina opened 1 year ago

NiciNikolina commented 1 year ago

Dear Team,

when trying to add sector constraints to the EfficientCVaR (using: ef_cvar.add_sector_constraints(sector_mapper, sector_lower, sector_upper)) it returns the following error:

is_sector = [sector_mapper[t] == sector for t in self.tickers] KeyError: 0.

I checked the constraints and they fulfill the requirements defined in the function add_sector_constraints in base_optimizer.py. Adding the same constraints to the EfficentFrontier class works perfectly fine.

I am using Python 3.9.

Any idea what the problem might be? Thanks in advance!

rwludwig commented 7 months ago

I have a related error. Key error in determining sector membership when adding sector constraints.

I thought that Python's default iteration over dictionaries returned keys, but I'm getting values now, which causes this error.

I never noticed this dict behavior because I never use a bare for loop on a dictionary, but BaseConvexOptimizer.add_sector_constraints does.

Lines 398 and 401 should be amended to use the .keys() function. I did this locally and it fixed my error. https://github.com/robertmartin8/PyPortfolioOpt/blob/master/pypfopt/base_optimizer.py#L398 https://github.com/robertmartin8/PyPortfolioOpt/blob/master/pypfopt/base_optimizer.py#L401