robertmartin8 / PyPortfolioOpt

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

ValueError: P must be symmetric/Hermitian. #479

Closed mezog closed 1 year ago

mezog commented 1 year ago

What are you trying to do? I'm just trying to get familiar with PyPortfolioOpt. The code I am using is below.

mu = pypfopt.expected_returns.mean_historical_return(data)
S = pypfopt.risk_models.sample_cov(data)
ef = pypfopt.efficient_frontier.EfficientFrontier(mu, S)
weights = ef.min_volatility()
print(weights)

When this code runs I get: ValueError: P must be symmetric/Hermitian

What have you tried? I check the shape of the S and ef matrix and dialed the error down to ef.min_volatility(). I'm not sure what to do next but go through the PyPortfolioOpt code and figure out where the math is going wrong.

What data are you using? I am using the daily open price values for 13,259 assets for the last 1000 days. This is everything in the US Market that has data associated with it.

robertmartin8 commented 1 year ago

Hi,

Portfolio optimisation fails when the number of assets is greater than the number of time periods (singular covariance matrix).

You could try Ledoit-Wolf shrinkage but really portfolio optimisation is not the best tool for this.

Cheers, Robert On 26 Aug 2022, 21:59 +0100, mezog @.***>, wrote:

What are you trying to do? I'm just trying to get familiar with PyPortfolioOpt. The code I am using is below. mu = pypfopt.expected_returns.mean_historical_return(data) S = pypfopt.risk_models.sample_cov(data) ef = pypfopt.efficient_frontier.EfficientFrontier(mu, S) weights = ef.min_volatility() print(weights) When this code runs I get: ValueError: P must be symmetric/Hermitian What have you tried? I check the shape of the S and ef matrix and dialed the error down to ef.min_volatility(). I'm not sure what to do next but go through the PyPortfolioOpt code and figure out where the math is going wrong. What data are you using? I am using the daily open price values for 13,259 assets for the last 1000 days. This is everything in the US Market that has data associated with it. — Reply to this email directly, view it on GitHub, or unsubscribe. You are receiving this because you are subscribed to this thread.Message ID: @.***>

JustinGuese commented 1 year ago

I'm getting this error a lot with clean data, and it happens when the S contains nan... I tried setting nan's to zero, but then the weights are all negative... any ideas how to solve this? It literally happens every time I choose more than the top 5 stocks...

robertmartin8 commented 1 year ago

If you have clean data, the covariance matrix should not have NaNs in it...

Generally one must be careful about modifying the cov matrix after its construction, because as the library points out, the covariance matrix must be symmetric/hermitian.