npx skills add ...
npx skills add tradermonty/claude-trading-skills --skill pair-trade-screener
Statistical arbitrage tool for identifying and analyzing pair trading opportunities. Detects cointegrated stock pairs within sectors, analyzes spread behavior, calculates z-scores, and provides entry/exit recommendations for market-neutral strategies. Use when user requests pair trading opportunities, statistical arbitrage screening, mean-reversion strategies, or market-neutral portfolio construction. Supports correlation analysis, cointegration testing, and spread backtesting.
npx skills add tradermonty/claude-trading-skills --skill pair-trade-screener
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:
Run the scripts from the repository root with the statistical dependency isolated to the command:
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:
Option C: Industry-Specific
Narrow focus to specific industry within sector:
Filtering Criteria:
Objective: Fetch price history for correlation and cointegration analysis.
Data Requirements:
FMP API Endpoint:
Data Validation:
Script Execution:
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 indicates the hedge ratio:
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:
Python Implementation:
Objective: Quantify current spread deviation from equilibrium.
Spread Calculation:
Two common methods:
Method 1: Price Difference (Additive)
Best for: Stocks with similar price levels
Method 2: Price Ratio (Multiplicative)
Best for: Stocks with different price levels, easier interpretation
Z-Score Calculation:
Measures how many standard deviations spread is from its mean:
Z-Score Interpretation:
Historical Spread Analysis:
Objective: Provide actionable trading signals with clear rules.
Entry Conditions:
Conservative Approach (Z ≥ ±2.0):
Aggressive Approach (Z ≥ ±1.5):
Exit Conditions:
Primary Exit: Mean Reversion (Z = 0)
Secondary Exit: Partial Profit Take
Stop Loss:
Time-Based Exit:
Objective: Determine dollar amounts for market-neutral exposure.
Market Neutral Sizing:
For a pair (Stock A, Stock B) with beta = β:
Equal Dollar Exposure:
Position Sizing Considerations:
Risk Metrics:
Objective: Create structured markdown report with findings and recommendations.
Report Sections:
Executive Summary
Cointegrated Pairs Table
Detailed Analysis (Top 10 Pairs)
Spread Charts (Text-Based)
Risk Warnings
File Naming Convention:
Example: pair_trade_analysis_Technology_2025-11-08.md
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:
Purpose: Screen for cointegrated pairs within a sector or custom list.
Usage:
Parameters:
--sector: Sector name (Technology, Financials, etc.)--symbols: Comma-separated list of tickers (alternative to sector)--min-correlation: Minimum correlation threshold (default: 0.70)--min-market-cap: Minimum market cap filter (default: $2B)--lookback-days: Historical data period (default: 730 days)--output: Output JSON file (default: pair_analysis.json)--api-key: FMP API key (or set FMP_API_KEY env var)Output:
Purpose: Analyze a specific pair's spread behavior and generate trading signals.
Usage:
Parameters:
--stock-a: First stock ticker--stock-b: Second stock ticker--lookback-days: Analysis period (default: 365)--entry-zscore: Z-score threshold for entry (default: 2.0)--exit-zscore: Z-score threshold for exit (default: 0.0)--api-key: FMP API keyOutput:
Comprehensive guide to statistical arbitrage and pair trading:
Deep dive into cointegration testing:
Sector Analyst Integration:
Technical Analyst Integration:
Backtest Expert Integration:
Market Environment Analysis Integration:
Portfolio Manager Integration:
statsmodels>=0.14,<0.15Use Case 1: Technology Sector Pairs
Use Case 2: Specific Pair Analysis
Use Case 3: 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:
Version: 1.0 Last Updated: 2025-11-08 Dependencies: Python 3.8+, pandas, numpy, scipy, statsmodels, requests
Example: ["AAPL", "MSFT", "GOOGL", "META", "NVDA"]GET /v3/historical-price-full/{symbol}?apikey=YOUR_API_KEYuv 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.jsonBeta = Covariance(A, B) / Variance(B)Half-Life = -log(2) / log(mean_reversion_coefficient)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.05Spread = Price_A - (Beta × Price_B)Spread = Price_A / Price_BZ-Score = (Current_Spread - Mean_Spread) / Std_Dev_SpreadLONG Signal:
- Z-score < -2.0 (spread 2+ std devs below mean)
- Spread is mean-reverting (cointegration p < 0.05)
- Half-life < 60 days
→ Action: Buy Stock A, Short Stock B (hedge ratio = beta)
SHORT Signal:
- Z-score > +2.0 (spread 2+ std devs above mean)
- Spread is mean-reverting (cointegration p < 0.05)
- Half-life < 60 days
→ Action: Short Stock A, Buy Stock B (hedge ratio = beta)Exit when spread returns to mean (z-score crosses 0)
→ Close both legs simultaneouslyExit 50% when z-score reaches ±1.0
Exit remaining 50% at z-score = 0Exit if z-score extends beyond ±3.0 (extreme divergence)
Risk: Possible structural break in relationshipExit after 90 days if no mean-reversion
Prevents holding broken pairs indefinitelyIf portfolio size = $10,000 allocated to this pair:
- Long $5,000 of Stock A
- Short $5,000 × β of Stock B
Example (β = 1.2):
- Long $5,000 Stock A
- Short $6,000 Stock B
→ Market neutral, beta = 0pair_trade_analysis_[SECTOR]_[YYYY-MM-DD].md# Sector-based screening
uv run --with 'statsmodels>=0.14,<0.15' python \
skills/pair-trade-screener/scripts/find_pairs.py \
--sector Technology \
--min-correlation 0.70 \
--output /tmp/pair-trade/technology.json
# Custom stock list
uv run --with 'statsmodels>=0.14,<0.15' python \
skills/pair-trade-screener/scripts/find_pairs.py \
--symbols AAPL,MSFT,GOOGL,META \
--min-correlation 0.75 \
--output /tmp/pair-trade/custom.json
# Full options
uv run --with 'statsmodels>=0.14,<0.15' python \
skills/pair-trade-screener/scripts/find_pairs.py \
--sector Financials \
--min-correlation 0.70 \
--min-market-cap 2000000000 \
--lookback-days 730 \
--output /tmp/pair-trade/financials.json[
{
"pair": "AAPL/MSFT",
"stock_a": "AAPL",
"stock_b": "MSFT",
"correlation": 0.87,
"beta": 1.15,
"cointegration_pvalue": 0.012,
"adf_statistic": -3.45,
"half_life_days": 42,
"current_zscore": -2.3,
"signal": "LONG",
"strength": "Strong"
}
]# Analyze specific pair
uv run --with 'statsmodels>=0.14,<0.15' python \
skills/pair-trade-screener/scripts/analyze_spread.py \
--stock-a AAPL \
--stock-b MSFT
# Custom lookback period
uv run --with 'statsmodels>=0.14,<0.15' python \
skills/pair-trade-screener/scripts/analyze_spread.py \
--stock-a JPM \
--stock-b BAC \
--lookback-days 365 \
--entry-zscore 2.0 \
--exit-zscore 0.5User: "Find pair trading opportunities in tech stocks"
Workflow:
1. Screen Technology sector for stocks with market cap > $10B
2. Calculate all pairwise correlations
3. Filter pairs with correlation ≥ 0.75
4. Run cointegration tests
5. Identify current z-score extremes (|z| > 2.0)
6. Generate top 10 pairs reportUser: "Analyze AAPL and MSFT as a pair trade"
Workflow:
1. Fetch 2-year price history for AAPL and MSFT
2. Calculate correlation and beta
3. Test for cointegration
4. Calculate current spread and z-score
5. Generate entry/exit recommendation
6. Provide position sizing guidanceUser: "Screen for pairs among regional banks"
Workflow:
1. Filter Financials sector for industry = "Regional Banks"
2. Exclude banks with <$5B market cap
3. Calculate pairwise statistics
4. Rank by cointegration strength
5. Focus on pairs with half-life < 45 days
6. Report top 5 mean-reverting pairs