Skip to content

Latest commit

 

History

1 Commit

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Quantitative Statistical Arbitrage & Pairs Trading Engine

An explainable, modular, event-driven statistical-arbitrage research framework built from scratch in Python and React. Implements cointegration testing (Engle-Granger & Johansen), dynamic hedge ratios (OLS, Total Least Squares, online Kalman Filter state-space), Ornstein-Uhlenbeck mean-reversion diagnostics, stateful hysteresis signal generation, event-driven backtesting, multi-dimensional sensitivity grids, automated LaTeX paper generation, and an interactive Web Dashboard.

Normalized Prices Spread and Signals Equity Curve


Key Features & Explainability Enhancements

  1. Econometric Cointegration Testing Suite:
    • Engle-Granger Two-Step Procedure: OLS regression followed by Augmented Dickey-Fuller (ADF) test on residual spread ($s_t = y_t - \alpha - \beta x_t$).
    • Johansen Trace & Max-Eigenvalue Test: Vector Error Correction Model (VECM) estimating cointegration rank $r$.
  2. Multiple Hedge Ratio Estimators:
    • Ordinary Least Squares (OLS): Asymmetric vertical error minimization.
    • Total Least Squares (TLS): Symmetric orthogonal distance minimization via Singular Value Decomposition (SVD).
    • Huber Robust Regression: Outlier-resistant loss function for spike filtering.
    • Kalman Filter Dynamic State-Space Model: Online time-varying estimation of $\beta_t$ that adapts dynamically to structural regime shifts.
  3. Statistical Diagnostics:
    • Ornstein-Uhlenbeck (OU) Mean-Reversion Half-Life: Discretized SDE regression ($d s_t = \theta(\mu - s_t) dt + \sigma dW_t \implies t_{1/2} = \frac{-\ln 2}{\lambda}$).
    • Hurst Exponent ($H$): Rescaled Range (R/S) analysis for memory ($H < 0.5 \implies$ mean-reverting).
    • Markout Analysis: Trade P&L decomposition at horizons $k \in {1, 3, 5, 10, 20}$ days post fill.
  4. Honest Event-Driven Backtesting:
    • Strictly Lagged Execution: Signals generated at close $t$ are executed at close $t+1$ to eliminate look-ahead bias.
    • Dollar-Neutral Capital Allocation: Weighted by $w = \frac{1}{1 + |\beta|}$.
    • Friction Drag Modeling: Charges proportional commission ($c$ bps) and slippage on position flips.
  5. Multi-Dimensional Sensitivity Engine:
    • 2D grid matrix evaluating Sharpe ratio and return decay across entry threshold $z^*$ vs transaction cost $c$ bps.
  6. Automated LaTeX Research Paper Engine:
    • Compiles paper.tex dynamically injecting computed metrics, LaTeX math derivations, and figure references.
  7. Interactive Web Visualizer & Educational Dashboard:
    • Modern React/Vite web application with live parameter sliders ($w$, $z^*$, $z_{\text{exit}}$, $c$, estimator toggle) and a 4-step interactive explainability guide.

Mathematical Specification

1. Cointegration Spread & Rolling Z-Score

Given asset price series $p^y_t$ (EWA) and $p^x_t$ (EWC): $$s_t = p^y_t - \alpha - \beta p^x_t$$ $$z_t = \frac{s_t - \mu_t^{(w)}}{\sigma_t^{(w)}}$$ where $\mu_t^{(w)}$ and $\sigma_t^{(w)}$ are rolling sample mean and sample standard deviation over window $w$.

2. Stateful Hysteresis Position State Machine

$$\pi_t = \begin{cases} +1 & \text{enter Long Spread when } z_t \le -z^_, \\ -1 & \text{enter Short Spread when } z_t \ge +z^_, \\ 0 & \text{exit to Flat when } |z_t| \le z_{\text{exit}}, \\ \pi_{t-1} & \text{otherwise (hold position).} \end{cases}$$

3. Strategy Net Return Accounting

$$r_t = \pi_{t-1} w (\Delta \ln p^y_t - \beta \Delta \ln p^x_t) - \kappa_t$$ $$\kappa_t = c \cdot |\pi_t - \pi_{t-1}| \cdot w (1 + |\beta|)$$


Repository Structure

.
├── data/
│   ├── prices.csv              # Bundled EWA/EWC daily adjusted close prices (2015-2024)
│   └── DATA_SOURCE.txt         # Data provenance ("real" or "synthetic")
├── src/
│   ├── __init__.py             # Package exports
│   ├── statarb.py              # Core quantitative engine (Cointegration, Signals, Backtest)
│   ├── dynamic_hedge.py        # Estimators (OLS, TLS, Huber, Kalman Filter)
│   ├── diagnostics.py          # OU Half-life, Hurst Exponent, Markout Analysis
│   ├── fetch_data.py           # Data seeder (yfinance API fetcher + VECM synthetic generator)
│   ├── run_analysis.py         # Pipeline execution -> figures/ & results/
│   ├── make_paper.py           # LaTeX paper generator (paper.tex)
│   └── make_site.py            # Static site generator (site/index.html)
├── tests/
│   ├── test_statarb.py         # 14 unit tests for pure core logic
│   └── test_advanced.py        # 5 unit tests for dynamic hedge & diagnostics
├── web/                        # Modern React + Vite Interactive Dashboard
│   ├── src/
│   │   ├── App.jsx             # Main interactive application
│   │   ├── components/         # Control panel, charts, walkthrough, trade ledger
│   │   └── data/               # Serialized execution payload
│   ├── index.html
│   └── package.json
├── figures/                    # Generated PNG visualizations
├── results/
│   ├── metrics.json            # Machine-readable quantitative outputs
│   └── dashboard_payload.json  # Full serialized time series payload
├── paper.tex                   # Rendered research paper
├── requirements.txt
└── README.md

Quick Start Guide

1. Python Environment Setup

# Create virtual environment
python3 -m venv .venv
source .venv/bin/activate

# Install dependencies
pip install -r requirements.txt

2. Run Full Offline Analysis & Generate Paper

# Run quantitative pipeline (computes tests, backtest, 6 figures, metrics.json)
python src/run_analysis.py

# Generate LaTeX paper & static HTML site
python src/make_paper.py
python src/make_site.py

3. Run Pytest Unit Test Suite

pytest tests/ -v

4. Launch Interactive Web Dashboard

cd web
npm install
npm run dev

Open http://localhost:3000 in your browser to interactively adjust parameters, view charts, and explore the explainability guide.


Empirical Performance Summary

Metric Value
Engle-Granger ADF p-value 0.0186 (Reject $H_0$)
Johansen Trace Statistic 20.06 (Crit 95% = 15.49)
OLS Hedge Ratio $\beta$ 0.5458
OU Mean-Reversion Half-Life 35.5 Days
Hurst Exponent ($H$) 0.42 (Anti-persistent / Mean-reverting)
Annualized Sharpe Ratio 0.73 (Net of 5 bps friction)
Sortino Ratio 0.64
Calmar Ratio 0.42
Total Cumulative Return +59.97%
Hit Rate 76.6%
Profit Factor 2.72

About

A cointegration-based statistical-arbitrage / pairs-trading research project

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages