https://github.com/cvxgrp/cvxcla

critical line algorithm for efficient frontier

https://github.com/cvxgrp/cvxcla

Science Score: 36.0%

This score indicates how likely this project is to be science-related based on various indicators:

  • CITATION.cff file
  • codemeta.json file
    Found codemeta.json file
  • .zenodo.json file
    Found .zenodo.json file
  • DOI references
  • Academic publication links
    Links to: researchgate.net, wiley.com
  • Committers with academic emails
  • Institutional organization owner
  • JOSS paper metadata
  • Scientific vocabulary similarity
    Low similarity (12.7%) to scientific vocabulary

Keywords

critical-line-algorithm efficient-frontier markowitz

Keywords from Contributors

unit-test labels numerical-optimization
Last synced: 5 months ago · JSON representation

Repository

critical line algorithm for efficient frontier

Basic Info
Statistics
  • Stars: 16
  • Watchers: 3
  • Forks: 4
  • Open Issues: 10
  • Releases: 25
Topics
critical-line-algorithm efficient-frontier markowitz
Created over 2 years ago · Last pushed 6 months ago
Metadata Files
Readme Contributing License Code of conduct

README.md

📈 cvxcla - Critical Line Algorithm for Portfolio Optimization

PyPI version Apache 2.0 License Downloads Coverage Status Renovate enabled

CI pre-commit

Open in GitHub Codespaces

📋 Overview

cvxcla is a Python package that implements the Critical Line Algorithm (CLA) for portfolio optimization. The CLA efficiently computes the entire efficient frontier for portfolio optimization problems with linear constraints and bounds on the weights.

The Critical Line Algorithm was introduced by Harry Markowitz in The Optimization of Quadratic Functions Subject to Linear Constraints and further described in his book Portfolio Selection.

The algorithm is based on the observation that the efficient frontier is a piecewise linear function when expected return is plotted against expected variance. The CLA computes the turning points (corners) of the efficient frontier, allowing for efficient representation of the entire frontier.

I gave the plenary talk at EQD's Singapore conference.

✨ Features

  • Efficient computation of the entire efficient frontier
  • Support for linear constraints and bounds on portfolio weights
  • Multiple implementations based on different approaches from the literature
  • Visualization of the efficient frontier using Plotly
  • Computation of the maximum Sharpe ratio portfolio
  • Fully tested and documented codebase

🚀 Installation

Using pip

bash pip install cvxcla

Development Setup

To set up a development environment:

  1. Clone the repository:

    bash git clone https://github.com/cvxgrp/cvxcla.git cd cvxcla

  2. Create a virtual environment and install dependencies:

    bash make install

This will:

  • Install the uv package manager
  • Create a Python 3.12 virtual environment
  • Install all dependencies from pyproject.toml

🔧 Usage

Here's a simple example of how to use cvxcla to compute the efficient frontier:

```python

import numpy as np # Set a seed for reproducibility np.random.seed(42) from cvxcla import CLA

# Define your portfolio problem n = 10 # Number of assets mean = np.random.randn(n) # Expected returns cov = np.random.randn(n, n) covariance = cov @ cov.T # Covariance matrix lowerbounds = np.zeros(n) # No short selling upperbounds = np.ones(n) # No leverage

Create a CLA instance

cla = CLA( ... mean = mean, ... covariance = covariance, ... lowerbounds = lowerbounds, ... upperbounds = upperbounds, ... a = np.ones((1, n)), # Fully invested constraint ... b = np.ones(1) ... )

# Access the efficient frontier frontier = cla.frontier

# Get the maximum Sharpe ratio portfolio maxsharperatio, maxsharpeweights = frontier.maxsharpe print(f"Maximum Sharpe ratio: {maxsharperatio:.6f}") Maximum Sharpe ratio: 2.946979 # Print first few weights to avoid long output print(f"First 3 weights: {maxsharpe_weights[:3]}") First 3 weights: [0. 0. 0.08509841]

```

For visualization, you can plot the efficient frontier:

```python

Plot the efficient frontier (not run in doctests)

fig = plot_frontier(frontier, volatility=True) fig.show() ```

📚 Literature and Implementations

The package includes implementations based on several key papers:

📝 Niedermayer and Niedermayer

They suggested a method to avoid the expensive inversion of the covariance matrix in Applying Markowitz's critical line algorithm. Our testing shows that in Python, this approach is not significantly faster than explicit matrix inversion using LAPACK via numpy.linalg.inv.

📝 Bailey and Lopez de Prado

We initially started with their code published in An Open-Source Implementation of the Critical-Line Algorithm for Portfolio Optimization. We've made several improvements:

  • Using boolean numpy arrays to indicate whether a weight is free or blocked
  • Rewriting the computation of the first turning point
  • Isolating the computation of λ and weight updates to make them testable
  • Using modern and immutable dataclasses throughout

Our updated implementation is included in the tests but not part of cvxcla package. We use it to verify our results and include it for educational purposes.

📝 Markowitz et al

In Avoiding the Downside: A Practical Review of the Critical Line Algorithm for Mean-Semivariance Portfolio Optimization, Markowitz and researchers from Hudson Bay Capital Management and Constantia Capital present a step-by-step tutorial.

