PyPortfolioOpt

raw JSON →
1.6.0 verified Mon Apr 27 auth: no python

PyPortfolioOpt is a financial portfolio optimization library for Python, providing methods for mean-variance optimization, Black-Litterman allocation, and risk parity. Version 1.6.0 supports CVXPY-based solvers and offers both classical and objective-based optimization approaches. Release cadence is irregular, with contributions from the community.

pip install pyportfolioopt
error pypfopt.exceptions.OptimizationError: No feasible solution found
cause The optimization constraints (e.g., weight bounds, target return) are too tight, or the covariance matrix is singular.
fix
Relax bounds, check for duplicate assets, or use a non-singular risk model like Ledoit-Wolf shrinkage.
error ImportError: cannot import name 'EfficientFrontier' from 'pypfopt'
cause Installed pyportfolioopt via pip but tried to import from 'pyportfolioopt' instead of 'pypfopt'.
fix
Change import to 'from pypfopt import EfficientFrontier'
error cvxpy.error.SolverError: Solver 'ECOS' failed. Try another solver.
cause The default solver ECOS may not be installed or fails on some problems (e.g., integer constraints).
fix
Install an alternative solver like SCS (pip install scs) or CVXOPT (pip install cvxopt) and specify solver='SCS' or solver='CVXOPT'.
gotcha Import package as pypfopt, not pyportfolioopt. The pip install name and the import name differ.
fix Use 'from pypfopt import ...' instead of 'from pyportfolioopt import ...'
gotcha CVXPY may require a separate solver installation (e.g., 'pip install cvxpy') on some systems, especially for advanced solvers like ECOS or SCS.
fix Install CVXPY with pip install cvxpy or use the bundled solver (may not work for large problems).
breaking In version 1.5+, the EfficientFrontier object no longer accepts a target return as a parameter to some methods; use objective functions instead.
fix Use methods like `ef.efficient_return(target_return)` directly, not via a constructor parameter.
deprecated The `pypfopt.plotting` module is deprecated as of version 1.6.0 and will be removed in a future release.
fix Use matplotlib directly to plot efficient frontier or weights.

Basic mean-variance optimization using historical returns and sample covariance.

import pandas as pd
from pypfopt import EfficientFrontier, risk_models, expected_returns

# Sample data: prices of 3 assets
data = pd.DataFrame({
    'AAPL': [1.0, 0.9, 0.8, 0.85],
    'GOOG': [1.0, 1.1, 1.0, 1.05],
    'MSFT': [1.0, 0.95, 1.1, 1.0]
})

# Calculate expected returns and covariance matrix
mu = expected_returns.mean_historical_return(data)
Sigma = risk_models.sample_cov(data)

# Optimize for maximum Sharpe ratio
ef = EfficientFrontier(mu, Sigma)
weights = ef.max_sharpe()

print(ef.clean_weights())