Agent skill

Cointegration Analysis

by agiprolabs in agiprolabs/claude-trading-skills

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

MITAuto-check passedBusiness, Finance & HR

Install Cointegration Analysis

skills CLI
$ npx skills add agiprolabs/claude-trading-skills --skill cointegration-analysis -a claude-code

Project install by default; add -g for ~/.claude/skills/.

GitHub CLI
$ gh skill install agiprolabs/claude-trading-skills cointegration-analysis --agent claude-code

Project scope by default; add --scope user for a personal install. Needs GitHub CLI 2.90.0 or later (public preview).

Manual copy
$ git clone --depth 1 https://github.com/agiprolabs/claude-trading-skills.git skills-src && mkdir -p .claude/skills && cp -r skills-src/skills/cointegration-analysis .claude/skills/cointegration-analysis && rm -rf skills-src

Use ~/.claude/skills/ instead of .claude/skills for a personal install. The folder must contain SKILL.md.

Claude Code skills documentation · loads skills from .claude/skills/

Facts

Skill name
cointegration-analysis
GitHub stars
410
Token cost
~2.1k tokens
SKILL.md length
841 words
Files
5 (incl. scripts, references)
Skills in repo
68
Repo updated
First seen
Licence
MIT

At a glance

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

  • Works in 9 steps: Engle-Granger Two-Step → Johansen Test → Phillips-Ouliaris → …
  • Tasks that involve Trading and backtesting
  • SKILL.md covers What Is Cointegration?, Methods, Practical Workflow and Rolling Cointegration, plus 4 more sections
  • Runs Python scripts from its folder

What it does

Cointegration Analysis is an agent skill from agiprolabs/claude-trading-skills. Cointegration testing for pairs trading using Engle-Granger, Johansen, and rolling stability analysis

Its SKILL.md is about 2.1k tokens, which your agent loads only when the skill is triggered. The skill folder holds 6 other files, including scripts and reference files (for example `references/methodology.md`, `references/pairs_trading.md` and `scripts/pairs_backtest.py`).

It sits in Business, Finance & HR, covering Trading and backtesting. The repository describes itself as: 68 trading, DeFi, and quantitative finance Agent Skills. Works with Claude Code, Cursor, Codex, Gemini CLI, and 30+ other tools. The licence is MIT.

When your agent uses it

  • Tasks that involve Trading and backtesting

Example prompts

  • “/cointegration-analysis”

Requirements

  • Python 3

Workflow steps

9 steps, taken from the step headings in SKILL.md.

  1. Engle-Granger Two-Step
  2. Johansen Test
  3. Phillips-Ouliaris
  4. Screen Pairs by Correlation
  5. Test Cointegration
  6. Estimate Hedge Ratio
  7. Compute Spread
  8. Test Spread for Mean Reversion
  9. Trade the Spread

What it can do on your machine

Read from SKILL.md and the folder at commit 981e1d7. It shows what the files ask for, not the result of running them.

  • Tool permissions

    Pre-approves nothing: there is no allowed-tools line, so your agent's usual permission prompts apply.

    From allowed-tools in the SKILL.md frontmatter.

  • Runs code

    Ships 2 files in scripts/ (Python), which the agent can run.

    From the folder's file list and the shell code blocks in SKILL.md.

  • Network

    No URLs in SKILL.md.

    From URLs in SKILL.md, links to its own repository left out.

  • Credentials

    Names no API keys, tokens, secrets or passwords.

    From names ending in _API_KEY, _TOKEN, _SECRET, _KEY or _PASSWORD in SKILL.md.

Context cost

Cointegration Analysis loads about 2.1k tokens when it runs, and up to ~5.8k if it reads all its reference files. Until then it costs about 31 tokens; SKILL.md has 841 words of instructions outside code blocks.

Always · name and description, kept in context so the agent knows when to use it
~31
When it runs · the whole SKILL.md, loaded when a task matches
~2.1k
With references · SKILL.md plus every file in references/, read only if the agent opens them
~5.8k

Estimates: characters ÷ 4, the usual rule of thumb; real counts depend on the model's tokenizer. Scripts and assets cost tokens only if the agent reads them.

Safety

Auto-check passed

The automated check found no risky patterns in SKILL.md.

Automated static check — not a guarantee. Review scripts before installing. It scans the text of SKILL.md for risky patterns (piping downloads into a shell, reading credential files, hidden Unicode, destructive commands); the scripts in this folder are not scanned.

