Skip to content

ccakirr/statarb_lab

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

6 Commits
 
 
 
 
 
 
 
 

Repository files navigation

Statistical Arbitrage Pairs Trading Lab

This project implements a statistical arbitrage pairs trading strategy for forex pairs using cointegration, hedge ratio estimation, spread normalization, signal generation, backtesting, walk-forward validation, and pair scanning.

The main objective is to test whether two non-stationary price series have a stable long-term relationship and whether deviations from that relationship can be traded using a mean-reversion strategy.

Features

  • Download daily forex price data with yfinance

  • Validate raw price series using the Augmented Dickey-Fuller test

  • Test pair cointegration using the Engle-Granger method

  • Estimate hedge ratio and intercept with OLS regression

  • Compute residual spread

  • Calculate rolling z-score without look-ahead bias

  • Generate long/short/flat trading signals

  • Backtest the spread strategy with transaction costs

  • Compute performance metrics:

    • Total return
    • Sharpe ratio
    • Maximum drawdown
    • Number of trades
  • Generate a four-panel strategy report

  • Run walk-forward validation

  • Scan a forex universe for statistically valid pairs

  • Filter scanner results by AR(1) half-life

Methodology

The strategy is based on the following statistical workflow:

  1. Load two forex price series as Y and X.
  2. Check that both raw price series are non-stationary using the ADF test.
  3. Test whether the two series are cointegrated using the Engle-Granger test.
  4. Estimate the hedge ratio with OLS:
Y = alpha + beta * X + residual
  1. Compute the residual spread:
spread = Y - beta * X - alpha
  1. Confirm that the spread is stationary.

  2. Convert the spread into a rolling z-score.

  3. Generate trading signals:

    • z < -2: long spread
    • z > 2: short spread
    • -0.5 < z < 0.5: close position
  4. Backtest the strategy using shifted signals to avoid look-ahead bias.

Signals are shifted by one period before being applied to returns. This means a signal generated at time t is only traded from time t+1.

Walk-Forward Validation

The walk-forward validation splits the dataset into rolling train/test windows.

For each fold:

  1. The hedge ratio is estimated only on the training window.
  2. Spread mean and standard deviation are learned only from the training spread.
  3. The test window is traded using frozen training parameters.
  4. Folds are skipped if the training data does not satisfy the statistical requirements.

This provides a more realistic out-of-sample validation compared to a full-sample backtest.

Pairs Scanner

The pair scanner tests all pair combinations inside a given forex universe.

For each pair, it applies:

  1. ADF tests on raw price series
  2. Engle-Granger cointegration test
  3. OLS hedge ratio estimation
  4. Spread stationarity check
  5. AR(1) half-life calculation
  6. Half-life filter:
5 < half_life < 60

Valid pairs are sorted by cointegration p-value.

Installation

Clone the repository and install the required Python packages:

pip install -r requirements.txt

Usage

Run the main script:

python pairs.py

The script will:

  1. Download forex price data
  2. Run stationarity and cointegration tests
  3. Build the pairs trading strategy
  4. Run the backtest
  5. Run walk-forward validation
  6. Run the pairs scanner
  7. Save the strategy plot

Example Output

-----Backtest Results-----
Total return: 1.46%
Max drawdown: -3.99%
N trades: 30
Sharpe ratio: 0.1577

-----Walk Forward Results-----
WF Combined Return: 3.55%
WF Mean Fold Return: 1.17%
WF Mean Sharpe: 1.3610
WF Folds: 3
WF Skipped: 3

Plot Output

The strategy creates a four-panel visual report:

  1. Normalized prices of both assets
  2. Residual spread
  3. Z-score with entry and exit zones
  4. Cumulative strategy returns

The plot is saved as:

pairs_result.png

Limitations

This project is a simplified research backtest. It does not model all real-world trading conditions.

Current limitations include:

  • No bid/ask spread modeling
  • No slippage modeling
  • No leverage or margin modeling
  • No realistic FX order execution
  • No live trading integration
  • Simplified spread-level return calculation
  • Historical statistical relationships may break in future market regimes

Disclaimer

This project is for educational and research purposes only. It is not financial advice and should not be used as a live trading system without further validation, risk management, and execution modeling.

About

A Python research lab for forex pairs trading using Engle-Granger cointegration, OLS hedge ratios, z-score mean reversion, walk-forward validation, and pair scanning.

Topics

Resources

Stars

Watchers

Forks

Releases

Packages

Contributors

Languages