Portfolio optimization library built on skfolio and scikit-learn
Project description
Portfolio Optimizer
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
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file portopt-0.1.0.tar.gz.
File metadata
- Download URL: portopt-0.1.0.tar.gz
- Upload date:
- Size: 131.2 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.12.7
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
a22281c8951006e36fc6a401e9eee09ce2b2560d3983dbc9d3dab3f07c12cbeb
|
|
| MD5 |
200eaf8c390d5d2672c21644f92637d3
|
|
| BLAKE2b-256 |
08032606795a4db946f9f0623673897bbe90e82b6af6bd9b163f5ceeb759811c
|
File details
Details for the file portopt-0.1.0-py3-none-any.whl.
File metadata
- Download URL: portopt-0.1.0-py3-none-any.whl
- Upload date:
- Size: 157.7 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.12.7
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
9954549b573a7543dd14fab54072f6137d8b026c33546f6c29e5c5afcaf371f5
|
|
| MD5 |
0b91281583987e47899a83c6d96c34a4
|
|
| BLAKE2b-256 |
07c69e12389bd6bed9b98f939ccd0f1acd317a52f2dee7af9547fedc6a9fc4c2
|