SKILL.md

The full file from agiprolabs/claude-trading-skills at commit 981e1d7, republished under its MIT licence (© agiprolabs). 841 words, ~2,124 tokens.

Download SKILL.mdSave it as .claude/skills/cointegration-analysis/SKILL.md (or your agent's skills folder). This skill also uses 4 other files; get the full folder from GitHub.
name
cointegration-analysis
description
Cointegration testing for pairs trading using Engle-Granger, Johansen, and rolling stability analysis

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
PropertyCorrelationCointegration
MeasuresShort-term co-movementLong-run equilibrium
StationarityRequires stationary returnsWorks with non-stationary prices
Time horizonCan change rapidlyStable over months/years
Trading useMomentum/trend signalsMean-reversion pairs trades
Failure modeBreaks in regime changesBreaks 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 < 0.05) → Y and X are cointegrated
  • β is the hedge ratio for the pairs trade
  • α is the long-run mean of the spread

Important: Engle-Granger critical values differ from standard ADF critical values. For n=2 series: 1% = -3.90, 5% = -3.34, 10% = -3.04.

Asymmetry warning: Testing YX can give a different result than XY. Always test both directions and use the stronger result.

python
from scipy import stats
import numpy as np
from statsmodels.tsa.stattools import adfuller

# Step 1: OLS regression
slope, intercept, _, _, _ = stats.linregress(x_prices, y_prices)
hedge_ratio = slope

# Step 2: Test residuals
residuals = y_prices - hedge_ratio * x_prices - intercept
adf_stat, p_value, _, _, crit_values, _ = adfuller(residuals, maxlag=None, autolag="AIC")

cointegrated = p_value < 0.05
2. Johansen Test

Tests multiple series simultaneously and returns the number of cointegrating relationships. More powerful than Engle-Granger for >2 series.

  • Based on a VAR model: ΔY_t = Π·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
python
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.

python
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.05

Practical Workflow

Step 1: Screen Pairs by Correlation

Pre-filter using Pearson correlation > 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.05 threshold.

Step 3: Estimate Hedge Ratio

Use OLS for simplicity. For production, consider Total Least Squares or Dynamic OLS (see references/methodology.md).

Step 4: Compute Spread
python
spread = y_prices - hedge_ratio * x_prices - intercept
z_score = (spread - spread.mean()) / spread.std()
Step 5: Test Spread for Mean Reversion
  • ADF test: p < 0.05 confirms stationarity
  • Hurst exponent: H < 0.5 indicates mean reversion (H ≈ 0.5 = random walk)
  • Half-life: λ from AR(1) on spread; half-life = -ln(2)/ln(λ)
    • Viable pairs: half-life between 5 and 60 days
Step 6: Trade the Spread

If the spread is mean-reverting, it is a viable pairs trade candidate. See references/pairs_trading.md for entry/exit rules and risk management.

Rolling Cointegration

Cointegration relationships can break down over time due to structural changes, regime shifts, or evolving market dynamics.

Show full SKILL.md (338 more words)Show less
Rolling Window Approach

Test cointegration on rolling 60–90 day windows:

python
window = 60
rolling_pvalues = []
rolling_hedges = []

for i in range(window, len(prices)):
    y_win = y_prices[i - window:i]
    x_win = x_prices[i - window:i]
    _, p_val, _ = coint(y_win, x_win)
    slope, intercept, _, _, _ = stats.linregress(x_win, y_win)
    rolling_pvalues.append(p_val)
    rolling_hedges.append(slope)
Monitoring Signals
SignalHealthyWarningStop Trading
Rolling p-value< 0.050.05–0.10> 0.10
Hedge ratio drift< 10% change10–25% change> 25% change
Spread half-life5–60 days60–120 days> 120 days or < 5

Crypto Pairs Candidates

Layer-1 Correlation
  • SOL vs ETH — L1 sector beta, often cointegrated during trending markets
  • SOL vs AVAX — alternative L1 correlation
Stablecoins
  • USDC vs USDT — should be perfectly cointegrated (peg arbitrage)
  • Useful as a sanity check for your cointegration pipeline
Liquid Staking Derivatives
  • mSOL vs jitoSOL — both track SOL staking yield
  • stSOL vs mSOL — Lido vs Marinade staking
Same-Sector Tokens
  • DEX tokens: RAY vs ORCA
  • Lending tokens: cross-protocol comparison
  • Meme tokens: rarely cointegrated, high risk

