{
  "schemaVersion": "1.0",
  "item": {
    "slug": "pair-trade-screener",
    "name": "Pair Trade Screener",
    "source": "tencent",
    "type": "skill",
    "category": "开发工具",
    "sourceUrl": "https://clawhub.ai/Veeramanikandanr48/pair-trade-screener",
    "canonicalUrl": "https://clawhub.ai/Veeramanikandanr48/pair-trade-screener",
    "targetPlatform": "OpenClaw"
  },
  "install": {
    "downloadMode": "redirect",
    "downloadUrl": "/downloads/pair-trade-screener",
    "sourceDownloadUrl": "https://wry-manatee-359.convex.site/api/v1/download?slug=pair-trade-screener",
    "sourcePlatform": "tencent",
    "targetPlatform": "OpenClaw",
    "installMethod": "Manual import",
    "extraction": "Extract archive",
    "prerequisites": [
      "OpenClaw"
    ],
    "packageFormat": "ZIP package",
    "includedAssets": [
      "README.md",
      "SKILL.md",
      "references/cointegration_guide.md",
      "references/methodology.md",
      "scripts/analyze_spread.py",
      "scripts/find_pairs.py"
    ],
    "primaryDoc": "SKILL.md",
    "quickSetup": [
      "Download the package from Yavira.",
      "Extract the archive and review SKILL.md first.",
      "Import or place the package into your OpenClaw setup."
    ],
    "agentAssist": {
      "summary": "Hand the extracted package to your coding agent with a concrete install brief instead of figuring it out manually.",
      "steps": [
        "Download the package from Yavira.",
        "Extract it into a folder your agent can access.",
        "Paste one of the prompts below and point your agent at the extracted folder."
      ],
      "prompts": [
        {
          "label": "New install",
          "body": "I downloaded a skill package from Yavira. Read SKILL.md from the extracted folder and install it by following the included instructions. Then review README.md for any prerequisites, environment setup, or post-install checks. Tell me what you changed and call out any manual steps you could not complete."
        },
        {
          "label": "Upgrade existing",
          "body": "I downloaded an updated skill package from Yavira. Read SKILL.md from the extracted folder, compare it with my current installation, and upgrade it while preserving any custom configuration unless the package docs explicitly say otherwise. Then review README.md for any prerequisites, environment setup, or post-install checks. Summarize what changed and any follow-up checks I should run."
        }
      ]
    },
    "sourceHealth": {
      "source": "tencent",
      "slug": "pair-trade-screener",
      "status": "healthy",
      "reason": "direct_download_ok",
      "recommendedAction": "download",
      "checkedAt": "2026-05-06T21:52:04.963Z",
      "expiresAt": "2026-05-13T21:52:04.963Z",
      "httpStatus": 200,
      "finalUrl": "https://wry-manatee-359.convex.site/api/v1/download?slug=pair-trade-screener",
      "contentType": "application/zip",
      "probeMethod": "head",
      "details": {
        "probeUrl": "https://wry-manatee-359.convex.site/api/v1/download?slug=pair-trade-screener",
        "contentDisposition": "attachment; filename=\"pair-trade-screener-0.1.0.zip\"",
        "redirectLocation": null,
        "bodySnippet": null,
        "slug": "pair-trade-screener"
      },
      "scope": "item",
      "summary": "Item download looks usable.",
      "detail": "Yavira can redirect you to the upstream package for this item.",
      "primaryActionLabel": "Download for OpenClaw",
      "primaryActionHref": "/downloads/pair-trade-screener"
    },
    "validation": {
      "installChecklist": [
        "Use the Yavira download entry.",
        "Review SKILL.md after the package is downloaded.",
        "Confirm the extracted package contains the expected setup assets."
      ],
      "postInstallChecks": [
        "Confirm the extracted package includes the expected docs or setup files.",
        "Validate the skill or prompts are available in your target agent workspace.",
        "Capture any manual follow-up steps the agent could not complete."
      ]
    },
    "downloadPageUrl": "https://openagent3.xyz/downloads/pair-trade-screener",
    "agentPageUrl": "https://openagent3.xyz/skills/pair-trade-screener/agent",
    "manifestUrl": "https://openagent3.xyz/skills/pair-trade-screener/agent.json",
    "briefUrl": "https://openagent3.xyz/skills/pair-trade-screener/agent.md"
  },
  "agentAssist": {
    "summary": "Hand the extracted package to your coding agent with a concrete install brief instead of figuring it out manually.",
    "steps": [
      "Download the package from Yavira.",
      "Extract it into a folder your agent can access.",
      "Paste one of the prompts below and point your agent at the extracted folder."
    ],
    "prompts": [
      {
        "label": "New install",
        "body": "I downloaded a skill package from Yavira. Read SKILL.md from the extracted folder and install it by following the included instructions. Then review README.md for any prerequisites, environment setup, or post-install checks. Tell me what you changed and call out any manual steps you could not complete."
      },
      {
        "label": "Upgrade existing",
        "body": "I downloaded an updated skill package from Yavira. Read SKILL.md from the extracted folder, compare it with my current installation, and upgrade it while preserving any custom configuration unless the package docs explicitly say otherwise. Then review README.md for any prerequisites, environment setup, or post-install checks. Summarize what changed and any follow-up checks I should run."
      }
    ]
  },
  "documentation": {
    "source": "clawhub",
    "primaryDoc": "SKILL.md",
    "sections": [
      {
        "title": "Overview",
        "body": "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.\n\nCore Methodology:\n\nIdentify pairs of stocks with high correlation and similar sector/industry exposure\nTest for cointegration (long-term statistical relationship)\nCalculate spread z-scores to identify mean-reversion opportunities\nGenerate entry/exit signals based on statistical thresholds\nProvide position sizing for market-neutral exposure\n\nKey Advantages:\n\nMarket-neutral: Profits in up, down, or sideways markets\nRisk management: Limited exposure to broad market movements\nStatistical foundation: Data-driven, not discretionary\nDiversification: Uncorrelated to traditional long-only strategies"
      },
      {
        "title": "When to Use This Skill",
        "body": "Use this skill when:\n\nUser asks for \"pair trading opportunities\"\nUser wants \"market-neutral strategies\"\nUser requests \"statistical arbitrage screening\"\nUser asks \"which stocks move together?\"\nUser wants to hedge sector exposure\nUser requests mean-reversion trade ideas\nUser asks about relative value trading\n\nExample user requests:\n\n\"Find pair trading opportunities in the tech sector\"\n\"Which stocks are cointegrated?\"\n\"Screen for statistical arbitrage opportunities\"\n\"Find mean-reversion pairs\"\n\"What are good market-neutral trades right now?\""
      },
      {
        "title": "Step 1: Define Pair Universe",
        "body": "Objective: Establish the pool of stocks to analyze for pair relationships.\n\nOption A: Sector-Based Screening (Recommended)\n\nSelect a specific sector to screen:\n\nTechnology\nFinancials\nHealthcare\nConsumer Discretionary\nIndustrials\nEnergy\nMaterials\nConsumer Staples\nUtilities\nReal Estate\nCommunication Services\n\nOption B: Custom Stock List\n\nUser provides specific tickers to analyze:\n\nExample: [\"AAPL\", \"MSFT\", \"GOOGL\", \"META\", \"NVDA\"]\n\nOption C: Industry-Specific\n\nNarrow focus to specific industry within sector:\n\nExample: \"Software\" within Technology sector\nExample: \"Regional Banks\" within Financials\n\nFiltering Criteria:\n\nMinimum market cap: $2B (mid-cap and above)\nMinimum average volume: 1M shares/day (liquidity requirement)\nActive trading: No delisted or inactive stocks\nSame exchange preference: Avoid cross-exchange complications"
      },
      {
        "title": "Step 2: Retrieve Historical Price Data",
        "body": "Objective: Fetch price history for correlation and cointegration analysis.\n\nData Requirements:\n\nTimeframe: 2 years (minimum 252 trading days)\nFrequency: Daily closing prices\nAdjustments: Adjusted for splits and dividends\nClean data: No gaps or missing values\n\nFMP API Endpoint:\n\nGET /v3/historical-price-full/{symbol}?apikey=YOUR_API_KEY\n\nData Validation:\n\nVerify consistent date ranges across all symbols\nRemove stocks with >10% missing data\nFill minor gaps with forward-fill method\nLog data quality issues\n\nScript Execution:\n\npython scripts/fetch_price_data.py --sector Technology --lookback 730"
      },
      {
        "title": "Step 3: Calculate Correlation and Beta",
        "body": "Objective: Identify candidate pairs with strong linear relationships.\n\nCorrelation Analysis:\n\nFor each pair of stocks (i, j) in the universe:\n\nCalculate Pearson correlation coefficient (ρ)\nCalculate rolling correlation (90-day window) for stability check\nFilter pairs with ρ >= 0.70 (strong positive correlation)\n\nCorrelation Interpretation:\n\nρ >= 0.90: Very strong correlation (best candidates)\nρ 0.70-0.90: Strong correlation (good candidates)\nρ 0.50-0.70: Moderate correlation (marginal)\nρ < 0.50: Weak correlation (exclude)\n\nBeta Calculation:\n\nFor each candidate pair (Stock A, Stock B):\n\nBeta = Covariance(A, B) / Variance(B)\n\nBeta indicates the hedge ratio:\n\nBeta = 1.0: Equal dollar amounts\nBeta = 1.5: $1.50 of B for every $1.00 of A\nBeta = 0.8: $0.80 of B for every $1.00 of A\n\nCorrelation Stability Check:\n\nCalculate correlation over multiple periods (6mo, 1yr, 2yr)\nRequire correlation to be stable (not deteriorating)\nFlag pairs where recent correlation < historical correlation by >0.15"
      },
      {
        "title": "Step 4: Cointegration Testing",
        "body": "Objective: Statistically validate long-term equilibrium relationship.\n\nWhy Cointegration Matters:\n\nCorrelation measures short-term co-movement\nCointegration proves long-term equilibrium relationship\nCointegrated pairs mean-revert predictably\nNon-cointegrated pairs may diverge permanently\n\nAugmented Dickey-Fuller (ADF) Test:\n\nFor each correlated pair:\n\nCalculate spread: Spread = Price_A - (Beta × Price_B)\nRun ADF test on spread series\nCheck p-value: p < 0.05 indicates cointegration (reject null hypothesis of unit root)\nExtract ADF statistic for strength ranking\n\nCointegration Interpretation:\n\np-value < 0.01: Very strong cointegration (★★★)\np-value 0.01-0.05: Moderate cointegration (★★)\np-value > 0.05: No cointegration (exclude)\n\nHalf-Life Calculation:\n\nEstimate mean-reversion speed:\n\nHalf-Life = -log(2) / log(mean_reversion_coefficient)\n\nHalf-life < 30 days: Fast mean-reversion (good for short-term trading)\nHalf-life 30-60 days: Moderate speed (standard)\nHalf-life > 60 days: Slow mean-reversion (long holding periods)\n\nPython Implementation:\n\nfrom statsmodels.tsa.stattools import adfuller\n\n# Calculate spread\nspread = price_a - (beta * price_b)\n\n# ADF test\nresult = adfuller(spread)\nadf_stat = result[0]\np_value = result[1]\n\n# Interpret\nis_cointegrated = p_value < 0.05"
      },
      {
        "title": "Step 5: Spread Analysis and Z-Score Calculation",
        "body": "Objective: Quantify current spread deviation from equilibrium.\n\nSpread Calculation:\n\nTwo common methods:\n\nMethod 1: Price Difference (Additive)\n\nSpread = Price_A - (Beta × Price_B)\n\nBest for: Stocks with similar price levels\n\nMethod 2: Price Ratio (Multiplicative)\n\nSpread = Price_A / Price_B\n\nBest for: Stocks with different price levels, easier interpretation\n\nZ-Score Calculation:\n\nMeasures how many standard deviations spread is from its mean:\n\nZ-Score = (Current_Spread - Mean_Spread) / Std_Dev_Spread\n\nZ-Score Interpretation:\n\nZ > +2.0: Stock A expensive relative to B (short A, long B)\nZ > +1.5: Moderately expensive (watch for entry)\nZ -1.5 to +1.5: Normal range (no trade)\nZ < -1.5: Moderately cheap (watch for entry)\nZ < -2.0: Stock A cheap relative to B (long A, short B)\n\nHistorical Spread Analysis:\n\nCalculate mean and std dev over 90-day rolling window\nPlot historical z-score distribution\nIdentify maximum historical z-score deviations\nCheck for structural breaks (spread regime change)"
      },
      {
        "title": "Step 6: Generate Entry/Exit Recommendations",
        "body": "Objective: Provide actionable trading signals with clear rules.\n\nEntry Conditions:\n\nConservative Approach (Z ≥ ±2.0):\n\nLONG Signal:\n- Z-score < -2.0 (spread 2+ std devs below mean)\n- Spread is mean-reverting (cointegration p < 0.05)\n- Half-life < 60 days\n→ Action: Buy Stock A, Short Stock B (hedge ratio = beta)\n\nSHORT Signal:\n- Z-score > +2.0 (spread 2+ std devs above mean)\n- Spread is mean-reverting (cointegration p < 0.05)\n- Half-life < 60 days\n→ Action: Short Stock A, Buy Stock B (hedge ratio = beta)\n\nAggressive Approach (Z ≥ ±1.5):\n\nLower threshold for more frequent trades\nHigher win rate but smaller avg profit per trade\nRequires tighter risk management\n\nExit Conditions:\n\nPrimary Exit: Mean Reversion (Z = 0)\n\nExit when spread returns to mean (z-score crosses 0)\n→ Close both legs simultaneously\n\nSecondary Exit: Partial Profit Take\n\nExit 50% when z-score reaches ±1.0\nExit remaining 50% at z-score = 0\n\nStop Loss:\n\nExit if z-score extends beyond ±3.0 (extreme divergence)\nRisk: Possible structural break in relationship\n\nTime-Based Exit:\n\nExit after 90 days if no mean-reversion\nPrevents holding broken pairs indefinitely"
      },
      {
        "title": "Step 7: Position Sizing and Risk Management",
        "body": "Objective: Determine dollar amounts for market-neutral exposure.\n\nMarket Neutral Sizing:\n\nFor a pair (Stock A, Stock B) with beta = β:\n\nEqual Dollar Exposure:\n\nIf portfolio size = $10,000 allocated to this pair:\n- Long $5,000 of Stock A\n- Short $5,000 × β of Stock B\n\nExample (β = 1.2):\n- Long $5,000 Stock A\n- Short $6,000 Stock B\n→ Market neutral, beta = 0\n\nPosition Sizing Considerations:\n\nTotal pair allocation: 10-20% of portfolio per pair\nMaximum pairs: 5-8 active pairs for diversification\nCorrelation across pairs: Avoid highly correlated pairs\n\nRisk Metrics:\n\nMaximum loss per pair: 2-3% of total portfolio\nStop loss trigger: Z-score > ±3.0 or -5% loss on spread\nPortfolio-level risk: Sum of all pair risks ≤ 10%"
      },
      {
        "title": "Step 8: Generate Pair Analysis Report",
        "body": "Objective: Create structured markdown report with findings and recommendations.\n\nReport Sections:\n\nExecutive Summary\n\nTotal pairs analyzed\nNumber of cointegrated pairs found\nTop 5 opportunities ranked by statistical strength\n\n\n\nCointegrated Pairs Table\n\nPair name (Stock A / Stock B)\nCorrelation coefficient\nCointegration p-value\nCurrent z-score\nTrade signal (Long/Short/None)\nHalf-life\n\n\n\nDetailed Analysis (Top 10 Pairs)\n\nPair description\nStatistical metrics\nCurrent spread position\nEntry/exit recommendations\nPosition sizing\nRisk assessment\n\n\n\nSpread Charts (Text-Based)\n\nHistorical z-score plot (ASCII art)\nEntry/exit levels marked\nCurrent position indicator\n\n\n\nRisk Warnings\n\nPairs with deteriorating correlation\nStructural breaks detected\nLow liquidity warnings\n\nFile Naming Convention:\n\npair_trade_analysis_[SECTOR]_[YYYY-MM-DD].md\n\nExample: pair_trade_analysis_Technology_2025-11-08.md"
      },
      {
        "title": "Statistical Rigor",
        "body": "Minimum Requirements for Valid Pair:\n\n✓ Correlation ≥ 0.70 over 2-year period\n✓ Cointegration p-value < 0.05 (ADF test)\n✓ Spread stationarity confirmed\n✓ Half-life < 90 days\n✓ No structural breaks in recent 6 months\n\nRed Flags (Exclude Pair):\n\nCorrelation dropped >0.20 in recent 6 months\nCointegration p-value > 0.05\nHalf-life increasing over time (mean-reversion weakening)\nSignificant corporate events (merger, spin-off, bankruptcy risk)\nLiquidity concerns (avg volume < 500K shares/day)"
      },
      {
        "title": "Practical Considerations",
        "body": "Transaction Costs:\n\nAssume 0.1% round-trip cost per leg\nTotal cost per pair = 0.4% (entry + exit, both legs)\nMinimum z-score threshold should exceed transaction costs\n\nShort Selling:\n\nVerify stock is shortable (not hard-to-borrow)\nFactor in short interest costs (borrow fees)\nMonitor short squeeze risk\n\nExecution:\n\nEnter/exit both legs simultaneously (avoid leg risk)\nUse limit orders to control slippage\nPre-locate shorts before entry"
      },
      {
        "title": "scripts/find_pairs.py",
        "body": "Purpose: Screen for cointegrated pairs within a sector or custom list.\n\nUsage:\n\n# Sector-based screening\npython scripts/find_pairs.py --sector Technology --min-correlation 0.70\n\n# Custom stock list\npython scripts/find_pairs.py --symbols AAPL,MSFT,GOOGL,META --min-correlation 0.75\n\n# Full options\npython scripts/find_pairs.py \\\n  --sector Financials \\\n  --min-correlation 0.70 \\\n  --min-market-cap 2000000000 \\\n  --lookback-days 730 \\\n  --output pairs_analysis.json\n\nParameters:\n\n--sector: Sector name (Technology, Financials, etc.)\n--symbols: Comma-separated list of tickers (alternative to sector)\n--min-correlation: Minimum correlation threshold (default: 0.70)\n--min-market-cap: Minimum market cap filter (default: $2B)\n--lookback-days: Historical data period (default: 730 days)\n--output: Output JSON file (default: stdout)\n--api-key: FMP API key (or set FMP_API_KEY env var)\n\nOutput:\n\n[\n  {\n    \"pair\": \"AAPL/MSFT\",\n    \"stock_a\": \"AAPL\",\n    \"stock_b\": \"MSFT\",\n    \"correlation\": 0.87,\n    \"beta\": 1.15,\n    \"cointegration_pvalue\": 0.012,\n    \"adf_statistic\": -3.45,\n    \"half_life_days\": 42,\n    \"current_zscore\": -2.3,\n    \"signal\": \"LONG\",\n    \"strength\": \"Strong\"\n  }\n]"
      },
      {
        "title": "scripts/analyze_spread.py",
        "body": "Purpose: Analyze a specific pair's spread behavior and generate trading signals.\n\nUsage:\n\n# Analyze specific pair\npython scripts/analyze_spread.py --stock-a AAPL --stock-b MSFT\n\n# Custom lookback period\npython scripts/analyze_spread.py \\\n  --stock-a JPM \\\n  --stock-b BAC \\\n  --lookback-days 365 \\\n  --entry-zscore 2.0 \\\n  --exit-zscore 0.5\n\nParameters:\n\n--stock-a: First stock ticker\n--stock-b: Second stock ticker\n--lookback-days: Analysis period (default: 365)\n--entry-zscore: Z-score threshold for entry (default: 2.0)\n--exit-zscore: Z-score threshold for exit (default: 0.0)\n--api-key: FMP API key\n\nOutput:\n\nCurrent spread analysis\nZ-score calculation\nEntry/exit recommendations\nPosition sizing\nHistorical z-score chart (text)"
      },
      {
        "title": "references/methodology.md",
        "body": "Comprehensive guide to statistical arbitrage and pair trading:\n\nPair Selection Criteria: How to identify good pair candidates\nStatistical Tests: Correlation, cointegration, stationarity\nSpread Construction: Price difference vs price ratio approaches\nMean Reversion: Half-life calculation and interpretation\nRisk Management: Position sizing, stop losses, diversification\nCommon Pitfalls: Survivorship bias, look-ahead bias, overfitting"
      },
      {
        "title": "references/cointegration_guide.md",
        "body": "Deep dive into cointegration testing:\n\nWhat is Cointegration?: Intuitive explanation\nADF Test: Step-by-step procedure\nP-Value Interpretation: Statistical significance thresholds\nHalf-Life Estimation: AR(1) model approach\nStructural Breaks: Testing for regime changes\nPractical Examples: Case studies with real pairs"
      },
      {
        "title": "Integration with Other Skills",
        "body": "Sector Analyst Integration:\n\nUse Sector Analyst to identify sectors in rotation\nScreen for pairs within outperforming sectors\nPairs in leading sectors may have stronger trends\n\nTechnical Analyst Integration:\n\nConfirm pair entry/exit with individual stock technicals\nCheck support/resistance levels before entry\nValidate trend direction aligns with spread signal\n\nBacktest Expert Integration:\n\nFeed pair candidates to Backtest Expert for validation\nTest historical z-score entry/exit rules\nOptimize threshold parameters (entry z-score, stop loss)\nWalk-forward analysis for robustness\n\nMarket Environment Analysis Integration:\n\nAvoid pair trading during extreme volatility (VIX > 30)\nCorrelations break down in crisis periods\nPrefer pair trading in sideways/range-bound markets\n\nPortfolio Manager Integration:\n\nTrack multiple pair positions\nMonitor overall market-neutral exposure\nCalculate portfolio-level pair trading P/L\nRebalance hedge ratios periodically"
      },
      {
        "title": "Important Notes",
        "body": "All analysis and output in English\nStatistical foundation: No discretionary interpretation\nMarket neutral focus: Minimize directional beta exposure\nData quality critical: Garbage in, garbage out\nRequires FMP API key: Free tier sufficient for basic screening\nPython dependencies: pandas, numpy, scipy, statsmodels"
      },
      {
        "title": "Common Use Cases",
        "body": "Use Case 1: Technology Sector Pairs\n\nUser: \"Find pair trading opportunities in tech stocks\"\n\nWorkflow:\n1. Screen Technology sector for stocks with market cap > $10B\n2. Calculate all pairwise correlations\n3. Filter pairs with correlation ≥ 0.75\n4. Run cointegration tests\n5. Identify current z-score extremes (|z| > 2.0)\n6. Generate top 10 pairs report\n\nUse Case 2: Specific Pair Analysis\n\nUser: \"Analyze AAPL and MSFT as a pair trade\"\n\nWorkflow:\n1. Fetch 2-year price history for AAPL and MSFT\n2. Calculate correlation and beta\n3. Test for cointegration\n4. Calculate current spread and z-score\n5. Generate entry/exit recommendation\n6. Provide position sizing guidance\n\nUse Case 3: Regional Bank Pairs\n\nUser: \"Screen for pairs among regional banks\"\n\nWorkflow:\n1. Filter Financials sector for industry = \"Regional Banks\"\n2. Exclude banks with <$5B market cap\n3. Calculate pairwise statistics\n4. Rank by cointegration strength\n5. Focus on pairs with half-life < 45 days\n6. Report top 5 mean-reverting pairs"
      },
      {
        "title": "Troubleshooting",
        "body": "Problem: No cointegrated pairs found\n\nSolutions:\n\nExpand universe (lower market cap threshold)\nRelax cointegration p-value to 0.10\nTry different sectors (Utilities often cointegrate well)\nIncrease lookback period to 3 years\n\nProblem: All z-scores near zero (no trade signals)\n\nSolutions:\n\nNormal market condition (pairs in equilibrium)\nCheck back later or expand universe\nLower entry threshold to ±1.5 instead of ±2.0\n\nProblem: Pair correlation broke down\n\nSolutions:\n\nCheck for corporate events (earnings, guidance changes)\nVerify no M&A activity or restructuring\nRemove pair from watchlist if structural break confirmed\nMonitor for 30 days before re-entering"
      },
      {
        "title": "API Requirements",
        "body": "Required: FMP API key (free tier sufficient)\nRate Limits: ~250 requests/day on free tier\nData Usage: ~2 requests per symbol for 2-year history\nUpgrade: Professional plan ($29/mo) recommended for frequent screening"
      },
      {
        "title": "Resources",
        "body": "FMP Historical Price API: https://site.financialmodelingprep.com/developer/docs/historical-price-full\nStock Screener API: https://site.financialmodelingprep.com/developer/docs/stock-screener-api\nStatsmodels Documentation: https://www.statsmodels.org/stable/index.html\nCointegration Paper: Engle & Granger (1987) - \"Co-Integration and Error Correction\"\n\nVersion: 1.0\nLast Updated: 2025-11-08\nDependencies: Python 3.8+, pandas, numpy, scipy, statsmodels, requests"
      }
    ],
    "body": "Pair Trade Screener\nOverview\n\nThis 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.\n\nCore Methodology:\n\nIdentify pairs of stocks with high correlation and similar sector/industry exposure\nTest for cointegration (long-term statistical relationship)\nCalculate spread z-scores to identify mean-reversion opportunities\nGenerate entry/exit signals based on statistical thresholds\nProvide position sizing for market-neutral exposure\n\nKey Advantages:\n\nMarket-neutral: Profits in up, down, or sideways markets\nRisk management: Limited exposure to broad market movements\nStatistical foundation: Data-driven, not discretionary\nDiversification: Uncorrelated to traditional long-only strategies\nWhen to Use This Skill\n\nUse this skill when:\n\nUser asks for \"pair trading opportunities\"\nUser wants \"market-neutral strategies\"\nUser requests \"statistical arbitrage screening\"\nUser asks \"which stocks move together?\"\nUser wants to hedge sector exposure\nUser requests mean-reversion trade ideas\nUser asks about relative value trading\n\nExample user requests:\n\n\"Find pair trading opportunities in the tech sector\"\n\"Which stocks are cointegrated?\"\n\"Screen for statistical arbitrage opportunities\"\n\"Find mean-reversion pairs\"\n\"What are good market-neutral trades right now?\"\nAnalysis Workflow\nStep 1: Define Pair Universe\n\nObjective: Establish the pool of stocks to analyze for pair relationships.\n\nOption A: Sector-Based Screening (Recommended)\n\nSelect a specific sector to screen:\n\nTechnology\nFinancials\nHealthcare\nConsumer Discretionary\nIndustrials\nEnergy\nMaterials\nConsumer Staples\nUtilities\nReal Estate\nCommunication Services\n\nOption B: Custom Stock List\n\nUser provides specific tickers to analyze:\n\nExample: [\"AAPL\", \"MSFT\", \"GOOGL\", \"META\", \"NVDA\"]\n\n\nOption C: Industry-Specific\n\nNarrow focus to specific industry within sector:\n\nExample: \"Software\" within Technology sector\nExample: \"Regional Banks\" within Financials\n\nFiltering Criteria:\n\nMinimum market cap: $2B (mid-cap and above)\nMinimum average volume: 1M shares/day (liquidity requirement)\nActive trading: No delisted or inactive stocks\nSame exchange preference: Avoid cross-exchange complications\nStep 2: Retrieve Historical Price Data\n\nObjective: Fetch price history for correlation and cointegration analysis.\n\nData Requirements:\n\nTimeframe: 2 years (minimum 252 trading days)\nFrequency: Daily closing prices\nAdjustments: Adjusted for splits and dividends\nClean data: No gaps or missing values\n\nFMP API Endpoint:\n\nGET /v3/historical-price-full/{symbol}?apikey=YOUR_API_KEY\n\n\nData Validation:\n\nVerify consistent date ranges across all symbols\nRemove stocks with >10% missing data\nFill minor gaps with forward-fill method\nLog data quality issues\n\nScript Execution:\n\npython scripts/fetch_price_data.py --sector Technology --lookback 730\n\nStep 3: Calculate Correlation and Beta\n\nObjective: Identify candidate pairs with strong linear relationships.\n\nCorrelation Analysis:\n\nFor each pair of stocks (i, j) in the universe:\n\nCalculate Pearson correlation coefficient (ρ)\nCalculate rolling correlation (90-day window) for stability check\nFilter pairs with ρ >= 0.70 (strong positive correlation)\n\nCorrelation Interpretation:\n\nρ >= 0.90: Very strong correlation (best candidates)\nρ 0.70-0.90: Strong correlation (good candidates)\nρ 0.50-0.70: Moderate correlation (marginal)\nρ < 0.50: Weak correlation (exclude)\n\nBeta Calculation:\n\nFor each candidate pair (Stock A, Stock B):\n\nBeta = Covariance(A, B) / Variance(B)\n\n\nBeta indicates the hedge ratio:\n\nBeta = 1.0: Equal dollar amounts\nBeta = 1.5: $1.50 of B for every $1.00 of A\nBeta = 0.8: $0.80 of B for every $1.00 of A\n\nCorrelation Stability Check:\n\nCalculate correlation over multiple periods (6mo, 1yr, 2yr)\nRequire correlation to be stable (not deteriorating)\nFlag pairs where recent correlation < historical correlation by >0.15\nStep 4: Cointegration Testing\n\nObjective: Statistically validate long-term equilibrium relationship.\n\nWhy Cointegration Matters:\n\nCorrelation measures short-term co-movement\nCointegration proves long-term equilibrium relationship\nCointegrated pairs mean-revert predictably\nNon-cointegrated pairs may diverge permanently\n\nAugmented Dickey-Fuller (ADF) Test:\n\nFor each correlated pair:\n\nCalculate spread: Spread = Price_A - (Beta × Price_B)\nRun ADF test on spread series\nCheck p-value: p < 0.05 indicates cointegration (reject null hypothesis of unit root)\nExtract ADF statistic for strength ranking\n\nCointegration Interpretation:\n\np-value < 0.01: Very strong cointegration (★★★)\np-value 0.01-0.05: Moderate cointegration (★★)\np-value > 0.05: No cointegration (exclude)\n\nHalf-Life Calculation:\n\nEstimate mean-reversion speed:\n\nHalf-Life = -log(2) / log(mean_reversion_coefficient)\n\nHalf-life < 30 days: Fast mean-reversion (good for short-term trading)\nHalf-life 30-60 days: Moderate speed (standard)\nHalf-life > 60 days: Slow mean-reversion (long holding periods)\n\nPython Implementation:\n\nfrom statsmodels.tsa.stattools import adfuller\n\n# Calculate spread\nspread = price_a - (beta * price_b)\n\n# ADF test\nresult = adfuller(spread)\nadf_stat = result[0]\np_value = result[1]\n\n# Interpret\nis_cointegrated = p_value < 0.05\n\nStep 5: Spread Analysis and Z-Score Calculation\n\nObjective: Quantify current spread deviation from equilibrium.\n\nSpread Calculation:\n\nTwo common methods:\n\nMethod 1: Price Difference (Additive)\n\nSpread = Price_A - (Beta × Price_B)\n\n\nBest for: Stocks with similar price levels\n\nMethod 2: Price Ratio (Multiplicative)\n\nSpread = Price_A / Price_B\n\n\nBest for: Stocks with different price levels, easier interpretation\n\nZ-Score Calculation:\n\nMeasures how many standard deviations spread is from its mean:\n\nZ-Score = (Current_Spread - Mean_Spread) / Std_Dev_Spread\n\n\nZ-Score Interpretation:\n\nZ > +2.0: Stock A expensive relative to B (short A, long B)\nZ > +1.5: Moderately expensive (watch for entry)\nZ -1.5 to +1.5: Normal range (no trade)\nZ < -1.5: Moderately cheap (watch for entry)\nZ < -2.0: Stock A cheap relative to B (long A, short B)\n\nHistorical Spread Analysis:\n\nCalculate mean and std dev over 90-day rolling window\nPlot historical z-score distribution\nIdentify maximum historical z-score deviations\nCheck for structural breaks (spread regime change)\nStep 6: Generate Entry/Exit Recommendations\n\nObjective: Provide actionable trading signals with clear rules.\n\nEntry Conditions:\n\nConservative Approach (Z ≥ ±2.0):\n\nLONG Signal:\n- Z-score < -2.0 (spread 2+ std devs below mean)\n- Spread is mean-reverting (cointegration p < 0.05)\n- Half-life < 60 days\n→ Action: Buy Stock A, Short Stock B (hedge ratio = beta)\n\nSHORT Signal:\n- Z-score > +2.0 (spread 2+ std devs above mean)\n- Spread is mean-reverting (cointegration p < 0.05)\n- Half-life < 60 days\n→ Action: Short Stock A, Buy Stock B (hedge ratio = beta)\n\n\nAggressive Approach (Z ≥ ±1.5):\n\nLower threshold for more frequent trades\nHigher win rate but smaller avg profit per trade\nRequires tighter risk management\n\nExit Conditions:\n\nPrimary Exit: Mean Reversion (Z = 0)\n\nExit when spread returns to mean (z-score crosses 0)\n→ Close both legs simultaneously\n\n\nSecondary Exit: Partial Profit Take\n\nExit 50% when z-score reaches ±1.0\nExit remaining 50% at z-score = 0\n\n\nStop Loss:\n\nExit if z-score extends beyond ±3.0 (extreme divergence)\nRisk: Possible structural break in relationship\n\n\nTime-Based Exit:\n\nExit after 90 days if no mean-reversion\nPrevents holding broken pairs indefinitely\n\nStep 7: Position Sizing and Risk Management\n\nObjective: Determine dollar amounts for market-neutral exposure.\n\nMarket Neutral Sizing:\n\nFor a pair (Stock A, Stock B) with beta = β:\n\nEqual Dollar Exposure:\n\nIf portfolio size = $10,000 allocated to this pair:\n- Long $5,000 of Stock A\n- Short $5,000 × β of Stock B\n\nExample (β = 1.2):\n- Long $5,000 Stock A\n- Short $6,000 Stock B\n→ Market neutral, beta = 0\n\n\nPosition Sizing Considerations:\n\nTotal pair allocation: 10-20% of portfolio per pair\nMaximum pairs: 5-8 active pairs for diversification\nCorrelation across pairs: Avoid highly correlated pairs\n\nRisk Metrics:\n\nMaximum loss per pair: 2-3% of total portfolio\nStop loss trigger: Z-score > ±3.0 or -5% loss on spread\nPortfolio-level risk: Sum of all pair risks ≤ 10%\nStep 8: Generate Pair Analysis Report\n\nObjective: Create structured markdown report with findings and recommendations.\n\nReport Sections:\n\nExecutive Summary\n\nTotal pairs analyzed\nNumber of cointegrated pairs found\nTop 5 opportunities ranked by statistical strength\n\nCointegrated Pairs Table\n\nPair name (Stock A / Stock B)\nCorrelation coefficient\nCointegration p-value\nCurrent z-score\nTrade signal (Long/Short/None)\nHalf-life\n\nDetailed Analysis (Top 10 Pairs)\n\nPair description\nStatistical metrics\nCurrent spread position\nEntry/exit recommendations\nPosition sizing\nRisk assessment\n\nSpread Charts (Text-Based)\n\nHistorical z-score plot (ASCII art)\nEntry/exit levels marked\nCurrent position indicator\n\nRisk Warnings\n\nPairs with deteriorating correlation\nStructural breaks detected\nLow liquidity warnings\n\nFile Naming Convention:\n\npair_trade_analysis_[SECTOR]_[YYYY-MM-DD].md\n\n\nExample: pair_trade_analysis_Technology_2025-11-08.md\n\nQuality Standards\nStatistical Rigor\n\nMinimum Requirements for Valid Pair:\n\n✓ Correlation ≥ 0.70 over 2-year period\n✓ Cointegration p-value < 0.05 (ADF test)\n✓ Spread stationarity confirmed\n✓ Half-life < 90 days\n✓ No structural breaks in recent 6 months\n\nRed Flags (Exclude Pair):\n\nCorrelation dropped >0.20 in recent 6 months\nCointegration p-value > 0.05\nHalf-life increasing over time (mean-reversion weakening)\nSignificant corporate events (merger, spin-off, bankruptcy risk)\nLiquidity concerns (avg volume < 500K shares/day)\nPractical Considerations\n\nTransaction Costs:\n\nAssume 0.1% round-trip cost per leg\nTotal cost per pair = 0.4% (entry + exit, both legs)\nMinimum z-score threshold should exceed transaction costs\n\nShort Selling:\n\nVerify stock is shortable (not hard-to-borrow)\nFactor in short interest costs (borrow fees)\nMonitor short squeeze risk\n\nExecution:\n\nEnter/exit both legs simultaneously (avoid leg risk)\nUse limit orders to control slippage\nPre-locate shorts before entry\nAvailable Scripts\nscripts/find_pairs.py\n\nPurpose: Screen for cointegrated pairs within a sector or custom list.\n\nUsage:\n\n# Sector-based screening\npython scripts/find_pairs.py --sector Technology --min-correlation 0.70\n\n# Custom stock list\npython scripts/find_pairs.py --symbols AAPL,MSFT,GOOGL,META --min-correlation 0.75\n\n# Full options\npython scripts/find_pairs.py \\\n  --sector Financials \\\n  --min-correlation 0.70 \\\n  --min-market-cap 2000000000 \\\n  --lookback-days 730 \\\n  --output pairs_analysis.json\n\n\nParameters:\n\n--sector: Sector name (Technology, Financials, etc.)\n--symbols: Comma-separated list of tickers (alternative to sector)\n--min-correlation: Minimum correlation threshold (default: 0.70)\n--min-market-cap: Minimum market cap filter (default: $2B)\n--lookback-days: Historical data period (default: 730 days)\n--output: Output JSON file (default: stdout)\n--api-key: FMP API key (or set FMP_API_KEY env var)\n\nOutput:\n\n[\n  {\n    \"pair\": \"AAPL/MSFT\",\n    \"stock_a\": \"AAPL\",\n    \"stock_b\": \"MSFT\",\n    \"correlation\": 0.87,\n    \"beta\": 1.15,\n    \"cointegration_pvalue\": 0.012,\n    \"adf_statistic\": -3.45,\n    \"half_life_days\": 42,\n    \"current_zscore\": -2.3,\n    \"signal\": \"LONG\",\n    \"strength\": \"Strong\"\n  }\n]\n\nscripts/analyze_spread.py\n\nPurpose: Analyze a specific pair's spread behavior and generate trading signals.\n\nUsage:\n\n# Analyze specific pair\npython scripts/analyze_spread.py --stock-a AAPL --stock-b MSFT\n\n# Custom lookback period\npython scripts/analyze_spread.py \\\n  --stock-a JPM \\\n  --stock-b BAC \\\n  --lookback-days 365 \\\n  --entry-zscore 2.0 \\\n  --exit-zscore 0.5\n\n\nParameters:\n\n--stock-a: First stock ticker\n--stock-b: Second stock ticker\n--lookback-days: Analysis period (default: 365)\n--entry-zscore: Z-score threshold for entry (default: 2.0)\n--exit-zscore: Z-score threshold for exit (default: 0.0)\n--api-key: FMP API key\n\nOutput:\n\nCurrent spread analysis\nZ-score calculation\nEntry/exit recommendations\nPosition sizing\nHistorical z-score chart (text)\nReference Documentation\nreferences/methodology.md\n\nComprehensive guide to statistical arbitrage and pair trading:\n\nPair Selection Criteria: How to identify good pair candidates\nStatistical Tests: Correlation, cointegration, stationarity\nSpread Construction: Price difference vs price ratio approaches\nMean Reversion: Half-life calculation and interpretation\nRisk Management: Position sizing, stop losses, diversification\nCommon Pitfalls: Survivorship bias, look-ahead bias, overfitting\nreferences/cointegration_guide.md\n\nDeep dive into cointegration testing:\n\nWhat is Cointegration?: Intuitive explanation\nADF Test: Step-by-step procedure\nP-Value Interpretation: Statistical significance thresholds\nHalf-Life Estimation: AR(1) model approach\nStructural Breaks: Testing for regime changes\nPractical Examples: Case studies with real pairs\nIntegration with Other Skills\n\nSector Analyst Integration:\n\nUse Sector Analyst to identify sectors in rotation\nScreen for pairs within outperforming sectors\nPairs in leading sectors may have stronger trends\n\nTechnical Analyst Integration:\n\nConfirm pair entry/exit with individual stock technicals\nCheck support/resistance levels before entry\nValidate trend direction aligns with spread signal\n\nBacktest Expert Integration:\n\nFeed pair candidates to Backtest Expert for validation\nTest historical z-score entry/exit rules\nOptimize threshold parameters (entry z-score, stop loss)\nWalk-forward analysis for robustness\n\nMarket Environment Analysis Integration:\n\nAvoid pair trading during extreme volatility (VIX > 30)\nCorrelations break down in crisis periods\nPrefer pair trading in sideways/range-bound markets\n\nPortfolio Manager Integration:\n\nTrack multiple pair positions\nMonitor overall market-neutral exposure\nCalculate portfolio-level pair trading P/L\nRebalance hedge ratios periodically\nImportant Notes\nAll analysis and output in English\nStatistical foundation: No discretionary interpretation\nMarket neutral focus: Minimize directional beta exposure\nData quality critical: Garbage in, garbage out\nRequires FMP API key: Free tier sufficient for basic screening\nPython dependencies: pandas, numpy, scipy, statsmodels\nCommon Use Cases\n\nUse Case 1: Technology Sector Pairs\n\nUser: \"Find pair trading opportunities in tech stocks\"\n\nWorkflow:\n1. Screen Technology sector for stocks with market cap > $10B\n2. Calculate all pairwise correlations\n3. Filter pairs with correlation ≥ 0.75\n4. Run cointegration tests\n5. Identify current z-score extremes (|z| > 2.0)\n6. Generate top 10 pairs report\n\n\nUse Case 2: Specific Pair Analysis\n\nUser: \"Analyze AAPL and MSFT as a pair trade\"\n\nWorkflow:\n1. Fetch 2-year price history for AAPL and MSFT\n2. Calculate correlation and beta\n3. Test for cointegration\n4. Calculate current spread and z-score\n5. Generate entry/exit recommendation\n6. Provide position sizing guidance\n\n\nUse Case 3: Regional Bank Pairs\n\nUser: \"Screen for pairs among regional banks\"\n\nWorkflow:\n1. Filter Financials sector for industry = \"Regional Banks\"\n2. Exclude banks with <$5B market cap\n3. Calculate pairwise statistics\n4. Rank by cointegration strength\n5. Focus on pairs with half-life < 45 days\n6. Report top 5 mean-reverting pairs\n\nTroubleshooting\n\nProblem: No cointegrated pairs found\n\nSolutions:\n\nExpand universe (lower market cap threshold)\nRelax cointegration p-value to 0.10\nTry different sectors (Utilities often cointegrate well)\nIncrease lookback period to 3 years\n\nProblem: All z-scores near zero (no trade signals)\n\nSolutions:\n\nNormal market condition (pairs in equilibrium)\nCheck back later or expand universe\nLower entry threshold to ±1.5 instead of ±2.0\n\nProblem: Pair correlation broke down\n\nSolutions:\n\nCheck for corporate events (earnings, guidance changes)\nVerify no M&A activity or restructuring\nRemove pair from watchlist if structural break confirmed\nMonitor for 30 days before re-entering\nAPI Requirements\nRequired: FMP API key (free tier sufficient)\nRate Limits: ~250 requests/day on free tier\nData Usage: ~2 requests per symbol for 2-year history\nUpgrade: Professional plan ($29/mo) recommended for frequent screening\nResources\nFMP Historical Price API: https://site.financialmodelingprep.com/developer/docs/historical-price-full\nStock Screener API: https://site.financialmodelingprep.com/developer/docs/stock-screener-api\nStatsmodels Documentation: https://www.statsmodels.org/stable/index.html\nCointegration Paper: Engle & Granger (1987) - \"Co-Integration and Error Correction\"\n\nVersion: 1.0 Last Updated: 2025-11-08 Dependencies: Python 3.8+, pandas, numpy, scipy, statsmodels, requests"
  },
  "trust": {
    "sourceLabel": "tencent",
    "provenanceUrl": "https://clawhub.ai/Veeramanikandanr48/pair-trade-screener",
    "publisherUrl": "https://clawhub.ai/Veeramanikandanr48/pair-trade-screener",
    "owner": "Veeramanikandanr48",
    "version": "0.1.0",
    "license": null,
    "verificationStatus": "Indexed source record"
  },
  "links": {
    "detailUrl": "https://openagent3.xyz/skills/pair-trade-screener",
    "downloadUrl": "https://openagent3.xyz/downloads/pair-trade-screener",
    "agentUrl": "https://openagent3.xyz/skills/pair-trade-screener/agent",
    "manifestUrl": "https://openagent3.xyz/skills/pair-trade-screener/agent.json",
    "briefUrl": "https://openagent3.xyz/skills/pair-trade-screener/agent.md"
  }
}