We address a problem they overlooked: after finding the first starting point, all variables might be blocked. We enforce that one variable labeled as free (even if it sits on a boundary) to avoid a singular matrix.

Rather than using their sparse matrix construction, we bisect the weights into free and blocked parts and use a linear solver for the free part only.

🧪 Testing

Run the test suite with:

bash make test

🧹 Code Quality

Format and lint the code with:

bash make fmt

📖 Documentation

👥 Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Run the tests to make sure everything works (make test)
  4. Format your code (make fmt)
  5. Commit your changes (git commit -m 'Add some amazing feature')
  6. Push to the branch (git push origin feature/amazing-feature)
  7. Open a Pull Request

📄 License

This project is licensed under the Apache License 2.0 - see the LICENSE file for details.

🔍 Related Projects

  • PyCLA by Philipp Schiele - A previous implementation of the Critical Line Algorithm in Python.

  • CLA by Martin Dengler - The original implementation by David Bailey and Marcos Lopez de Prado.

Owner

  • Name: Stanford University Convex Optimization Group
  • Login: cvxgrp
  • Kind: organization
  • Location: Stanford, CA

GitHub Events

Total
  • Create event: 126
  • Issues event: 17
  • Release event: 16
  • Watch event: 7
  • Delete event: 114
  • Issue comment event: 72
  • Push event: 572
  • Pull request event: 288
  • Fork event: 1
Last Year
  • Create event: 126
  • Issues event: 17
  • Release event: 16
  • Watch event: 7
  • Delete event: 114
  • Issue comment event: 72
  • Push event: 572
  • Pull request event: 288
  • Fork event: 1

Committers

Last synced: 6 months ago

All Time
  • Total Commits: 571
  • Total Committers: 5
  • Avg Commits per committer: 114.2
  • Development Distribution Score (DDS): 0.433
Past Year
  • Commits: 350
  • Committers: 5
  • Avg Commits per committer: 70.0
  • Development Distribution Score (DDS): 0.386
Top Committers
Name Email Commits
Thomas Schmelzer t****r@g****m 324
renovate[bot] 2****]@u****m 116
dependabot[bot] 4****]@u****m 65
Thomas Schmelzer t****r@a****e 61
pre-commit-ci[bot] 6****]@u****m 5
Committer Domains (Top 20 + Academic)
adia.ae: 1

Issues and Pull Requests

Last synced: 5 months ago

All Time
  • Total issues: 39
  • Total pull requests: 347
  • Average time to close issues: 3 days
  • Average time to close pull requests: about 12 hours
  • Total issue authors: 2
  • Total pull request authors: 4
  • Average comments per issue: 0.18
  • Average comments per pull request: 0.39
  • Merged pull requests: 290
  • Bot issues: 1
  • Bot pull requests: 224
Past Year
  • Issues: 12
  • Pull requests: 242
  • Average time to close issues: 26 minutes
  • Average time to close pull requests: about 9 hours
  • Issue authors: 2
  • Pull request authors: 4
  • Average comments per issue: 0.0
  • Average comments per pull request: 0.38
  • Merged pull requests: 194
  • Bot issues: 1
  • Bot pull requests: 149
Top Authors
Issue Authors
  • tschm (38)
  • renovate[bot] (1)
Pull Request Authors
  • renovate[bot] (136)
  • tschm (123)
  • dependabot[bot] (84)
  • pre-commit-ci[bot] (4)
Top Labels
Issue Labels
Pull Request Labels
dependencies (89) python (42) renovate (25) github_actions (5) pre-commit (5)

Packages

  • Total packages: 1
  • Total downloads:
    • pypi 343 last-month
  • Total dependent packages: 0
  • Total dependent repositories: 0
  • Total versions: 17
  • Total maintainers: 1
pypi.org: cvxcla

Critical line algorithm for the efficient frontier

  • Versions: 17
  • Dependent Packages: 0
  • Dependent Repositories: 0
  • Downloads: 343 Last month
Rankings
Dependent packages count: 10.2%
Stargazers count: 23.1%
Forks count: 29.8%
Average: 37.2%
Downloads: 55.7%
Dependent repos count: 67.1%
Maintainers (1)
Last synced: 6 months ago

Dependencies

pyproject.toml pypi
  • cvxpy * develop
  • cvxsimulator * develop
  • loguru * develop
  • plotly * develop
  • numpy *
  • python >=3.8,<4.0
  • scipy *
.github/workflows/basic.yml actions
  • actions/checkout v3 composite
  • cvxgrp/.github/actions/test main composite
  • pre-commit/action v3.0.0 composite
.github/workflows/book.yml actions
  • JamesIves/github-pages-deploy-action v4.4.3 composite
  • actions/checkout v3 composite
  • actions/download-artifact v3 composite
  • cvxgrp/.github/actions/jupyter main composite
  • cvxgrp/.github/actions/sphinx main composite
  • cvxgrp/.github/actions/test main composite
.github/workflows/ci.yml actions
  • actions/checkout v3 composite
  • cvxgrp/.github/actions/test main composite
.github/workflows/release.yml actions
  • actions/checkout v3 composite
  • cvxgrp/.github/actions/release main composite
poetry.lock pypi
  • 193 dependencies