Skip to content

snek5/mvo

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

8 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Portfolio Optimizer v2

A quantitative portfolio optimization framework implementing Modern Portfolio Theory (MPT), Mean-Variance Optimization, Black-Litterman portfolio construction, and convex optimization techniques using Python and CVXPY.

The project combines quantitative finance, numerical optimization, and software engineering principles into a reusable research-oriented framework. Rather than serving as a trading system, the objective is to provide a mathematically rigorous environment for experimenting with portfolio construction methods while maintaining clean software architecture.


Overview

This project was built with three design principles:

  • Mathematical correctness — optimization routines closely follow the original formulations proposed in quantitative finance literature.
  • Reusable software design — optimization logic is separated from the presentation layer, allowing the mathematical engine to be imported into other Python projects.
  • Transparency — every optimization result is reproducible from explicit assumptions instead of hidden heuristics.

The application provides an interactive Streamlit interface while the optimization engine remains framework-independent.


Features

Portfolio Construction

  • Mean-Variance Optimization (Markowitz)
  • Maximum Sharpe (Tangency Portfolio)
  • Global Minimum Variance Portfolio
  • Efficient Frontier generation
  • Monte Carlo portfolio simulation
  • Long-only and long-short optimization
  • Allocation constraints
  • Portfolio rebalancing calculator

Black-Litterman Model

  • Reverse optimization using market equilibrium returns

  • Investor view incorporation

  • Configurable:

    • Market risk aversion (δ)
    • Prior uncertainty (τ)
    • View uncertainty (Ω)
    • Pick matrix (P)
    • Expected views (Q)
  • Optional market-cap weighted equilibrium portfolio

Risk Analysis

  • Annualized covariance matrix
  • Correlation matrix
  • Portfolio volatility
  • Expected return
  • Sharpe ratio
  • Efficient frontier visualization

Mathematical Foundation

Log Returns

Daily log returns are computed as

$$ r_t = \ln\left(\frac{P_t}{P_{t-1}}\right) $$

Log returns are additive through time and exhibit better statistical properties than simple returns for continuous compounding.


Covariance Matrix

The annualized covariance matrix is estimated by

$$ \Sigma = 252 \cdot \mathrm{Cov}(r) $$

where

  • $r$ denotes daily log returns
  • 252 represents the approximate number of trading days per year.

Portfolio volatility is

$$ \sigma_p = \sqrt{w^T \Sigma w} $$


Mean-Variance Optimization

The optimizer solves the classical Markowitz utility maximization problem

$$ \max_w \left( w^T \mu - \frac{\lambda}{2} w^T \Sigma w \right) $$

subject to

$$ \sum_i w_i = 1 $$

along with optional constraints

  • long-only
  • minimum allocation
  • maximum allocation
  • leverage constraints
  • target return
  • target volatility

where

  • (w) denotes portfolio weights
  • (\mu) expected returns
  • (\Sigma) covariance matrix
  • (\lambda) investor risk aversion.

The optimization problem is solved using CVXPY with the ECOS convex optimization solver.


Maximum Sharpe Portfolio

The tangency portfolio maximizes

$$ \frac{w^T \mu - r_f}{\sqrt{w^T \Sigma w}} $$

where

  • $r_f$ is the risk-free rate.

The implementation reformulates the fractional optimization problem into an equivalent convex optimization problem.


Efficient Frontier

The efficient frontier is generated by repeatedly solving

$$ \min_w ; w^T \Sigma w $$

subject to

$$ w^T \mu = r $$

for a sequence of target returns.

This produces the Pareto frontier between expected return and portfolio risk.


Black-Litterman Model

Rather than relying purely on historical returns, the Black-Litterman framework combines

  • market equilibrium expectations
  • subjective investor views

using Bayesian inference.

Implied Equilibrium Returns

The prior expected return is

$$ \pi = \delta \Sigma w_m $$

where

  • ($w_m$) is the market-cap weighted portfolio
  • ($\delta$) is market risk aversion.

Posterior Returns

Investor views are expressed through

  • Pick Matrix ($P$)
  • View Vector ($Q$)
  • View Uncertainty Matrix ($\Omega$)

The posterior expectation becomes

$$ \mu_{BL} = \left( (\tau \Sigma)^{-1} + P^T \Omega^{-1} P \right)^{-1} \left( (\tau \Sigma)^{-1} \pi + P^T \Omega^{-1} Q \right) $$

which blends market equilibrium with subjective beliefs according to their relative confidence.


Software Architecture

.
├── app_v2.py
│   Streamlit user interface
│
├── portfolio_utils.py
│   Quantitative optimization library
│
├── requirements.txt
│
└── README.md

The project intentionally separates

Presentation Layer

  • Streamlit
  • Data loading
  • User interaction

from

Quantitative Engine

  • Optimization
  • Black-Litterman
  • Efficient Frontier
  • Monte Carlo
  • Portfolio statistics

This allows the optimization library to be reused independently of the UI.


Technology Stack

  • Python
  • NumPy
  • Pandas
  • CVXPY
  • Streamlit
  • Matplotlib
  • Yahoo Finance
  • ECOS Solver

Running the Project

Clone

git clone https://github.com/<username>/portfolio-optimizer-v2.git

cd portfolio-optimizer-v2

Create Virtual Environment

python -m venv .venv

Linux / macOS

source .venv/bin/activate

Windows

.venv\Scripts\activate

Install Dependencies

pip install -r requirements.txt

Example requirements

streamlit
numpy
pandas
matplotlib
cvxpy
yfinance
ecos

Launch

streamlit run app_v2.py

The application will open in your browser.


Example Workflow

  1. Select a basket of assets.
  2. Download historical market prices.
  3. Estimate annualized covariance and returns.
  4. (Optional) Specify Black-Litterman investor views.
  5. Perform portfolio optimization.
  6. Compare
  • Maximum Utility Portfolio
  • Tangency Portfolio
  • Efficient Frontier
  1. Export optimized allocations.

Current Limitations

This project focuses on the mathematical foundations of portfolio optimization rather than production portfolio management.

The following are intentionally outside the current scope:

  • Transaction cost modeling
  • Portfolio turnover penalties
  • Factor risk models
  • Covariance shrinkage estimators
  • Walk-forward optimization
  • Rolling backtesting
  • Regime detection
  • Execution algorithms
  • Multi-period optimization

These extensions represent natural future work toward institutional-grade portfolio construction.


Future Improvements

  • Ledoit-Wolf covariance shrinkage
  • Risk parity optimization
  • Hierarchical Risk Parity (HRP)
  • Conditional Value-at-Risk optimization
  • Robust Bayesian estimators
  • Multi-factor models
  • Performance attribution
  • Walk-forward validation
  • Historical stress testing
  • Benchmark comparison
  • Portfolio turnover optimization
  • Transaction cost modeling

References

  • Harry Markowitz (1952), Portfolio Selection
  • Fischer Black & Robert Litterman (1992), Global Portfolio Optimization
  • Stephen Boyd & Lieven Vandenberghe, Convex Optimization
  • Attilio Meucci, Risk and Asset Allocation
  • Grinold & Kahn, Active Portfolio Management

Disclaimer

This project is intended for quantitative research and educational purposes.

It is not investment advice and should not be used as the sole basis for capital allocation decisions. Real-world portfolio management requires robust estimation techniques, transaction cost modeling, execution constraints, and extensive out-of-sample validation.

About

Portfolio Optimizer on Streamlit

Resources

Stars

Watchers

Forks

Releases

Packages

Contributors

Languages