Identifies cointegrated stock pairs within sectors using correlation analysis, cointegration testing, and z-score calculations for market-neutral statistical arbitrage strategies.
Ships in tradermonty-claude-trading-skills. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them; scripts run unread.
This skill identifies and analyzes statistical arbitrage opportunities through pair trading. Pair trading is a market-neutral strategy that profits from the relative price movements of two correlated securities, regardless of overall market direction. The skill uses rigorous statistical methods including correlation analysis and cointegration testing to find robust trading pairs.
Core Methodology:
Key Advantages:
Use this skill when:
Example user requests:
statsmodels>=0.14,<0.15 for ADF and autoregression calculationsSet the API key without placing it on the command line or in a committed file:
export FMP_API_KEY="<fmp-api-key>"
Run the scripts from the repository root with the statistical dependency isolated to the command:
uv run --with 'statsmodels>=0.14,<0.15' python \
skills/pair-trade-screener/scripts/find_pairs.py \
--symbols AAPL,MSFT \
--output /tmp/pair-trade/pairs.json
Objective: Establish the pool of stocks to analyze for pair relationships.
Option A: Sector-Based Screening (Recommended)
Select a specific sector to screen:
Option B: Custom Stock List
User provides specific tickers to analyze:
Example: ["AAPL", "MSFT", "GOOGL", "META", "NVDA"]
Option C: Industry-Specific
Narrow focus to specific industry within sector:
Filtering Criteria:
Objective: Fetch price history for correlation and cointegration analysis.
Data Requirements:
adjClose from /stable/historical-price-eod/dividend-adjusted when available. The fallback full endpoint serves unadjusted close; the run then warns per symbol and records price_basis: closeFMP API Endpoint:
GET /stable/historical-price-eod/dividend-adjusted?symbol={symbol} # preferred, adjClose
GET /stable/historical-price-eod/full?symbol={symbol} # fallback, unadjusted close
Header: apikey: <FMP_API_KEY>
Data Validation:
Script Execution:
uv run --with 'statsmodels>=0.14,<0.15' python \
skills/pair-trade-screener/scripts/find_pairs.py \
--sector Technology \
--lookback-days 730 \
--output /tmp/pair-trade/technology.json
Objective: Identify candidate pairs with strong linear relationships.
Correlation Analysis:
For each pair of stocks (i, j) in the universe:
Correlation Interpretation:
Beta Calculation:
For each candidate pair (Stock A, Stock B):
Beta = Covariance(A, B) / Variance(B)
Beta indicates the share hedge ratio from price-level OLS (Price_A = alpha + Beta × Price_B):
Beta × Price_B / Price_A)Beta × Price_B / Price_A)Correlation Stability Check:
Objective: Statistically validate long-term equilibrium relationship.
Why Cointegration Matters:
Augmented Dickey-Fuller (ADF) Test:
For each correlated pair:
Spread = Price_A - (Beta × Price_B)Cointegration Interpretation:
Half-Life Calculation:
Estimate mean-reversion speed:
Half-Life = -log(2) / log(mean_reversion_coefficient)
Python Implementation:
from statsmodels.tsa.stattools import adfuller
# Calculate spread
spread = price_a - (beta * price_b)
# ADF test
result = adfuller(spread)
adf_stat = result[0]
p_value = result[1]
# Interpret
is_cointegrated = p_value < 0.05
Objective: Quantify current spread deviation from equilibrium.
Spread Calculation:
Two common methods:
Method 1: Price Difference (Additive)
Spread = Price_A - (Beta × Price_B)
Best for: Stocks with similar price levels
Method 2: Price Ratio (Multiplicative)
Spread = Price_A / Price_B
Best for: Stocks with different price levels, easier interpretation
Z-Score Calculation:
Measures how many standard deviations spread is from its mean:
Z-Score = (Current_Spread - Mean_Spread) / Std_Dev_Spread
Z-Score Interpretation:
Historical Spread Analysis:
Objective: Provide actionable trading signals with clear rules.
Read references/trade_rules_and_reporting.md (section "Step 6 detail: Entry and Exit Conditions") when generating entry and exit recommendations. It holds the conservative and aggressive entry rules, mean-reversion, partial-profit, stop-loss and time-based exits.
Objective: Determine dollar amounts for market-neutral exposure.
Read references/trade_rules_and_reporting.md (section "Step 7 detail: Position Sizing and Risk Management") when sizing a pair. It holds market-neutral sizing, position sizing considerations and risk metrics.
Objective: Create structured markdown report with findings and recommendations.
Read references/trade_rules_and_reporting.md (section "Step 8 detail: Pair Analysis Report") when writing the report. It holds the report sections, a markdown template and the file naming convention.
find_pairs.py creates the requested parent directory and writes one JSON object
with metadata and pairs keys. Each pair includes the correlation, hedge ratio,
ADF result, half-life, current z-score, signal, and generation timestamp. Progress
and a ranked summary are written to stdout. File-system errors produce a concise
stderr message and a nonzero exit.
analyze_spread.py writes a single-pair statistical report to stdout and does not
create files. Both commands reject invalid or non-finite thresholds, insufficient
lookback windows, and duplicate symbols before making API requests. Missing
statsmodels produces an install command on stderr without a traceback.
Minimum Requirements for Valid Pair:
Red Flags (Exclude Pair):
Transaction Costs:
Short Selling:
Execution:
Read references/script_usage.md for full CLI usage, options and output formats of find_pairs.py and analyze_spread.py.
Comprehensive guide to statistical arbitrage and pair trading:
Deep dive into cointegration testing:
Read references/skill_integrations.md for how to combine this skill with Sector Analyst, Technical Analyst, Backtest Expert, Market Environment Analysis and Portfolio Manager.
statsmodels>=0.14,<0.15Read references/common_use_cases.md for three worked use cases: technology sector pairs, a specific pair, regional bank pairs.
Problem: No cointegrated pairs found
Solutions:
Problem: All z-scores near zero (no trade signals)
Solutions:
Problem: Pair correlation broke down
Solutions:
/stable/company-screener only. Historical prices try the dividend-adjusted stable endpoint first, then the canonical stable full and v3 fallback.adjClose is used when supplied; otherwise raw close, which is not dividend-adjusted. Each symbol's basis is recorded as price_basis (dividend_adjusted, adj_close or close) in the find_pairs JSON metadata and printed by analyze_spread, and a stderr warning names every symbol on raw close. Mixed bases in one run warn separately.Version: 1.0 Last Updated: 2025-11-08 Dependencies: Python 3.8+, pandas, numpy, scipy, statsmodels, requests
README.md (opens in a new tab)references/cointegration_guide.md (opens in a new tab)references/common_use_cases.md (opens in a new tab)references/methodology.md (opens in a new tab)references/script_usage.md (opens in a new tab)references/skill_integrations.md (opens in a new tab)references/trade_rules_and_reporting.md (opens in a new tab)requirements.txt (opens in a new tab)scripts/analyze_spread.py (opens in a new tab)scripts/find_pairs.py (opens in a new tab)scripts/fmp_client.py (opens in a new tab)scripts/pair_fmp_client.py (opens in a new tab)scripts/statsmodels_support.py (opens in a new tab)scripts/tests/conftest.py (opens in a new tab)scripts/tests/test_find_pairs_screener.py (opens in a new tab)scripts/tests/test_generated_transport.py (opens in a new tab)scripts/tests/test_pair_resilience.py (opens in a new tab)scripts/tests/test_pair_statistics_and_cli.py (opens in a new tab)scripts/tests/test_pair_trade_coverage.py (opens in a new tab)scripts/tests/test_report_threshold_and_share_rounding.py (opens in a new tab)What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
/tradermonty-claude-trading-skills:pair-trade-screenerfrom tradermonty-claude-trading-skills
tradermonty-claude-trading-skills@cascade-business-ops is listed by joshuarweaver/cascade-business-ops — review the source before installing
npx claudepluginhub joshuarweaver/cascade-business-ops --plugin tradermonty-claude-trading-skills74 skills in this plugin
/backtest-expertExpert guidance for systematic backtesting of trading strategies. Use when developing, testing, stress-testing, or validating quantitative trading strategies. Covers "beating ideas to death" methodology, parameter robustness testing, slippage modeling, bias prevention, and interpreting backtest results. Applicable when user asks about backtesting, strategy validation, robustness testing, avoiding overfitting, or systematic trading development./breadth-chart-analystThis skill should be used when analyzing market breadth charts, specifically the S&P 500 Breadth Index (200-Day MA based) and the US Stock Market Uptrend Stock Ratio charts. Use this skill when the user provides breadth chart images for analysis, requests market breadth assessment, positioning strategy recommendations, or wants to understand medium-term strategic and short-term tactical market outlook based on breadth indicators. Also works WITHOUT chart images by fetching CSV data directly from public sources. All analysis and output are conducted in English./breakout-trade-plannerGenerate Minervini-style breakout trade plans from VCP screener output with worst-case risk calculation, portfolio heat management, and Alpaca-compatible order templates (stop-limit bracket for pre-placement, limit bracket for post-confirmation). Use when user has VCP screener results and wants actionable trade plans with entry/stop/target levels and position sizing.Other plugins' skills for the same job