explaingit

pyportfolio/pyportfolioopt

5,716Jupyter NotebookAudience · dataComplexity · 3/5LicenseSetup · easy

TLDR

Python library that uses modern portfolio theory to calculate how to split money across investments, producing percentage weights that maximize returns for a chosen level of risk.

Mindmap

mindmap
  root((repo))
    What it does
      Portfolio optimization
      Efficient frontier
      Weight allocation
    Methods
      Mean-variance
      Black-Litterman
      Hierarchical parity
    Features
      Custom constraints
      Share count output
      Covariance options
    Audience
      Data analysts
      Finance teams
Click or tap to explore — scroll the page freely

Code map

Detail Auto

An interactive map of this repo's files and how they connect — its source is parsed live in your browser. Click Visualize to build it.

filefunction / class

Things people build with this

USE CASE 1

Calculate the optimal stock allocation that maximizes the Sharpe ratio from historical price data.

USE CASE 2

Convert percentage portfolio weights into actual share counts for a fixed cash budget.

USE CASE 3

Apply Black-Litterman allocation to blend your own market views with standard mean-variance optimization.

USE CASE 4

Set constraints like maximum position size or sector limits when optimizing a portfolio.

Tech stack

PythonJupyter NotebookPyPINumPySciPy

Getting it running

Difficulty · easy Time to first run · 30min

Requires historical price data in a pandas DataFrame format, typically fetched from yfinance or loaded from a CSV.

Use freely for any purpose including commercial, modify and redistribute, as long as you include the MIT license notice.

In plain English

PyPortfolioOpt is a Python library for deciding how to split money across a set of investments to get the best return for a given level of risk. The core idea comes from a 1952 academic paper by Harry Markowitz: by combining assets that do not all move up and down together, you can build a portfolio that achieves better risk-adjusted returns than any single asset alone. The set of best possible portfolios for each level of risk is called the efficient frontier, and this library can compute it automatically from historical price data. To use the library, you feed it a table of historical stock prices. It calculates the expected return and the covariance between assets, then runs an optimization to find the combination of weights that hits your goal, which might be maximizing the Sharpe ratio (a score that measures how much return you get per unit of risk), minimizing overall volatility, or hitting a specific target return. The output is a set of percentage weights. A separate step can then convert those weights into actual share counts given a budget, for example telling you to buy 19 shares of one stock and 57 of another with $10,000. Beyond the classical mean-variance approach, the library also implements Black-Litterman allocation, which lets you blend your own views about future returns with market-implied estimates. It also includes Hierarchical Risk Parity, a newer method that groups assets by similarity before allocating, which can be more stable when there is uncertainty about future correlations. Several options exist for estimating the covariance matrix, including methods that shrink the raw sample covariance toward a more stable estimate. Constraints can be added to any optimization, such as keeping individual position sizes within bounds, requiring that the portfolio hold only long positions, or setting a maximum sector exposure. The library is designed to be extended: you can define custom objective functions and add them alongside the built-in ones. The project is MIT licensed, published on PyPI, and includes a cookbook of Jupyter notebooks walking through real examples from data download to final allocation. A paper describing the library was published in the Journal of Open Source Software.

Copy-paste prompts

Prompt 1
Using PyPortfolioOpt with historical price data from yfinance, write Python code that calculates expected returns, builds a covariance matrix, and finds the max Sharpe ratio portfolio weights for a list of 10 stocks.
Prompt 2
I have a 15-stock portfolio and want to minimize volatility while keeping no single position above 20% and excluding short positions. Write the complete PyPortfolioOpt code with those constraints applied.
Prompt 3
Show me how to use PyPortfolioOpt's DiscreteAllocation to convert portfolio weights into actual share counts for a $50,000 budget, including how to report the leftover cash.
Prompt 4
I want to use Black-Litterman with PyPortfolioOpt. I believe two specific stocks will outperform the market by 5%. Show me the code to input those views and extract the updated portfolio weights.
Open on GitHub → Explain another repo

← pyportfolio on gitmyhub — every repo by this author, as a profile.

Verify against the repo before relying on details.