pair-trading

$npx mdskill add HKUDS/Vibe-Trading/pair-trading

Execute mean-reversion trades on correlated pairs using Z-score signals.

  • Identify opportunities where price ratios deviate significantly from historical averages.
  • Depends on real-time price data for two correlated instruments.
  • Generates long-short signals when Z-scores exceed predefined thresholds.
  • Delivers equal-weighted trade execution with automatic position closing.

SKILL.md

.github/skills/pair-tradingView on GitHub ↗
---
name: pair-trading
description: Pair trading strategy. Trades mean reversion using the spread/ratio Z-score of two correlated instruments. Requires at least two instruments.
category: strategy
---
# Pair Trading Strategy

## Purpose

Select two highly correlated instruments (such as stocks from the same industry or BTC/ETH), monitor how far their price ratio (or spread) deviates from the mean, and trade against extreme deviations while waiting for mean reversion.

## Signal Logic

1. **Compute the price ratio**: `ratio = close_A / close_B`
2. **Rolling mean and standard deviation**: `mean = ratio.rolling(lookback).mean()`, `std = ratio.rolling(lookback).std()`
3. **Z-score**: `z = (ratio - mean) / std`
4. **Signal generation**:
   - Z < -entry_z → long A, short B (ratio is too low, expected to revert)
   - Z > +entry_z → short A, long B (ratio is too high, expected to revert)
   - |Z| < exit_z → close the position (reverted back near the mean)

## Implementation Notes

- Pair trading requires **exactly two instruments** (`codes` array length = 2)
- The first instrument is A (`leg1`), and the second is B (`leg2`)
- Signals for A and B are opposite: when A is long, B is short, and vice versa
- **Equal-weight allocation only**: A and B each take 50% of capital, with no precise hedge-ratio calculation

## Parameters

| Parameter | Default | Description |
|------|--------|------|
| lookback | 60 | Lookback window for mean and standard deviation |
| entry_z | 2.0 | Entry Z-score threshold |
| exit_z | 0.5 | Exit Z-score threshold |

## Example `config.json`

```json
{
  "source": "tushare",
  "codes": ["601318.SH", "601628.SH"],
  "start_date": "2023-01-01",
  "end_date": "2024-12-31",
  "initial_cash": 1000000,
  "commission": 0.001,
  "extra_fields": null
}
```

Cryptocurrency version:
```json
{
  "source": "okx",
  "codes": ["BTC-USDT", "ETH-USDT"],
  "start_date": "2024-01-01",
  "end_date": "2024-12-31",
  "initial_cash": 1000000,
  "commission": 0.001,
  "extra_fields": null
}
```

## Common Pitfalls

- `codes` must contain exactly 2 instruments, no more and no less
- The date indexes of the two instruments must be aligned (use an inner join), otherwise the ratio calculation will be wrong
- Before the lookback window is filled, Z-scores are `NaN`, so fill signals with 0
- Do not generate same-direction signals for both A and B; pair trading is fundamentally a long-short hedge

## Dependencies

```bash
pip install pandas numpy
```

## Signal Convention

- Instrument A: `0.5` = long, `-0.5` = short, `0` = flat
- Instrument B: direction is opposite to A

More from HKUDS/Vibe-Trading

SkillDescription
adr-hshareADR/H-share/A-share cross-listing premium analysis — track pricing gaps between US-listed ADRs, HK-listed H-shares, and A-shares for arbitrage signals, dual-listing valuation, and delisting risk assessment.
akshareAKShare financial data aggregator (18k+ stars). Free, no API key. Covers A-shares, US, HK, futures, macro, forex. Primary fallback for tushare and yfinance.
asset-allocationAsset allocation theory and optimizer usage — MPT / Black-Litterman / risk budgeting / all-weather strategy, including guides for 4 optimizers and rebalancing rules.
backtest-diagnoseDiagnose failed or underperforming backtests, locate the root cause, and fix the issue
behavioral-financeBehavioral finance applications: theories of overreaction and underreaction, behavioral explanations for momentum and reversal, investor sentiment cycles, cognitive-bias checklists, and debiasing quantitative strategies.
candlestickCandlestick pattern recognition engine, pure pandas vectorized implementation of 15 classic candlestick patterns (5 single-candle + 5 double-candle + 4 triple-candle + 1 trend confirmation), generating a composite signal from bullish/bearish pattern scores.
ccxtCCXT unified crypto exchange library (100+ exchanges). Free public market data. Fallback when OKX is unavailable.
chanlun基于缠论(缠中说禅)的形态识别引擎,使用czsc库自动检测K线分型、笔、中枢,并生成一买/一卖/二买/二卖/三买/三卖等买卖点信号。支持多周期分析和形态分类(3/5/7/9/11笔形态)。
commodity-analysisCommodity analysis (oil supply-demand balance / gold pricing / copper as an economic predictor / inventory cycles / futures premium-discount structure / seasonality), generating directional commodity signals.
convertible-bondA股可转债分析——转股/纯债/期权三维估值、下修/强赎/回售博弈、双低策略与转债轮动选债框架