Skip to main content

investing-quant

A linear programming (LP) based quantitative portfolio optimization system using the Rockafellar-Uryasev CVaR framework.


Purpose

This project implements a multi-constraint portfolio optimizer that allocates capital across a universe of financial instruments — including equity ETFs, fixed income ETFs, and individual stocks — spanning US, EU, and Emerging Markets regions.

The optimizer maximizes expected net return (after transaction fees) subject to a layered set of risk and diversification constraints:

  • Budget constraint — fully invested capital
  • Concentration cap — per-instrument maximum allocation
  • Asset-class bands — minimum and maximum exposure to ETFs, bonds, and stocks
  • Geographic bands — minimum and maximum exposure to US, EU, and Emerging Markets
  • Beta ceiling — portfolio-level market sensitivity limit
  • Weighted volatility ceiling — linear proxy for portfolio risk
  • Liquidity constraint — weighted average days to full liquidation
  • CVaR bound — tail risk limit via Conditional Value at Risk (95% confidence), linearized using Monte Carlo scenarios and the Rockafellar-Uryasev reformulation

The full mathematical formulation (constraints C-1 through C-9) is documented in docs/Investment Portfolio Optimization.pdf.

Disclaimer: This project is intended for educational and analytical purposes only. It does not constitute financial advice.


Two ways to run this: package or notebook

There are two independent, self-contained ways to run the optimizer, each with its own instrument universe and tuned parameters:

  • The iq CLI package (src/investing_quant/) — headless, reads its universe from data/universe.csv (40 instruments) and its parameters from a YAML config (configs/base.yaml). Has a test suite. This is the one to script against or automate.
  • The notebook (notebooks/quant-lp-model.ipynb) — self-contained and Colab-ready, with its own hardcoded 43-instrument universe, sensitivity-sweep experiments, and matplotlib charts that the package does not (yet) reproduce.

They share the same model (ModelParameters, the LP constraints, CVaR scenario generation) but are maintained in parallel, not kept in sync — a correctness fix to one (like the C-9 slack-variable fix below) needs to be applied to the other by hand. A data/parameter change to one (e.g. editing data/universe.csv) does not affect the other.


The advisory agent (axe-quant/)

axe-quant/ is an advisory conversational agent built as a Hermes plugin. It reads an asset list from Telegram or Slack, screens it with a vendored ticker-screener skill over FMP data, classifies the instruments into this package's constraint taxonomy, solves an allocation with solve_portfolio, and reports it back to the same conversation — on demand or on a schedule. It proposes; it never places an order.

The agent is not part of the published investing-quant wheel. The host installs the published package at the version pinned in axe-quant/requirements.txt; development resolves this checkout through [tool.uv.sources]. Its specs live in openspec/changes/add-axe-quant-agent/. See axe-quant/README.md for the host setup, the advisory boundary, and the test suite.


Content Structure

investing-quant/
├── docs/
│   ├── Investment Portfolio Optimization.pdf    # Technical/math reference (constraints C-1..C-9)
│   └── Investment Portfolio Optimization.pptx
├── notebooks/
│   └── quant-lp-model.ipynb        # Self-contained notebook, its own 43-instrument universe
├── data/
│   └── universe.csv                # Package's instrument universe (40 instruments)
├── configs/
│   └── base.yaml                   # Package's tuned model parameters
├── src/investing_quant/            # The iq package (see below)
├── tests/                          # pytest suite for the package
├── axe-quant/                      # advisory Hermes plugin (not in the wheel)
│   ├── plugin/                     # tools, hooks, storage, pipeline
│   ├── skills/                     # orchestrator + vendored ticker-screener
│   ├── tests/                      # agent behaviour and contract tests
│   └── docs/                       # Hermes pin, key rotation, porting notes
├── openspec/                       # specs and changes for both artifacts
├── scripts/
│   ├── extract_universe.py         # One-off script used to generate data/universe.csv
│   └── sync_seed_universe.py       # Copies data/universe.csv into the plugin bundle
├── LICENSE
└── README.md

Notebook Sections (quant-lp-model.ipynb)

Section Description
1 — Setup Imports, solver configuration (GLPK via PuLP)
2 — Instrument Universe Definition of 43 instruments with expected return, beta, volatility, liquidity, and transaction fee
3 — Model Parameters ModelParameters dataclass: capital, concentration caps, asset-class/region bands, risk ceilings
4 — CVaR Scenario Generation Monte Carlo correlated monthly return scenarios
5 — LP Formulation Decision variables, objective function, and constraints C-1 through C-9
6 — Solve GLPK solver execution via PuLP
7 — Extract Results Parsing optimal allocations, VaR/CVaR, and risk metrics from solver output
8 — Portfolio Reports Styled tables, allocation bar and pie charts, constraint compliance, P&L distribution
9 — Sensitivity Analysis CVaR limit, beta ceiling, and concentration cap sweep experiments
10 — Custom Sandbox Template for user-defined parameter experiments
11 — Export Writes portfolio_allocations.csv and portfolio_full_results.csv

