Metadata-Version: 2.4
Name: portopt
Version: 0.1.0
Summary: Portfolio optimization library built on skfolio and scikit-learn
Author: Silvio Baratto
License: BSD-3-Clause
Project-URL: Homepage, https://github.com/SilvioBaratto/optimizer
Project-URL: Documentation, https://silviobaratto.github.io/optimizer
Project-URL: Repository, https://github.com/SilvioBaratto/optimizer
Project-URL: Issues, https://github.com/SilvioBaratto/optimizer/issues
Project-URL: Changelog, https://github.com/SilvioBaratto/optimizer/blob/main/CHANGELOG.md
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Financial and Insurance Industry
Classifier: Intended Audience :: Science/Research
Classifier: License :: OSI Approved :: BSD License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Office/Business :: Financial :: Investment
Classifier: Topic :: Scientific/Engineering :: Mathematics
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: numpy>=1.24
Requires-Dist: pandas>=2.0
Requires-Dist: scipy>=1.11
Requires-Dist: scikit-learn>=1.6
Requires-Dist: skfolio>=0.5
Requires-Dist: hmmlearn>=0.3.3
Requires-Dist: arch>=8.0.0
Provides-Extra: test
Requires-Dist: pytest>=7.4; extra == "test"
Requires-Dist: pytest-cov>=4.0; extra == "test"
Requires-Dist: hypothesis>=6.0; extra == "test"
Provides-Extra: lint
Requires-Dist: ruff>=0.1; extra == "lint"
Requires-Dist: pip-audit>=2.6; extra == "lint"
Provides-Extra: typecheck
Requires-Dist: mypy>=1.5; extra == "typecheck"
Requires-Dist: pyright[nodejs]==1.1.398; extra == "typecheck"
Provides-Extra: docs
Requires-Dist: mkdocs-material>=9.0; extra == "docs"
Requires-Dist: mkdocstrings[python]>=0.24; extra == "docs"
Requires-Dist: mkdocs-gen-files>=0.5; extra == "docs"
Requires-Dist: mkdocs-literate-nav>=0.6; extra == "docs"
Provides-Extra: dmm
Requires-Dist: torch>=2.0; extra == "dmm"
Requires-Dist: pyro-ppl>=1.9; extra == "dmm"
Provides-Extra: dev
Requires-Dist: portopt[docs,lint,test,typecheck]; extra == "dev"
Requires-Dist: pre-commit>=3.5; extra == "dev"
Dynamic: license-file

# Portfolio Optimizer

[![CI](https://github.com/SilvioBaratto/optimizer/actions/workflows/ci.yml/badge.svg)](https://github.com/SilvioBaratto/optimizer/actions/workflows/ci.yml)
![Python 3.10+](https://img.shields.io/badge/python-3.10%2B-blue)
[![codecov](https://codecov.io/gh/SilvioBaratto/optimizer/branch/main/graph/badge.svg)](https://codecov.io/gh/SilvioBaratto/optimizer)
![License](https://img.shields.io/badge/license-BSD--3--Clause-green)

Quantitative portfolio construction and optimization platform built on [skfolio](https://skfolio.org/) 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

```bash
pip install -e ".[dev]"
```

```python
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

```bash
# 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

```bash
# 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`](examples/quickstart.py) | MeanRisk optimization with walk-forward backtest |
| [`robust_optimization.py`](examples/robust_optimization.py) | Compare robust portfolios at different kappa values |
| [`regime_blending.py`](examples/regime_blending.py) | HMM fitting and regime-conditional moment estimation |
| [`factor_selection.py`](examples/factor_selection.py) | Factor construction, standardization, and stock selection |
| [`full_pipeline.py`](examples/full_pipeline.py) | End-to-end pipeline with pre-selection and rebalancing |

```bash
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](LICENSE)
