Calculate the optimal stock allocation that maximizes the Sharpe ratio from historical price data.
Convert percentage portfolio weights into actual share counts for a fixed cash budget.
Apply Black-Litterman allocation to blend your own market views with standard mean-variance optimization.
Set constraints like maximum position size or sector limits when optimizing a portfolio.
Requires historical price data in a pandas DataFrame format, typically fetched from yfinance or loaded from a CSV.
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.
← pyportfolio on gitmyhub — every repo by this author, as a profile.
Verify against the repo before relying on details.