Requirements

  • Python 3.11+
  • PuLP below 4 (pulp>=2.8,<4). PuLP 4.0 removed the LpVariable(name, lowBound=...) call form the model uses; the 4.x port is a separate change, and pyproject.toml caps the dependency until then.
  • GLPK system solver (used by both the package and the notebook, via PuLP)
# Debian / Ubuntu
sudo apt install glpk-utils

# macOS (Homebrew)
brew install glpk

# Windows
# Download from https://winglpk.sourceforge.net or use WSL

Running the package (iq CLI)

The package uses uv for dependency management.

uv sync                     # installs into .venv, using uv.lock
uv run iq --help

Validate the bundled universe and config, then solve:

uv run iq validate -u data/universe.csv -c configs/base.yaml
uv run iq optimize -c configs/base.yaml -u data/universe.csv

When both a universe and a config are given, iq validate also checks the composition's feasibility: a band with a positive lower bound and no instruments, lower bounds that overrun the budget, caps that cannot absorb a fully invested budget, or a class/region conflict. iq optimize prints the same diagnosis and refuses to solve a problem the composition LP proves infeasible.

Exit codes: 0 optimal/valid, 1 no optimal result or validation failure, 2 composition infeasible (or nothing to validate).

iq optimize prints the parameter summary, executive summary, active positions, allocation breakdown, constraint compliance, and risk analysis. Add -o DIR to also write DIR/portfolio_allocations.csv and DIR/portfolio_full_results.csv. Override individual parameters without editing the YAML:

uv run iq optimize -c configs/base.yaml -u data/universe.csv --budget 5000 --seed 7 -o out/

To use your own universe or parameters, edit data/universe.csv (same columns as the shipped file) and/or configs/base.yaml, or point -u/-c at different files entirely.

Run the test suite:

uv run pytest              # fast suite
uv run pytest -m slow       # + the full-size golden regression test
uv run ruff check .

Running the notebook

1. Create and activate a virtual environment

python -m venv .venv
source .venv/bin/activate        # Linux / macOS
.venv\Scripts\activate           # Windows

2. Install Python dependencies

pip install numpy pandas polars pulp matplotlib jupyterlab

(Alternatively, uv sync --extra notebook installs these into the package's own .venv.)

3. Launch Jupyter and open the notebook

jupyter lab notebooks/quant-lp-model.ipynb

4. Configure the model

Edit the ModelParameters dataclass in Section 3 to set:

  • W — total capital to allocate
  • U_default — per-instrument concentration cap
  • Asset-class and region allocation bands
  • Risk ceilings: beta_max, sigma_max, liquidity_max_days, cvar_max

5. Run all cells

Execute all notebook cells in order. The solver will find the optimal allocation and render portfolio reports.

6. Export results

Section 11 writes two CSV files to the working directory:

  • portfolio_allocations.csv — active positions with weights and risk metrics
  • portfolio_full_results.csv — full instrument universe with solver outputs

7. Sensitivity experiments (optional)

Sections 9 and 10 contain pre-built and template experiments for exploring how the optimal portfolio changes as individual parameters vary. (These sweeps, and the notebook's matplotlib charts, are not yet reproduced by the iq package.)


Contact

Ramiro Chaparro ramiro@datup.ai


License

MIT License — Copyright 2026 Datup AI

See LICENSE for full terms.

Metadata

Release files for investing-quant 0.2.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 investing-quant 0.2.0
File Size Uploaded Provenance Actions
investing_quant-0.2.0.tar.gz 1.4 MB Without provenance Details for investing_quant-0.2.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for investing-quant 0.2.0
File Interpreter ABI Platform Actions
investing_quant-0.2.0-py3-none-any.whl Python 3 none any Details for investing_quant-0.2.0-py3-none-any.whl

Total release size: 1.4 MB

Release files / investing_quant-0.2.0.tar.gz

Download URL investing_quant-0.2.0.tar.gz
Size 1.4 MB
Tags Source
SHA-256 checksum
How to use checksums
b017da12059a3cf54ebea66265bba9f22cbaa713677cf43427d91d60a62f2785
BLAKE2b-256 checksum
How to use checksums
9735bc932eff9117a9f01ebd3be4bb96b9d4ce4ed63d940b21c4f37c958bea4b
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.14.8

Release files / investing_quant-0.2.0-py3-none-any.whl

Download URL investing_quant-0.2.0-py3-none-any.whl
Size 23.8 kB
Tags Python 3
SHA-256 checksum
How to use checksums
9b70c8e9d147412009096c8ca8b459e2b3965559bea24431ddcd667683d02f24
BLAKE2b-256 checksum
How to use checksums
c9a07c5e9230b383506588395d1d8848bd71a98b970d033826f46c91d4262739
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.14.8

Security for investing-quant 0.2.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.2.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