# 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)
