Skip to content

About

Python algorithmic-trading simulator for strategy development and execution-cost study. Simulated results only; no live trading.

Topics

Resources

Stars

2 stars

Watchers

0 watching

Forks

Repository files navigation

Statistical Arbitrage & Execution Research Engine

Cointegration • Dynamic Hedge Estimation • Walk-Forward Validation • Execution & TCA

Public portfolio build for the Advanced Algorithmic Trading Simulator (AATS) family. This is the canonical public surface — not a live trading product and not a private research twin. Older non-public name variants are legacy scaffolds / placeholders slated for retirement; see docs/POSITIONING.md.

A statistical arbitrage research repository focused on research validity, temporal discipline, execution-cost awareness, portfolio accounting, reproducibility, and truthful claims. The repository preserves the original event-driven pairs prototype, but now positions it explicitly as a research engine rather than a finished production trading stack.

Headline result

The pre-registered 2025 walk-forward evaluation (statarb_hist_etf_wf_v4, 19 US ETFs in four within-group buckets) ran once over three pure-2025 test windows (2025-01-08 → 2025-10-09). Each window tested 55 candidate pairs (165 in total); zero survived Benjamini-Hochberg FDR control, so zero pairs qualified and zero trades were placed.

This is the intended behavior of multiple-testing control, not a pipeline failure: the same screen admitted four pairs in the earlier development windows. In 2025, no candidate met the pre-specified threshold, so the strategy rules generated no position. Because no positions were taken, no 2025 Sharpe ratio, drawdown, return or turnover figure exists, and none is estimated or implied.

Post-publication correction. Current main includes the corrected Benjamini-Hochberg step-up implementation merged through PR #13. The accepted study artifacts remain frozen to their recorded producing lineage and were not regenerated. The corrected rule leaves the 2025 zero-survivor / zero-trade result unchanged; possible changes to pre-2024 selected-pair identities require a separately named impact run against the original hash-matching frozen data. See docs/post-publication-bh-correction.md.

Known defects and unreported results (2026-11-14). The position-sizing code does not trade the tested spread, and the four development windows that traded have out-of-sample results the write-up did not report. Neither affects the 2025 zero-trade result. See docs/known-defects-and-unreported-results.md.

What the 2025 null could have detected. A power study of the frozen screen (research/power/REPORT.md) found it detects a truly cointegrated pair 98% of the time at a 5-day spread half-life, 51% at 10 days and 4% at 20 days. The 2025 result therefore rules out week-scale mean reversion only; it does not rule out slower mean reversion.

Disclaimer. Research and educational material only. Nothing here is investment advice or a recommendation to trade. The live-order scripts under scripts/ are unsupported examples.

Research hypothesis and architecture

The working hypothesis is transparent mean-reversion in cointegrated pairs, evaluated with:

  • Static OLS Hedge Ratio as the explicit baseline
  • Sequential Kalman hedge estimation as the dynamic alternative
  • Formation / validation / test chronology with no random splits
  • Formation-only pair selection with Benjamini-Hochberg / FDR control on Engle-Granger scan p-values
  • Decision-time-safe trailing normalization for z-score signals, excluding the current spread from its own mean/std estimate
  • Stylized cost-aware execution simulation with commissions, spread, slippage, and impact scenarios
  • Portfolio ledger accounting for cash, positions, realized PnL, unrealized PnL, exposure, and NAV

What is implemented vs. what is not

Implemented in this public repo:

  • event-time synchronization so pair signals wait for same-timestamp observations from both legs
  • chronological split helpers and walk-forward window generation
  • static OLS baseline diagnostics and sequential Kalman beta path estimation
  • FDR-controlled pair selection on formation data
  • stylized partial-fill / VWAP execution simulation with configurable scenario costs
  • portfolio accounting and conservative performance-analytics helpers

