Maintained

PyPortfolioOpt guide

PyPortfolioOpt turns textbook portfolio theory into a few readable lines of code.

Last reviewed · Also known as pypfopt

Quick answer

PyPortfolioOpt is a Python library for portfolio optimization: estimate expected returns and covariance (with shrinkage), solve mean-variance problems on the efficient frontier (max Sharpe, min volatility, target return), use Black-Litterman views or hierarchical risk parity, and convert weights into whole-share allocations.

PyPortfolioOpt at a glance

Category
Portfolio optimization & analytics
Language
Python
License
MIT
Does
Performance analytics, Optimization
Markets
Stocks, ETFs, Crypto
Best for
Allocating capital across strategies or assets once you have return estimates.
In AlgoGP
Use the exported strategy object from your own code

Pick it if

Allocating capital across strategies or assets once you have return estimates.

Watch out for

Garbage in, garbage out: optimizers amplify estimation error.

PyPortfolioOpt strengths and limitations

Strengths

  • Clean API and docs.
  • Shrinkage covariance and robust estimators.
  • Discrete allocation helper.

Limitations

  • Garbage in, garbage out: optimizers amplify estimation error.
  • Fewer risk measures than Riskfolio-Lib.

PyPortfolioOpt example

pip install pyportfolioopt
Install
from pypfopt import EfficientFrontier, expected_returns, risk_models
mu = expected_returns.mean_historical_return(prices)
S = risk_models.CovarianceShrinkage(prices).ledoit_wolf()
ef = EfficientFrontier(mu, S)
print(ef.max_sharpe(), ef.clean_weights())
Max-Sharpe weights.

Use PyPortfolioOpt with AlgoGP

AlgoGP does not add PyPortfolioOpt to projects automatically yet, but nothing stops you using them together. Every AlgoGP project exports plain Python with a framework-neutral strategy object, so you can call it from PyPortfolioOpt yourself.

  1. 1

    Design and backtest in AlgoGP

    Describe the idea to the copilot and backtest it on AlgoGP’s normalized history.

  2. 2

    Add any bridge to get the adapter core

    Adding a bridged framework (for example Backtrader) writes frameworks/algogp_bridge.py, whose StrategyBridge.on_bar() returns the orders the strategy wants.

  3. 3

    Call it from PyPortfolioOpt

    Feed PyPortfolioOpt’s bars to StrategyBridge, place the returned orders with PyPortfolioOpt, and report fills back with sync().

PyPortfolioOpt: frequently asked questions

PyPortfolioOpt or Riskfolio-Lib?

PyPortfolioOpt is simpler; Riskfolio-Lib offers many more risk measures and constraints.

PyPortfolioOpt alternatives

Independent guide. AlgoGP is not affiliated with PyPortfolioOpt. Features, licenses and maintenance change; check the official documentation. Nothing here is investment advice.

Build a strategy