Common Pitfalls

  1. Spurious cointegration — Two trending series (both up in a bull market) may appear cointegrated. Always test on sufficient data (>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

© agiprolabs, MIT. Rendered from Markdown: HTML in the file is shown as text, images as links, and headings moved down two levels. Raw file

Files

SKILL.md and 4 other files (scripts, references) in skills/cointegration-analysis of agiprolabs/claude-trading-skills.

  • SKILL.md
  • references/methodology.md
  • references/pairs_trading.md
  • scripts/pairs_backtest.py
  • scripts/test_cointegration.py

Open the folder on GitHubat commit 981e1d7

Compare with similar skills

Cointegration Analysis next to the 5 skills that share the most tags, products or categories with it. Stars are the repository's; “used in” counts other GitHub owners with a copy.

Cointegration Analysis compared with similar skills
SkillStarsUsed inTokensAuto-checkLicenceRepo updated
Cointegration Analysis this skillagiprolabs/claude-trading-skills410—~2.1kAutomated safety check: PassMIT
Tushare Datazillionare/zillionare3192 repos~2.3kAutomated safety check: PassNone
Tradingview MCPatilaahmettaner/tradingview-mcp5k—~1.3kAutomated safety check: PassMIT
Digital Oraclekomako-workshop/digital-oracle870—~5.9kAutomated safety check: PassMIT
Fintoolsecond-state/fintool3161 repos~5.9kAutomated safety check: PassNone
Polyclawchainstacklabs/polyclaw3601 repos~2kAutomated safety check: PassApache-2.0

Similar skills

  • Tushare Data

    zillionare/zillionare

    面向中文自然语言的 Tushare 数据研究技能。用于把“看看这只股票最近怎么样”“帮我查财报趋势”“最近哪个板块最强”“北向资金在买什么”“给我导出一份行情数据”这类请求,转成可执行的数据获取、清洗、对比、筛选、导出与简要分析流程。适用于 A 股、指数、ETF/基金、财务、估值、资金流、公告新闻、板块概念与宏观数据等研究场景。

    319 GitHub starsUsed in 2 repos~2.3k tokens
    Business, Finance & HRAuto-check passed
  • Tradingview MCP

    atilaahmettaner/tradingview-mcp

    AI Trading Intelligence — live prices, 30+ technical indicators, backtesting (6 strategies), walk-forward overfitting detection, trade logs, equity curves, licensed news sentiment (Marketaux), and…

    5k GitHub stars~1.3k tokensUpdated yesterday
    Business, Finance & HRAuto-check passed
  • Digital Oracle

    komako-workshop/digital-oracle

    Answer prediction questions using market trading data, not opinions.

    870 GitHub stars~5.9k tokensUpdated 2 mo ago
    Business, Finance & HRAuto-check passed
  • Fintool

    second-state/fintool

    Financial trading CLIs — spot and perp trading on Hyperliquid, Binance, Coinbase, OKX.

    316 GitHub starsUsed in 1 repo~5.9k tokens
    Business, Finance & HRAuto-check passed
  • Polyclaw

    chainstacklabs/polyclaw

    Trade on Polymarket via split + CLOB execution. An agent skill from chainstacklabs/polyclaw.

    360 GitHub starsUsed in 1 repo~2k tokens
    Business, Finance & HRAuto-check passed
  • Markdown

    facioquo/stock-indicators-dotnet

    Format and lint Markdown in this repository against GitHub Flavored Markdown and its markdownlint-cli2 configuration — headers, lists, code fences, callouts (VitePress containers on docs-site pages…

    1.2k GitHub stars~812 tokensUpdated today
    Business, Finance & HRAuto-check passed

More from agiprolabs/claude-trading-skills

All 68 skills in this repo
  • Backtrader

    agiprolabs/claude-trading-skills

    Event-driven backtesting with bar-by-bar execution, complex order types, multiple analyzers, and custom indicators

    410 GitHub stars~2.4k tokensUpdated 1 mo ago
    Auto-check passed
  • Birdeye API

    agiprolabs/claude-trading-skills

    Solana token market data via Birdeye — prices, OHLCV, trades, token metadata, security checks, and trader activity

    410 GitHub stars~1.8k tokensUpdated 1 mo ago
    Auto-check passed
  • Coingecko API

    agiprolabs/claude-trading-skills

    Broad crypto market data from CoinGecko covering 13,000+ tokens.

    410 GitHub stars~1.6k tokensUpdated 1 mo ago
    Auto-check passed
  • Copy Trading

    agiprolabs/claude-trading-skills

    Wallet evaluation, monitoring, and copy-trade strategy design for Solana DEX trading

    410 GitHub stars~2.4k tokensUpdated 1 mo ago
    Auto-check passed
  • Correlation Analysis

    agiprolabs/claude-trading-skills

    Cross-asset correlation analysis including rolling correlation, hierarchical clustering, tail dependence, and regime-dependent correlation

    410 GitHub stars~2.4k tokensUpdated 1 mo ago
    Auto-check passed
  • Cost Basis Engine

    agiprolabs/claude-trading-skills

    Multi-method cost basis computation including specific identification, FIFO, LIFO, HIFO, and proportional average cost with partial sell handling

    410 GitHub stars~3.1k tokensUpdated 1 mo ago
    Auto-check passed

Questions about Cointegration Analysis

What does Cointegration Analysis do?

Cointegration testing for pairs trading using Engle-Granger, Johansen, and rolling stability analysis. Cointegration Analysis is an agent skill from agiprolabs/claude-trading-skills.

When should I use Cointegration Analysis?

Cointegration Analysis fits situations like: tasks that involve Trading and backtesting.

How do I install Cointegration Analysis in Claude Code?

Run `npx skills add agiprolabs/claude-trading-skills --skill cointegration-analysis -a claude-code`. Or copy the skill folder (skills/cointegration-analysis in agiprolabs/claude-trading-skills) into .claude/skills/cointegration-analysis in your project. Claude Code loads it when a task matches its description.

How do I install Cointegration Analysis in Codex?

Run `npx skills add agiprolabs/claude-trading-skills --skill cointegration-analysis -a codex`. Or copy the skill folder (skills/cointegration-analysis in agiprolabs/claude-trading-skills) into .agents/skills/cointegration-analysis in your project. Codex loads it when a task matches its description.

Can I use Cointegration Analysis in Cursor, Gemini CLI or GitHub Copilot?

Cursor, Gemini CLI, GitHub Copilot and OpenCode also load SKILL.md folders. With the skills CLI, run `npx skills add agiprolabs/claude-trading-skills --skill cointegration-analysis -a cursor` (or -a gemini-cli, github-copilot or opencode for the others). To copy it by hand, put the folder in .cursor/skills/cointegration-analysis, .gemini/skills/cointegration-analysis, .github/skills/cointegration-analysis and .opencode/skills/cointegration-analysis in your project.

What does Cointegration Analysis need to run?

Going by SKILL.md and its folder, Cointegration Analysis needs Python for the scripts in its folder. Our summary lists: Python 3.

Does Cointegration Analysis access the network?

SKILL.md contains no URLs. Any network use would come from the scripts or tools the agent runs. This is read from the text; nothing was executed.

Is Cointegration Analysis safe to install?

Our automated static check of SKILL.md found no risky patterns, such as piping downloads into a shell, reading credential files or hidden Unicode. It is not a guarantee. The check reads SKILL.md only: the scripts in the folder are not scanned, so read them before running anything.

What licence does Cointegration Analysis use?

Cointegration Analysis is published under the MIT licence (the repository's licence). It allows redistribution, so the full SKILL.md is shown on this page.

How many tokens does Cointegration Analysis use?

About 2.1k tokens (SKILL.md is roughly 8.5k characters). Agents keep only the skill's name and description in context until a task matches; then they load SKILL.md in full. Its references folder adds about 3.7k tokens, read only when the agent opens those files.

What are the alternatives to Cointegration Analysis?

Skills that share tags, products or a category with Cointegration Analysis: Tushare Data (zillionare/zillionare, 319 stars), Tradingview MCP (atilaahmettaner/tradingview-mcp, 5k stars), Digital Oracle (komako-workshop/digital-oracle, 870 stars) and Fintool (second-state/fintool, 316 stars). The comparison table on this page puts their stars, adoption, token cost, safety result and licence side by side.

Who maintains Cointegration Analysis?

agiprolabs (a GitHub user) maintains it in agiprolabs/claude-trading-skills, which has 410 GitHub stars. The repository holds 68 skills in this directory. The repository was last updated on September 3, 2026.

Source: agiprolabs/claude-trading-skills on GitHub. Facts on this page come from the repository at the commit we read; the author's words are quoted as theirs.