Explicit limitations and truthful positioning:

  • the execution simulator is stylized and not an empirical L2 market microstructure reconstruction
  • the static baseline is not dynamic; previous README language claiming a dynamic hedge ratio from full-history polyfit was incorrect and has been corrected
  • the pre-registered 2025 evaluation produced no trades (see Headline result), so this repository makes no out-of-sample performance claim
  • the universe examples are still static convenience lists and therefore remain exposed to survivorship / selection bias if treated as a production universe
  • static OLS vs Kalman nuance: fit_dynamic_kalman_hedge_ratio (src/stat_arb_engine/research.py) reports two residuals. predictive_innovation is the one-step-ahead innovation e_t = y_t - (alpha_{t|t-1} + beta_{t|t-1} x_t), computed before the update with y_t, with its predictive variance in innovation_variance; this is the out-of-sample spread for signal work. fitted_spread (alias in_sample_residual) is computed from the state after the update with y_t, so it is an in-sample diagnostic that is shrunk toward zero by construction (it equals e_t scaled by R / S_t). fitted_spread is unchanged for backward compatibility and still feeds the published walk-forward z-scores; it never uses data after bar t, and the v4 walk-forward backtest (lag_for_execution in src/stat_arb_engine/wf_v4_backtest.py) executes each bar with the hedge ratio (and position) decided at t-1, so the published results are unaffected
  • live/paper Alpaca integration remains secondary to the default research/backtest workflow and now requires explicit live opt-in

Repository layout

src/stat_arb_engine/        # Research engine package
scripts/main.py             # Synthetic offline demonstration
scripts/pair_finder.py      # Live-data pair scan bridge using formation-only research logic
scripts/live_trading.py     # Secondary Alpaca bridge (explicit live opt-in)
scripts/live_feed.py        # Alpaca data feed used by the legacy entry points
scripts/                    # Also holds the data-acquisition and study runners
research/                   # Experiment ledger and study records
publication/stat-arb-study/ # Technical write-up + offline reproducibility bundle
results/

scripts/main.py, scripts/pair_finder.py, scripts/live_trading.py and scripts/live_feed.py are legacy entry points kept for the original prototype workflow (formerly at the repository root); the research code lives in src/stat_arb_engine/.

Setup

Core research environment (Python 3.11+):

pip install -e ".[dev]"
pytest -q
ruff check .
mypy

Reproducible install

For an exact, fully pinned environment (targets Python 3.12):

pip install -r requirements-lock.txt && pip install -e . --no-deps

Regenerate with uv pip compile pyproject.toml --extra dev --python-version 3.12 --no-header -o requirements-lock.txt (the header comment in the lock file records the exact command).

Quickstart (synthetic offline demo)

No market data or API keys required. After pip install -e ".[dev]":

python scripts/main.py

This runs the event-driven pairs prototype on synthetic prices and prints a local equity-curve summary (NAV / PnL / Sharpe on the synthetic path only). It is a workflow smoke test, not an out-of-sample performance claim (see Headline result above — the 2025 walk-forward produced zero trades, so no OOS Sharpe / return / drawdown figure exists).

Docker (optional; same synthetic entrypoint):

docker build -t aats-public .
docker run --rm aats-public

Optional live integration extras:

pip install -e ".[dev,live]"
cp .env.example .env
# edit .env with Alpaca credentials

Research workflow summary

  1. Build a formation window.
  2. Scan candidate pairs on formation data only.
  3. Apply BH/FDR control to Engle-Granger scan p-values.
  4. Use residual ADF as a secondary diagnostic filter rather than double-counted evidence.
  5. Estimate the baseline Static OLS Hedge Ratio and compare against the sequential Kalman model.
  6. Generate z-score signals from prior-window statistics only; do not let the current spread normalize itself.
  7. Evaluate on untouched validation / test windows or walk-forward slices.
  8. Report assumptions, cost scenarios, and limitations alongside results.

Reproducible artifacts

The executed historical study lives in results/historical_oos/ and is documented in publication/stat-arb-study/. Additional artifact directories are reserved under:

  • results/synthetic/
  • results/walk_forward/
  • results/pair_selection/
  • results/execution_costs/
  • results/factor_attribution/
  • results/sensitivity/

Directories without a committed run contain placeholder READMEs rather than fabricated metrics.

Consolidation note / AATS family

This repository is the canonical public AATS / stat-arb research surface for portfolio use. Cluster map of the four AATS-named repos (and retirement guidance for private legacy twins): docs/POSITIONING.md.

This repository supersedes earlier exploratory statistical-arbitrage repositories.

Live trading safety

Research/backtesting is the default path.

Live order submission is intentionally secondary and requires --live explicit opt-in. The Alpaca paper account is the default; --no-paper selects the live account, and the selected account and order mode are logged at startup. Even then, this repository should be treated as a research environment with stylized execution assumptions rather than production deployment evidence.

License

Apache-2.0 — see LICENSE. © 2026 Micap AI LLC.

Author

Micap AI LLC · contact@micap.pro · https://github.com/jmiaie

About

Python algorithmic-trading simulator for strategy development and execution-cost study. Simulated results only; no live trading.

Topics

Resources

Stars

2 stars

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages