pair-trade-screener
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChinesePair Trade Screener
配对交易筛选工具
Overview
概述
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:
- Identify pairs of stocks with high correlation and similar sector/industry exposure
- Test for cointegration (long-term statistical relationship)
- Calculate spread z-scores to identify mean-reversion opportunities
- Generate entry/exit signals based on statistical thresholds
- Provide position sizing for market-neutral exposure
Key Advantages:
- Market-neutral: Profits in up, down, or sideways markets
- Risk management: Limited exposure to broad market movements
- Statistical foundation: Data-driven, not discretionary
- Diversification: Uncorrelated to traditional long-only strategies
本工具通过配对交易识别和分析统计套利机会。配对交易是一种市场中性策略,通过两种相关证券的相对价格变动获利,不受整体市场走势的影响。本工具采用严谨的统计方法,包括相关性分析和cointegration(协整)检验,以寻找可靠的交易对。
核心方法:
- 识别具有高相关性且板块/行业属性相似的股票对
- 检验cointegration(长期统计关系)
- 计算价差z-score以识别均值回归机会
- 根据统计阈值生成进出仓信号
- 提供市场中性敞口的仓位配置建议
主要优势:
- 市场中性:在上涨、下跌或横盘市场中均可获利
- 风险管理:降低对整体市场波动的敞口
- 统计基础:基于数据驱动,而非主观判断
- 分散化:与传统的单边多头策略不相关
When to Use This Skill
适用场景
Use this skill when:
- User asks for "pair trading opportunities"
- User wants "market-neutral strategies"
- User requests "statistical arbitrage screening"
- User asks "which stocks move together?"
- User wants to hedge sector exposure
- User requests mean-reversion trade ideas
- User asks about relative value trading
Example user requests:
- "Find pair trading opportunities in the tech sector"
- "Which stocks are cointegrated?"
- "Screen for statistical arbitrage opportunities"
- "Find mean-reversion pairs"
- "What are good market-neutral trades right now?"
在以下场景中使用本工具:
- 用户询问“配对交易机会”
- 用户需要“市场中性策略”
- 用户请求“统计套利筛选”
- 用户询问“哪些股票走势联动?”
- 用户希望对冲板块敞口
- 用户寻求均值回归交易思路
- 用户询问相对价值交易
示例用户请求:
- “在科技板块寻找配对交易机会”
- “哪些股票存在协整关系?”
- “筛选统计套利机会”
- “寻找均值回归配对标的”
- “当前有哪些优质的市场中性交易?”
Analysis Workflow
分析流程
Step 1: Define Pair Universe
步骤1:定义配对标的池
Objective: Establish the pool of stocks to analyze for pair relationships.
Option A: Sector-Based Screening (Recommended)
Select a specific sector to screen:
- Technology
- Financials
- Healthcare
- Consumer Discretionary
- Industrials
- Energy
- Materials
- Consumer Staples
- Utilities
- Real Estate
- Communication Services
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:
- Example: "Software" within Technology sector
- Example: "Regional Banks" within Financials
Filtering Criteria:
- Minimum market cap: $2B (mid-cap and above)
- Minimum average volume: 1M shares/day (liquidity requirement)
- Active trading: No delisted or inactive stocks
- Same exchange preference: Avoid cross-exchange complications
目标: 确定用于分析配对关系的股票池。
选项A:基于板块的筛选(推荐)
选择特定板块进行筛选:
- 科技
- 金融
- 医疗健康
- 非必需消费品
- 工业
- 能源
- 原材料
- 必需消费品
- 公用事业
- 房地产
- 通信服务
选项B:自定义股票列表
用户提供特定股票代码进行分析:
示例: ["AAPL", "MSFT", "GOOGL", "META", "NVDA"]选项C:基于行业的筛选
将范围缩小至板块内的特定行业:
- 示例:科技板块内的“软件”行业
- 示例:金融板块内的“区域银行”行业
筛选标准:
- 最低市值:20亿美元(中型股及以上)
- 最低日均成交量:100万股(流动性要求)
- 交易活跃:排除已退市或不活跃的股票
- 优先同交易所:避免跨交易所的复杂性
Step 2: Retrieve Historical Price Data
步骤2:获取历史价格数据
Objective: Fetch price history for correlation and cointegration analysis.
Data Requirements:
- Timeframe: 2 years (minimum 252 trading days)
- Frequency: Daily closing prices
- Adjustments: Adjusted for splits and dividends
- Clean data: No gaps or missing values
FMP API Endpoint:
GET /v3/historical-price-full/{symbol}?apikey=YOUR_API_KEYData Validation:
- Verify consistent date ranges across all symbols
- Remove stocks with >10% missing data
- Fill minor gaps with forward-fill method
- Log data quality issues
Script Execution:
bash
python scripts/fetch_price_data.py --sector Technology --lookback 730目标: 获取用于相关性和协整分析的历史价格数据。
数据要求:
- 时间范围:2年(至少252个交易日)
- 频率:每日收盘价
- 调整:已针对拆股和分红进行调整
- 数据清洁:无缺口或缺失值
FMP API端点:
GET /v3/historical-price-full/{symbol}?apikey=YOUR_API_KEY数据验证:
- 验证所有标的的日期范围一致
- 移除缺失数据超过10%的股票
- 用前向填充法填补小缺口
- 记录数据质量问题
脚本执行:
bash
python scripts/fetch_price_data.py --sector Technology --lookback 730Step 3: Calculate Correlation and Beta
步骤3:计算相关性和Beta值
Objective: Identify candidate pairs with strong linear relationships.
Correlation Analysis:
For each pair of stocks (i, j) in the universe:
- Calculate Pearson correlation coefficient (ρ)
- Calculate rolling correlation (90-day window) for stability check
- Filter pairs with ρ >= 0.70 (strong positive correlation)
Correlation Interpretation:
- ρ >= 0.90: Very strong correlation (best candidates)
- ρ 0.70-0.90: Strong correlation (good candidates)
- ρ 0.50-0.70: Moderate correlation (marginal)
- ρ < 0.50: Weak correlation (exclude)
Beta Calculation:
For each candidate pair (Stock A, Stock B):
Beta = Covariance(A, B) / Variance(B)Beta indicates the hedge ratio:
- Beta = 1.0: Equal dollar amounts
- Beta = 1.5: $1.50 of B for every $1.00 of A
- Beta = 0.8: $0.80 of B for every $1.00 of A
Correlation Stability Check:
- Calculate correlation over multiple periods (6mo, 1yr, 2yr)
- Require correlation to be stable (not deteriorating)
- Flag pairs where recent correlation < historical correlation by >0.15
目标: 识别具有强线性关系的候选配对。
相关性分析:
对标的池中的每一对股票(i, j):
- 计算皮尔逊相关系数(ρ)
- 计算滚动相关性(90天窗口)以检查稳定性
- 筛选ρ ≥ 0.70的配对(强正相关)
相关性解读:
- ρ ≥ 0.90:极强相关性(最佳候选)
- ρ 0.70-0.90:强相关性(优质候选)
- ρ 0.50-0.70:中等相关性(边缘候选)
- ρ < 0.50:弱相关性(排除)
Beta值计算:
对每个候选配对(股票A,股票B):
Beta = Covariance(A, B) / Variance(B)Beta值表示对冲比率:
- Beta = 1.0:等额资金配置
- Beta = 1.5:每配置1美元A,对应配置1.5美元B
- Beta = 0.8:每配置1美元A,对应配置0.8美元B
相关性稳定性检查:
- 计算多个时间段(6个月、1年、2年)的相关性
- 要求相关性保持稳定(未出现恶化)
- 若近期相关性较历史相关性下降超过0.15,则标记该配对
Step 4: Cointegration Testing
步骤4:Cointegration检验
Objective: Statistically validate long-term equilibrium relationship.
Why Cointegration Matters:
- Correlation measures short-term co-movement
- Cointegration proves long-term equilibrium relationship
- Cointegrated pairs mean-revert predictably
- Non-cointegrated pairs may diverge permanently
Augmented Dickey-Fuller (ADF) Test:
For each correlated pair:
- Calculate spread:
Spread = Price_A - (Beta × Price_B) - Run ADF test on spread series
- Check p-value: p < 0.05 indicates cointegration (reject null hypothesis of unit root)
- Extract ADF statistic for strength ranking
Cointegration Interpretation:
- p-value < 0.01: Very strong cointegration (★★★)
- p-value 0.01-0.05: Moderate cointegration (★★)
- p-value > 0.05: No cointegration (exclude)
Half-Life Calculation:
Estimate mean-reversion speed:
Half-Life = -log(2) / log(mean_reversion_coefficient)- Half-life < 30 days: Fast mean-reversion (good for short-term trading)
- Half-life 30-60 days: Moderate speed (standard)
- Half-life > 60 days: Slow mean-reversion (long holding periods)
Python Implementation:
python
from statsmodels.tsa.stattools import adfuller目标: 统计验证长期均衡关系。
为什么Cointegration很重要:
- 相关性衡量短期联动性
- Cointegration证明长期均衡关系
- 存在Cointegration的配对会可预测地回归均值
- 无Cointegration的配对可能永久分化
Augmented Dickey-Fuller (ADF) Test:
对每个相关配对:
- 计算价差:
Spread = Price_A - (Beta × Price_B) - 对价差序列运行ADF检验
- 检查p值:p < 0.05表示存在Cointegration(拒绝单位根的原假设)
- 提取ADF统计量用于强度排名
Cointegration解读:
- p值 < 0.01:极强Cointegration(★★★)
- p值 0.01-0.05:中等Cointegration(★★)
- p值 > 0.05:无Cointegration(排除)
半衰期计算:
估计均值回归速度:
Half-Life = -log(2) / log(mean_reversion_coefficient)- 半衰期 < 30天:快速均值回归(适合短期交易)
- 半衰期 30-60天:中等速度(标准水平)
- 半衰期 > 60天:慢速均值回归(持有周期较长)
Python实现:
python
from statsmodels.tsa.stattools import adfullerCalculate spread
Calculate spread
spread = price_a - (beta * price_b)
spread = price_a - (beta * price_b)
ADF test
ADF test
result = adfuller(spread)
adf_stat = result[0]
p_value = result[1]
result = adfuller(spread)
adf_stat = result[0]
p_value = result[1]
Interpret
Interpret
is_cointegrated = p_value < 0.05
undefinedis_cointegrated = p_value < 0.05
undefinedStep 5: Spread Analysis and Z-Score Calculation
步骤5:价差分析与z-score计算
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_BBest 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_SpreadZ-Score Interpretation:
- Z > +2.0: Stock A expensive relative to B (short A, long B)
- Z > +1.5: Moderately expensive (watch for entry)
- Z -1.5 to +1.5: Normal range (no trade)
- Z < -1.5: Moderately cheap (watch for entry)
- Z < -2.0: Stock A cheap relative to B (long A, short B)
Historical Spread Analysis:
- Calculate mean and std dev over 90-day rolling window
- Plot historical z-score distribution
- Identify maximum historical z-score deviations
- Check for structural breaks (spread regime change)
目标: 量化当前价差与均衡水平的偏离程度。
价差计算:
两种常用方法:
方法1:价格差(加法)
Spread = Price_A - (Beta × Price_B)最适用于:价格水平相近的股票
方法2:价格比(乘法)
Spread = Price_A / Price_B最适用于:价格水平不同的股票,解读更简单
z-score计算:
衡量价差偏离均值的标准差倍数:
Z-Score = (Current_Spread - Mean_Spread) / Std_Dev_Spreadz-score解读:
- Z > +2.0:股票A相对B被高估(做空A,做多B)
- Z > +1.5:中度高估(关注进场时机)
- Z -1.5至+1.5:正常区间(不交易)
- Z < -1.5:中度低估(关注进场时机)
- Z < -2.0:股票A相对B被低估(做多A,做空B)
历史价差分析:
- 计算90天滚动窗口的均值和标准差
- 绘制历史z-score分布
- 识别历史z-score的最大偏离值
- 检查是否存在结构突变(价差机制变化)
Step 6: Generate Entry/Exit Recommendations
步骤6:生成进出仓建议
Objective: Provide actionable trading signals with clear rules.
Entry Conditions:
Conservative Approach (Z ≥ ±2.0):
LONG 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)Aggressive Approach (Z ≥ ±1.5):
- Lower threshold for more frequent trades
- Higher win rate but smaller avg profit per trade
- Requires tighter risk management
Exit Conditions:
Primary Exit: Mean Reversion (Z = 0)
Exit when spread returns to mean (z-score crosses 0)
→ Close both legs simultaneouslySecondary Exit: Partial Profit Take
Exit 50% when z-score reaches ±1.0
Exit remaining 50% at z-score = 0Stop Loss:
Exit if z-score extends beyond ±3.0 (extreme divergence)
Risk: Possible structural break in relationshipTime-Based Exit:
Exit after 90 days if no mean-reversion
Prevents holding broken pairs indefinitely目标: 提供清晰规则下的可执行交易信号。
进场条件:
保守策略(Z ≥ ±2.0):
做多信号:
- z-score < -2.0(价差低于均值2个标准差以上)
- 价差具有均值回归性(cointegration p < 0.05)
- 半衰期 < 60天
→ 操作:买入股票A,做空股票B(对冲比率=beta)
做空信号:
- z-score > +2.0(价差高于均值2个标准差以上)
- 价差具有均值回归性(cointegration p < 0.05)
- 半衰期 < 60天
→ 操作:做空股票A,买入股票B(对冲比率=beta)激进策略(Z ≥ ±1.5):
- 更低的阈值以获得更频繁的交易机会
- 胜率更高但单笔交易平均利润更小
- 需要更严格的风险管理
出场条件:
主要出场:均值回归(Z = 0)
当价差回归均值时出场(z-score穿越0)
→ 同时平仓两个头寸次要出场:部分止盈
当z-score达到±1.0时平仓50%
剩余50%在z-score=0时平仓止损:
若z-score超过±3.0(极端偏离)则出场
风险:配对关系可能出现结构突变时间止损:
若90天内未出现均值回归则出场
避免无限期持有已失效的配对Step 7: Position Sizing and Risk Management
步骤7:仓位配置与风险管理
Objective: Determine dollar amounts for market-neutral exposure.
Market Neutral Sizing:
For a pair (Stock A, Stock B) with beta = β:
Equal Dollar Exposure:
If 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 = 0Position Sizing Considerations:
- Total pair allocation: 10-20% of portfolio per pair
- Maximum pairs: 5-8 active pairs for diversification
- Correlation across pairs: Avoid highly correlated pairs
Risk Metrics:
- Maximum loss per pair: 2-3% of total portfolio
- Stop loss trigger: Z-score > ±3.0 or -5% loss on spread
- Portfolio-level risk: Sum of all pair risks ≤ 10%
目标: 确定市场中性敞口的资金规模。
市场中性配置:
对于beta=β的配对(股票A,股票B):
等额资金敞口:
若分配给该配对的投资组合规模为10,000美元:
- 做多5,000美元的股票A
- 做空5,000 × β美元的股票B
示例(β=1.2):
- 做多5,000美元股票A
- 做空6,000美元股票B
→ 市场中性,beta=0仓位配置考虑因素:
- 单配对总配置:投资组合的10-20%
- 最大活跃配对数:5-8个以实现分散化
- 配对间相关性:避免高度相关的配对
风险指标:
- 单配对最大亏损:总投资组合的2-3%
- 止损触发条件:z-score > ±3.0或价差亏损5%
- 组合层面风险:所有配对风险总和 ≤ 10%
Step 8: Generate Pair Analysis Report
步骤8:生成配对分析报告
Objective: Create structured markdown report with findings and recommendations.
Report Sections:
-
Executive Summary
- Total pairs analyzed
- Number of cointegrated pairs found
- Top 5 opportunities ranked by statistical strength
-
Cointegrated Pairs Table
- Pair name (Stock A / Stock B)
- Correlation coefficient
- Cointegration p-value
- Current z-score
- Trade signal (Long/Short/None)
- Half-life
-
Detailed Analysis (Top 10 Pairs)
- Pair description
- Statistical metrics
- Current spread position
- Entry/exit recommendations
- Position sizing
- Risk assessment
-
Spread Charts (Text-Based)
- Historical z-score plot (ASCII art)
- Entry/exit levels marked
- Current position indicator
-
Risk Warnings
- Pairs with deteriorating correlation
- Structural breaks detected
- Low liquidity warnings
File Naming Convention:
pair_trade_analysis_[SECTOR]_[YYYY-MM-DD].mdExample:
pair_trade_analysis_Technology_2025-11-08.md目标: 创建包含研究结果和建议的结构化Markdown报告。
报告章节:
-
执行摘要
- 分析的配对总数
- 找到的协整配对数量
- 按统计强度排名的前5个机会
-
协整配对表
- 配对名称(股票A / 股票B)
- 相关系数
- Cointegration p值
- 当前z-score
- 交易信号(做多/做空/无)
- 半衰期
-
详细分析(前10个配对)
- 配对描述
- 统计指标
- 当前价差位置
- 进出仓建议
- 仓位配置
- 风险评估
-
价差图表(文本格式)
- 历史z-score图(ASCII艺术)
- 标记进出仓水平
- 当前位置指示器
-
风险提示
- 相关性恶化的配对
- 检测到结构突变的配对
- 流动性不足的提示
文件命名规范:
pair_trade_analysis_[SECTOR]_[YYYY-MM-DD].md示例:
pair_trade_analysis_Technology_2025-11-08.mdQuality Standards
质量标准
Statistical Rigor
统计严谨性
Minimum Requirements for Valid Pair:
- ✓ Correlation ≥ 0.70 over 2-year period
- ✓ Cointegration p-value < 0.05 (ADF test)
- ✓ Spread stationarity confirmed
- ✓ Half-life < 90 days
- ✓ No structural breaks in recent 6 months
Red Flags (Exclude Pair):
- Correlation dropped >0.20 in recent 6 months
- Cointegration p-value > 0.05
- Half-life increasing over time (mean-reversion weakening)
- Significant corporate events (merger, spin-off, bankruptcy risk)
- Liquidity concerns (avg volume < 500K shares/day)
有效配对的最低要求:
- ✓ 2年周期内相关性 ≥ 0.70
- ✓ Cointegration p值 < 0.05(ADF检验)
- ✓ 价差平稳性已确认
- ✓ 半衰期 < 90天
- ✓ 近6个月内无结构突变
警示信号(排除配对):
- 近6个月相关性下降超过0.20
- Cointegration p值 > 0.05
- 半衰期持续上升(均值回归性减弱)
- 重大公司事件(并购、分拆、破产风险)
- 流动性问题(日均成交量 < 50万股)
Practical Considerations
实际考虑因素
Transaction Costs:
- Assume 0.1% round-trip cost per leg
- Total cost per pair = 0.4% (entry + exit, both legs)
- Minimum z-score threshold should exceed transaction costs
Short Selling:
- Verify stock is shortable (not hard-to-borrow)
- Factor in short interest costs (borrow fees)
- Monitor short squeeze risk
Execution:
- Enter/exit both legs simultaneously (avoid leg risk)
- Use limit orders to control slippage
- Pre-locate shorts before entry
交易成本:
- 假设每边往返成本为0.1%
- 单配对总成本=0.4%(进出仓,双向头寸)
- 最低z-score阈值应覆盖交易成本
卖空:
- 验证股票是否可卖空(非难借标的)
- 考虑卖空利息成本(借入费用)
- 监控逼空风险
执行:
- 同时进出两个头寸(避免单边风险)
- 使用限价单控制滑点
- 进场前预先锁定卖空标的
Available Scripts
可用脚本
scripts/find_pairs.py
scripts/find_pairs.py
Purpose: Screen for cointegrated pairs within a sector or custom list.
Usage:
bash
undefined用途: 在板块或自定义列表中筛选协整配对。
使用方法:
bash
undefinedSector-based screening
基于板块的筛选
python scripts/find_pairs.py --sector Technology --min-correlation 0.70
python scripts/find_pairs.py --sector Technology --min-correlation 0.70
Custom stock list
自定义股票列表
python scripts/find_pairs.py --symbols AAPL,MSFT,GOOGL,META --min-correlation 0.75
python scripts/find_pairs.py --symbols AAPL,MSFT,GOOGL,META --min-correlation 0.75
Full options
完整选项
python scripts/find_pairs.py
--sector Financials
--min-correlation 0.70
--min-market-cap 2000000000
--lookback-days 730
--output pairs_analysis.json
--sector Financials
--min-correlation 0.70
--min-market-cap 2000000000
--lookback-days 730
--output pairs_analysis.json
**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: stdout)
- `--api-key`: FMP API key (or set FMP_API_KEY env var)
**Output:**
```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"
}
]python scripts/find_pairs.py
--sector Financials
--min-correlation 0.70
--min-market-cap 2000000000
--lookback-days 730
--output pairs_analysis.json
--sector Financials
--min-correlation 0.70
--min-market-cap 2000000000
--lookback-days 730
--output pairs_analysis.json
**参数:**
- `--sector`: 板块名称(Technology、Financials等)
- `--symbols`: 逗号分隔的股票代码列表(替代板块参数)
- `--min-correlation`: 最低相关性阈值(默认:0.70)
- `--min-market-cap`: 最低市值筛选(默认:20亿美元)
- `--lookback-days`: 历史数据周期(默认:730天)
- `--output`: 输出JSON文件(默认:标准输出)
- `--api-key`: FMP API密钥(或设置FMP_API_KEY环境变量)
**输出:**
```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"
}
]scripts/analyze_spread.py
scripts/analyze_spread.py
Purpose: Analyze a specific pair's spread behavior and generate trading signals.
Usage:
bash
undefined用途: 分析特定配对的价差行为并生成交易信号。
使用方法:
bash
undefinedAnalyze specific pair
分析特定配对
python scripts/analyze_spread.py --stock-a AAPL --stock-b MSFT
python scripts/analyze_spread.py --stock-a AAPL --stock-b MSFT
Custom lookback period
自定义回溯周期
python scripts/analyze_spread.py
--stock-a JPM
--stock-b BAC
--lookback-days 365
--entry-zscore 2.0
--exit-zscore 0.5
--stock-a JPM
--stock-b BAC
--lookback-days 365
--entry-zscore 2.0
--exit-zscore 0.5
**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 key
**Output:**
- Current spread analysis
- Z-score calculation
- Entry/exit recommendations
- Position sizing
- Historical z-score chart (text)python scripts/analyze_spread.py
--stock-a JPM
--stock-b BAC
--lookback-days 365
--entry-zscore 2.0
--exit-zscore 0.5
--stock-a JPM
--stock-b BAC
--lookback-days 365
--entry-zscore 2.0
--exit-zscore 0.5
**参数:**
- `--stock-a`: 第一只股票代码
- `--stock-b`: 第二只股票代码
- `--lookback-days`: 分析周期(默认:365天)
- `--entry-zscore`: 进场z-score阈值(默认:2.0)
- `--exit-zscore`: 出场z-score阈值(默认:0.0)
- `--api-key`: FMP API密钥
**输出:**
- 当前价差分析
- z-score计算结果
- 进出仓建议
- 仓位配置
- 历史z-score图表(文本格式)Reference Documentation
参考文档
references/methodology.md
references/methodology.md
Comprehensive guide to statistical arbitrage and pair trading:
- Pair Selection Criteria: How to identify good pair candidates
- Statistical Tests: Correlation, cointegration, stationarity
- Spread Construction: Price difference vs price ratio approaches
- Mean Reversion: Half-life calculation and interpretation
- Risk Management: Position sizing, stop losses, diversification
- Common Pitfalls: Survivorship bias, look-ahead bias, overfitting
统计套利与配对交易的综合指南:
- 配对选择标准:如何识别优质配对候选
- 统计检验:相关性、协整、平稳性
- 价差构建:价格差vs价格比方法
- 均值回归:半衰期计算与解读
- 风险管理:仓位配置、止损、分散化
- 常见陷阱:生存偏差、前瞻偏差、过拟合
references/cointegration_guide.md
references/cointegration_guide.md
Deep dive into cointegration testing:
- What is Cointegration?: Intuitive explanation
- ADF Test: Step-by-step procedure
- P-Value Interpretation: Statistical significance thresholds
- Half-Life Estimation: AR(1) model approach
- Structural Breaks: Testing for regime changes
- Practical Examples: Case studies with real pairs
协整检验深度指南:
- 什么是Cointegration? 直观解释
- ADF Test:分步流程
- P值解读:统计显著性阈值
- 半衰期估计:AR(1)模型方法
- 结构突变:机制变化检验
- 实际示例:真实配对的案例研究
Integration with Other Skills
与其他工具的集成
Sector Analyst Integration:
- Use Sector Analyst to identify sectors in rotation
- Screen for pairs within outperforming sectors
- Pairs in leading sectors may have stronger trends
Technical Analyst Integration:
- Confirm pair entry/exit with individual stock technicals
- Check support/resistance levels before entry
- Validate trend direction aligns with spread signal
Backtest Expert Integration:
- Feed pair candidates to Backtest Expert for validation
- Test historical z-score entry/exit rules
- Optimize threshold parameters (entry z-score, stop loss)
- Walk-forward analysis for robustness
Market Environment Analysis Integration:
- Avoid pair trading during extreme volatility (VIX > 30)
- Correlations break down in crisis periods
- Prefer pair trading in sideways/range-bound markets
Portfolio Manager Integration:
- Track multiple pair positions
- Monitor overall market-neutral exposure
- Calculate portfolio-level pair trading P/L
- Rebalance hedge ratios periodically
板块分析师集成:
- 使用板块分析师识别轮动中的板块
- 在表现优异的板块内筛选配对
- 领先板块中的配对可能具有更强的趋势
技术分析师集成:
- 用个股技术指标确认配对进出仓信号
- 进场前检查支撑/阻力位
- 验证趋势方向与价差信号一致
回测专家集成:
- 将配对候选提供给回测专家进行验证
- 测试历史z-score进出仓规则
- 优化阈值参数(进场z-score、止损)
- 滚动窗口分析以验证稳健性
市场环境分析集成:
- 极端波动期间(VIX > 30)避免配对交易
- 危机期间相关性会破裂
- 横盘/区间震荡市场更适合配对交易
投资组合经理集成:
- 跟踪多个配对头寸
- 监控整体市场中性敞口
- 计算组合层面的配对交易盈亏
- 定期重新平衡对冲比率
Important Notes
重要说明
- All analysis and output in English
- Statistical foundation: No discretionary interpretation
- Market neutral focus: Minimize directional beta exposure
- Data quality critical: Garbage in, garbage out
- Requires FMP API key: Free tier sufficient for basic screening
- Python dependencies: pandas, numpy, scipy, statsmodels
- 所有分析和输出均为英文
- 统计基础:无主观解读
- 市场中性聚焦:最小化方向性beta敞口
- 数据质量至关重要:输入垃圾数据,输出垃圾结果
- 需要FMP API密钥:免费 tier 足以满足基础筛选需求
- Python依赖:pandas, numpy, scipy, statsmodels
Common Use Cases
常见用例
Use Case 1: Technology Sector Pairs
User: "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 reportUse Case 2: Specific Pair Analysis
User: "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 guidanceUse Case 3: Regional Bank Pairs
User: "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用例1:科技板块配对
用户: "在科技股中寻找配对交易机会"
流程:
1. 筛选科技板块中市值>100亿美元的股票
2. 计算所有两两相关性
3. 筛选相关性≥0.75的配对
4. 运行协整检验
5. 识别当前z-score极端值(|z| > 2.0)
6. 生成前10个配对的报告用例2:特定配对分析
用户: "分析AAPL和MSFT的配对交易机会"
流程:
1. 获取AAPL和MSFT的2年历史价格数据
2. 计算相关性和Beta值
3. 运行协整检验
4. 计算当前价差和z-score
5. 生成进出仓建议
6. 提供仓位配置指导用例3:区域银行配对
用户: "筛选区域银行中的配对机会"
流程:
1. 在金融板块中筛选行业为"区域银行"的标的
2. 排除市值<50亿美元的银行
3. 计算两两统计指标
4. 按协整强度排名
5. 聚焦半衰期<45天的配对
6. 报告前5个均值回归配对Troubleshooting
故障排除
Problem: No cointegrated pairs found
Solutions:
- Expand universe (lower market cap threshold)
- Relax cointegration p-value to 0.10
- Try different sectors (Utilities often cointegrate well)
- Increase lookback period to 3 years
Problem: All z-scores near zero (no trade signals)
Solutions:
- Normal market condition (pairs in equilibrium)
- Check back later or expand universe
- Lower entry threshold to ±1.5 instead of ±2.0
Problem: Pair correlation broke down
Solutions:
- Check for corporate events (earnings, guidance changes)
- Verify no M&A activity or restructuring
- Remove pair from watchlist if structural break confirmed
- Monitor for 30 days before re-entering
问题:未找到协整配对
解决方案:
- 扩大标的池(降低市值阈值)
- 将协整p值放宽至0.10
- 尝试其他板块(公用事业板块通常协整性较好)
- 将回溯周期增加至3年
问题:所有z-score接近0(无交易信号)
解决方案:
- 市场处于正常状态(配对处于均衡)
- 稍后再检查或扩大标的池
- 将进场阈值从±2.0降低至±1.5
问题:配对相关性破裂
解决方案:
- 检查公司事件(财报、业绩指引变化)
- 确认无并购或重组活动
- 若确认结构突变,将配对从观察列表中移除
- 监控30天后再考虑重新纳入
API Requirements
API要求
- Required: FMP API key (free tier sufficient)
- Rate Limits: ~250 requests/day on free tier
- Data Usage: ~2 requests per symbol for 2-year history
- Upgrade: Professional plan ($29/mo) recommended for frequent screening
- 必需:FMP API密钥(免费 tier 可用)
- 速率限制:免费 tier 约250请求/天
- 数据使用:每个标的2年历史数据约需2次请求
- 升级建议:频繁筛选推荐专业版(29美元/月)
Resources
资源
- FMP Historical Price API: https://site.financialmodelingprep.com/developer/docs/historical-price-full
- Stock Screener API: https://site.financialmodelingprep.com/developer/docs/stock-screener-api
- Statsmodels Documentation: https://www.statsmodels.org/stable/index.html
- Cointegration Paper: Engle & Granger (1987) - "Co-Integration and Error Correction"
Version: 1.0
Last Updated: 2025-11-08
Dependencies: Python 3.8+, pandas, numpy, scipy, statsmodels, requests
- FMP历史价格API: https://site.financialmodelingprep.com/developer/docs/historical-price-full
- 股票筛选API: https://site.financialmodelingprep.com/developer/docs/stock-screener-api
- Statsmodels文档: https://www.statsmodels.org/stable/index.html
- 协整论文: Engle & Granger (1987) - "Co-Integration and Error Correction"
版本: 1.0
最后更新: 2025-11-08
依赖: Python 3.8+, pandas, numpy, scipy, statsmodels, requests