Portfolio Optimization with PyPortfolioOpt
Use PyPortfolioOpt to compute efficient frontiers, optimize portfolio weights, and analyze risk metrics.
Installation and Data Preparation
PyPortfolioOpt provides portfolio optimization methods including mean-variance, Black-Litterman, and HRP. ```bash pip install PyPortfolioOpt pandas yfinance
Prepare price data:
```python
import yfinance as yf
tickers = ["AAPL", "MSFT", "GOOGL", "AMZN", "TSLA"]
prices = yf.download(tickers, start="2022-01-01", end="2024-06-01")["Close"]
returns = prices.pct_change().dropna()Mean-Variance Optimization
Find the optimal risk-return tradeoff using Markowitz optimization. ```python from pypfopt import EfficientFrontier, risk_models, expected_returns mu = expected_returns.mean_historical_return(prices) S = risk_models.sample_cov(prices) ef = EfficientFrontier(mu, S) weights = ef.max_sharpe() cleaned_weights = ef.clean_weights() for ticker, weight in cleaned_weights.items(): if weight > 0.01: print(f"{ticker}: {weight:.4f}") ef.portfolio_performance(verbose=True)
Use `ef.min_volatility()` for minimum variance or `ef.efficient_return(0.2)` for target return.Hierarchical Risk Parity (HRP)
HRP uses clustering for diversification without matrix inversion. ```python from pypfopt import HRPOpt hrp = HRPOpt(returns) hrp_weights = hrp.optimize() hrp.portfolio_performance(verbose=True) from pypfopt import plotting import matplotlib.pyplot as plt plotting.plot_dendrogram(hrp) plt.show()
HRP produces more stable allocations than mean-variance for large asset universes.Verified by
editor
Last verified
2026-06-24
