robertmartin8 / PyPortfolioOpt

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

Bug in Cookbook 2-Mean-Variance-Optimisation #390

Closed nicktids closed 2 years ago

nicktids commented 2 years ago

Describe the bug The last cell of Cookbook 2 does not run due to InstantiationError: The objective function was changed after the initial optimization. Please create a new instance instead.

Expected behavior I believe is the ef.max_sharpe() where a new objective function is being created

Code sample

mu = expected_returns.capm_return(prices)
S = risk_models.CovarianceShrinkage(prices).ledoit_wolf()

ef = EfficientFrontier(mu, S)

fig, ax = plt.subplots()
plotting.plot_efficient_frontier(ef, ax=ax, show_assets=False)

# Find and plot the tangency portfolio
ef.max_sharpe()
ret_tangent, std_tangent, _ = ef.portfolio_performance()
ax.scatter(std_tangent, ret_tangent, marker="*", s=100, c="r", label="Max Sharpe")

# Plot random portfolios
ax.scatter(stds, rets, marker=".", c=sharpes, cmap="viridis_r")

# Format
ax.set_title("Efficient Frontier with random portfolios")
ax.legend()
plt.tight_layout()
plt.show()

Additional context Love the work and effort you have put in here, I'm trying to build an efficient portfolio for work for an asset allocation problem. To show a possible long term returns for a set asset allocation.

Tested on your Binder as well in case it was my environment https://hub.gke2.mybinder.org/user/robertmartin8-pyportfolioopt-1fz91ksx/notebooks/cookbook/2-Mean-Variance-Optimisation.ipynb

nicktids commented 2 years ago

ok same as https://github.com/robertmartin8/PyPortfolioOpt/issues/373

robertmartin8 commented 2 years ago

I’ll fix the notebook

nicktids commented 2 years ago

Thanks

Yes Probably should not have closed when I found the error, as still a bug

sy2384 commented 2 years ago

Using a new ef to max_sharpe fixes the problem for me:

...
# Find and plot the tangency portfolio
ef2 = EfficientFrontier(mu, S)
ef2.max_sharpe()
ret_tangent, std_tangent, _ = ef2.portfolio_performance()
...

And, big thanks to Robert for the amazing work!