Skip to main content

Portfolio Optimizer

CI Python 3.10+ codecov License

Quantitative portfolio construction and optimization platform built on skfolio and scikit-learn.

Architecture

optimizer/          Pure-Python optimization library (DB-agnostic, sklearn/skfolio-based)
  preprocessing/    Return data cleaning (validation, outlier treatment, sector imputation)
  pre_selection/    Asset filtering pipeline (completeness, variance, correlation, dominance)
  moments/          Expected return and covariance estimation
  views/            Black-Litterman, Entropy Pooling, Opinion Pooling
  optimization/     Mean-risk, risk budgeting, HRP/HERC/NCO, stacking
  synthetic/        Vine copula scenario generation and stress testing
  validation/       Walk-forward, combinatorial purged CV, randomized CV
  scoring/          Performance scoring for model selection
  tuning/           Grid search and randomized search with temporal CV
  rebalancing/      Calendar and threshold-based rebalancing
  pipeline/         End-to-end orchestration (prices → validated weights)

api/                FastAPI backend (PostgreSQL, BAML, Trading 212 integration)
cli/                Typer CLI (data fetching, universe management, macro regime analysis)
tests/              Test suite for the optimizer library
theory/             LaTeX/Markdown theoretical documentation

Quick Start — Optimizer Library

pip install -e ".[dev]"
import pandas as pd
from optimizer.optimization import MeanRiskConfig, build_mean_risk
from optimizer.validation import WalkForwardConfig
from optimizer.pipeline import run_full_pipeline

# Load price data (DatetimeIndex, one column per asset)
prices = pd.read_csv("prices.csv", index_col=0, parse_dates=True)

# Configure and run
optimizer = build_mean_risk(MeanRiskConfig.for_max_sharpe())
cv_config = WalkForwardConfig.for_quarterly_rolling()

result = run_full_pipeline(
    prices=prices,
    optimizer=optimizer,
    cv_config=cv_config,
)

print(result.weights)
print(result.summary)

Quick Start — API + CLI

# Start PostgreSQL
docker compose up -d

# Set up the API
cd api
pip install -r requirements.txt
cp .env.example .env              # Edit with your API keys
alembic upgrade head
uvicorn app.main:app --reload     # http://localhost:8000

# CLI (from project root)
pip install -r requirements.txt
python -m cli --help
python -m cli db health
python -m cli universe stats
python -m cli yfinance fetch

Development

# Install with dev dependencies
pip install -e ".[dev]"

# Run tests
pytest tests/ -v

# Lint
ruff check .

# Type check
mypy .

Examples

Self-contained scripts using synthetic data (no API keys required):

Script Description
quickstart.py MeanRisk optimization with walk-forward backtest
robust_optimization.py Compare robust portfolios at different kappa values
regime_blending.py HMM fitting and regime-conditional moment estimation
factor_selection.py Factor construction, standardization, and stock selection
full_pipeline.py End-to-end pipeline with pre-selection and rebalancing
pip install -e ".[dev]"
python examples/quickstart.py

Environment Variables

Copy .env.example to .env and fill in your API keys. Database defaults match docker-compose.yml and work out of the box.

Variable Description
DATABASE_URL PostgreSQL connection string
FRED_API_KEY Federal Reserve Economic Data
TRADING_212_API_KEY Trading 212 portfolio access
TRADING_ECONOMICS_API_KEY Trading Economics macro data
OPENAI_KEY Azure OpenAI (for BAML chatbot)

Disclaimer

This software is provided for educational and research purposes only. It is not intended as, and shall not be understood or construed as, financial, investment, tax, or legal advice.

No investment advice. The authors and contributors are not registered investment advisors, broker-dealers, or financial planners. Nothing in this software or its documentation constitutes a recommendation to buy, sell, or hold any financial instrument.

No liability for losses. The authors and contributors accept no responsibility or liability whatsoever for any loss or damage arising from the use of this software. You may lose some or all of your invested capital. Use this software entirely at your own risk.

Past performance is not indicative of future results. Backtesting and historical analysis produced by this software do not guarantee future performance. Simulated results may not reflect the impact of real market conditions including liquidity, slippage, fees, and taxes.

Seek professional advice. Before making any investment decision, consult with a qualified, licensed financial advisor, accountant, or attorney.

By using this software, you acknowledge that you have read and understood this disclaimer and agree to be bound by its terms.

License

BSD-3-Clause

Metadata

Release files for portopt 0.1.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for portopt 0.1.0
File Size Uploaded Provenance Actions
portopt-0.1.0.tar.gz 131.2 kB Without provenance Details for portopt-0.1.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for portopt 0.1.0
File Interpreter ABI Platform Actions
portopt-0.1.0-py3-none-any.whl Python 3 none any Details for portopt-0.1.0-py3-none-any.whl

Total release size: 288.9 kB

Release files / portopt-0.1.0.tar.gz

Download URL portopt-0.1.0.tar.gz
Size 131.2 kB
Tags Source
SHA-256 checksum
How to use checksums
a22281c8951006e36fc6a401e9eee09ce2b2560d3983dbc9d3dab3f07c12cbeb
BLAKE2b-256 checksum
How to use checksums
08032606795a4db946f9f0623673897bbe90e82b6af6bd9b163f5ceeb759811c
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.12.7

Release files / portopt-0.1.0-py3-none-any.whl

Download URL portopt-0.1.0-py3-none-any.whl
Size 157.7 kB
Tags Python 3
SHA-256 checksum
How to use checksums
9954549b573a7543dd14fab54072f6137d8b026c33546f6c29e5c5afcaf371f5
BLAKE2b-256 checksum
How to use checksums
07c69e12389bd6bed9b98f939ccd0f1acd317a52f2dee7af9547fedc6a9fc4c2
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.12.7

Security for portopt 0.1.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.1.0 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page