AgentStack
Browse Sign in
Browse Why AgentStack Sell Docs
Sign in
SKILL verified MIT Self-run

Cointegration Analysis

skill-agiprolabs-claude-trading-skills-cointegration-analysis · by agiprolabs

Cointegration testing for pairs trading using Engle-Granger, Johansen, and rolling stability analysis

No reviews yet
0 installs
32 views
0.0% view→install

Install

$ agentstack add skill-agiprolabs-claude-trading-skills-cointegration-analysis

✓ scanned · ✓ verified, works with Claude Code, Cursor, and more.

Security review

✓ Passed

No issues found. Passed automated security review. · v0.1.0 How review works →

  • Prompt-injection patterns
  • Secret / credential exfiltration
  • Dangerous shell & filesystem operations
  • Untrusted network calls
  • Known-malicious package signatures

What it can access

  • Network access No
  • Filesystem access No
  • Shell / process execution No
  • Environment & secrets No
  • Dynamic code execution No

From automated source analysis of v0.1.0. “Used” means the capability is present in the source — more access means more to trust, not that it’s unsafe.

View the full security report →

Verified badge

Passed review? Show it. Paste this badge into your README, it links to the public security report.

AgentStack Verified badge Links to your public security report.
[![AgentStack Verified](https://agentstack.voostack.com/badges/verified.svg)](https://agentstack.voostack.com/security/report/skill-agiprolabs-claude-trading-skills-cointegration-analysis)

Reliability & compatibility

Security review passed
0 installs to date
no reviews yet
3mo ago

Declared compatibility

Claude CodeClaude Desktop

Compatibility is declared by the source manifest. End-to-end runtime verification is coming, see below.

Preview Execution monitoring

We're building live execution health for every listing: tool-call success rate, median latency, uptime, and last-checked timestamps, measured, not self-reported. It isn't live yet, so we don't show numbers we can't stand behind.

How agent discovery & health will work →
Are you the author of Cointegration Analysis? Claim this listing to set pricing, connect Stripe payouts, and keep 70% of every sale.
Sign up to claim

About

Cointegration Analysis

Cointegration testing identifies pairs of assets that share a long-run equilibrium relationship, enabling statistical arbitrage and pairs trading strategies.

What Is Cointegration?

Two price series are cointegrated when they are individually non-stationary (random walks) but a linear combination of them is stationary (mean-reverting). Intuitively, the prices may wander apart temporarily but are pulled back to an equilibrium spread over time.

Cointegration vs Correlation

| Property | Correlation | Cointegration | |---|---|---| | Measures | Short-term co-movement | Long-run equilibrium | | Stationarity | Requires stationary returns | Works with non-stationary prices | | Time horizon | Can change rapidly | Stable over months/years | | Trading use | Momentum/trend signals | Mean-reversion pairs trades | | Failure mode | Breaks in regime changes | Breaks on structural shifts |

Two assets can be highly correlated but not cointegrated (e.g., two unrelated uptrends). Conversely, cointegrated assets may have low short-term correlation during temporary divergences — which is exactly when pairs trades are entered.

Why It Matters

  • Pairs trading: Long the underperformer, short the outperformer, profit on convergence
  • Statistical arbitrage: Systematic mean-reversion on spread z-scores
  • Spread trading: Trade the spread directly as a synthetic instrument
  • Risk hedging: Cointegrated hedge ratios minimize tracking error over time

Methods

1. Engle-Granger Two-Step

The most common approach for two series.

Step 1 — Regress Y on X using OLS:

Y_t = α + β * X_t + ε_t

Step 2 — Test the residuals ε_t for stationarity using the ADF test.

  • If residuals are stationary (p 2 series.
  • Based on a VAR model: ΔYt = Π·Y{t-1} + Σ Γi·ΔY{t-i} + ε_t
  • Tests the rank of the Π matrix
  • Uses trace test and maximum eigenvalue test
  • Returns: number of cointegrating vectors and the vectors themselves
from statsmodels.tsa.vector_ar.vecm import coint_johansen

# data: T×N array of price series
result = coint_johansen(data, det_order=0, k_ar_diff=1)

# Trace statistic vs critical values (90%, 95%, 99%)
trace_stats = result.lr1          # Trace statistics
trace_crit = result.cvt           # Critical values
max_eigen_stats = result.lr2      # Max eigenvalue statistics
max_eigen_crit = result.cvm       # Critical values

# Cointegrating vectors
coint_vectors = result.evec

3. Phillips-Ouliaris

Similar to Engle-Granger but uses Phillips-Perron style test statistics instead of ADF. More robust to heteroskedasticity and serial correlation in the residuals. Available via statsmodels.tsa.stattools.coint.

from statsmodels.tsa.stattools import coint

# Returns: test statistic, p-value, critical values
t_stat, p_value, crit_values = coint(y_prices, x_prices)
cointegrated = p_value  0.7 to reduce the number of
cointegration tests (which are more expensive).

### Step 2: Test Cointegration

Run Engle-Granger in both directions. Use p  0.10 |
| Hedge ratio drift |  25% change |
| Spread half-life | 5–60 days | 60–120 days | > 120 days or 200 observations) and
   check out-of-sample stability.

2. **Structural breaks** — A fundamental change (protocol upgrade, tokenomics
   change) can permanently break cointegration. Monitor rolling p-values.

3. **Look-ahead bias** — Estimating the hedge ratio on the full sample and then
   backtesting on the same sample inflates results. Always use walk-forward
   estimation.

4. **Too-short sample** — Cointegration tests need >100 observations minimum,
   ideally >200, to have reasonable power.

5. **Ignoring transaction costs** — Pairs trades involve 4 transactions per
   round trip. At 0.3% per leg, that is 1.2% in costs that the spread must
   overcome.

6. **Asymmetric cointegration** — The relationship may only hold in one
   direction or one regime. Consider threshold cointegration models for
   production use.

## Integration with Other Skills

- **`correlation-analysis`** — Pre-screening pairs by correlation before cointegration testing
- **`mean-reversion`** — Trading the cointegrated spread using mean-reversion entry/exit rules
- **`vectorbt`** — Backtesting pairs strategies with walk-forward validation
- **`regime-detection`** — Identifying when cointegration regimes shift
- **`volatility-modeling`** — Spread volatility forecasting for dynamic position sizing

## Files

### References
- `references/methodology.md` — Engle-Granger details, Johansen derivation, hedge ratio estimation methods, spread construction
- `references/pairs_trading.md` — Entry/exit rules, risk management, performance metrics, crypto-specific considerations

### Scripts
- `scripts/test_cointegration.py` — Full cointegration test pipeline with ADF, Hurst, half-life, rolling stability, and demo mode
- `scripts/pairs_backtest.py` — Walk-forward pairs trading backtest with synthetic data and performance reporting

## Source & license

This open-source skill is cataloged on AgentStack and links to its original source — we do not rehost the code.

- **Author:** [agiprolabs](https://github.com/agiprolabs)
- **Source:** [agiprolabs/claude-trading-skills](https://github.com/agiprolabs/claude-trading-skills)
- **License:** MIT

Install and usage instructions live in the source repository linked above.

Reviews

No reviews yet, be the first.

Versions

  • v0.1.0 Imported from the upstream source.