Skip to content
Skillpedia
Analysis & spreadsheets37k · #7505

correlation-analysis

What it does

This skill teaches an agent to measure correlation and cointegration between assets. It is for traders and portfolio builders who want to know which assets move together and whether that link lasts.

When to use it

  • ✓When you want to find assets that move closely with a chosen asset.
  • ✓When you want to test whether two assets stay linked over the long run for pair trading.
  • ✓When you want to group assets by how they move together.

Skill link

https://github.com/HKUDS/Vibe-Trading/blob/main/agent/src/skills/correlation-analysis/SKILL.md

Copy it and paste it into your AI (Claude, ChatGPT or Cursor), asking it to follow the instructions.

How to use

The easiest way: copy the message and paste it into your AI. It reads the skill and follows the instructions.

Ready-to-paste message

Use this skill to help me: https://github.com/HKUDS/Vibe-Trading/blob/main/agent/src/skills/correlation-analysis/SKILL.md Read the SKILL.md file at that link and follow its instructions for my task.
Want your AI to find skills like this on its own?Install the free Skillpedia MCP: one line, and it searches 15,000+ skills before each task.Install in 1 minute →

Example of what to ask your AI

“Find stocks that move closely with this one, and test which of those pairs stay linked over time.”

5 new skills a week. 1 minute to read.

How it works

The agent calculates correlations between the target and a universe of assets, keeps the strongest matches, and runs cointegration tests to confirm a long-run link. It can then calculate how long a gap usually takes to close and produce a pair-trading signal.

Technical content (original SKILL.md)

Original text by the author, straight from GitHub.

Correlation and Cointegration Analysis

Overview

Correlation analysis is a foundational tool for pairs trading, portfolio construction, and risk management. This skill covers four analysis modes (co-movement discovery / return-correlation deep dive / sector clustering / realized correlation), a full cointegration-testing framework, cross-market linkage analysis, and the complete workflow from analytics to pair-trading signals.


Mode 1: Co-Movement Discovery

Use case: Given a target asset, scan a universe for highly correlated assets and build a candidate pool with similar industry or factor exposure, for use in pairs trading or substitute identification.

Workflow

1. Pull daily return series for the target asset and N candidates
2. Compute Pearson / Spearman correlations between the target and each candidate
3. Rank by correlation in descending order and keep Top-K (usually K=10-20)
4. Run cointegration tests on the Top-K set to retain pairs with real long-run equilibrium
5. Output the candidate pool and a correlation summary
import pandas as pd
import numpy as np
from scipy.stats import pearsonr, spearmanr

def scan_correlated_assets(
    target_returns: pd.Series,
    universe_returns: pd.DataFrame,
    top_k: int = 20,
    min_corr: float = 0.5,
    method: str = "pearson",
) -> pd.DataFrame:
    """Scan for assets that are highly correlated with the target asset.

    Args:
        target_returns: Daily return series for the target asset
        universe_returns: Candidate-universe return matrix, columns are symbols
        top_k: Number of top candidates to return
        min_corr: Minimum absolute-correlation threshold
        method: "pearson" or "spearman"

    Returns:
        A DataFrame containing symbol / corr / p_value / rank
    """
    aligned = universe_returns.dropna(axis=1, how="any")
    aligned, target_aligned = aligned.align(target_returns, join="inner", axis=0)

    results = []
    for col in aligned.columns:
        if method == "spearman":
            corr, p = spearmanr(target_aligned, aligned[col])
        else:
            corr, p = pearsonr(target_aligned, aligned[col])
        results.append({"symbol": col, "corr": corr, "p_value": p})

    df = pd.DataFrame(results)
    df = df[df["corr"].abs() >= min_corr].sort_values("corr", ascending=False)
    df["rank"] = range(1, len(df) + 1)
    return df.head(top_k).reset_index(drop=True)

Screening guidance:

Correlation Conclusion Follow-up Action
> 0.8 Strong same-direction co-movement Send to the cointegration test queue
0.6 - 0.8 Moderate co-movement Check industry / factor alignment before cointegration
< 0.6 Weak correlation Usually unsuitable for pairs trading
Negative and < -0.6 Strong inverse co-movement Can be used in hedged portfolios, but be careful with spread direction

Mode 2: Deep Return-Correlation Analysis

Use case: Run a full bivariate correlation study on two assets, including multiple correlation coefficients, Beta / R², rolling correlation, and spread Z-Score.

Core Metrics

import statsmodels.api as sm
from scipy.stats import pearsonr, spearmanr, kendalltau

def bivariate_correlation_analysis(
    y: pd.Series,
    x: pd.Series,
    rolling_window: int = 60,
) -> dict:
    """Run deep correlation analysis for two assets.

    Args:
        y: Daily return series of asset A
        x: Daily return series of asset B
        rolling_window: Rolling-window length in trading days

    Returns:
        Dict of correlation statistics
    """
    # Align the two series.
    df = pd.concat([y.rename("y"), x.rename("x")], axis=1).dropna()
    y_clean, x_clean = df["y"], df["x"]

    # Static correlations.
    pearson_r, pearson_p = pearsonr(y_clean, x_clean)
    spearman_r, spearman_p = spearmanr(y_clean, x_clean)
    kendall_r, kendall_p = kendalltau(y_clean, x_clean)

    # OLS: y = α + β·x
    x_const = sm.add_constant(x_clean)
    ols = sm.OLS(y_clean, x_const).fit()
    beta = ols.params["x"]
    alpha = ols.params["const"]
    r_squared = ols.rsquared

    # Rolling Pearson correlation.
    rolling_corr = y_clean.rolling(rolling_window).corr(x_clean)

    # Spread and Z-Score using the hedge ratio.
    spread = y_clean - beta * x_clean
    spread_mean = spread.rolling(rolling_window).mean()
    spread_std = spread.rolling(rolling_window).std()
    z_score = (spread - spread_mean) /
FAQ

Is correlation the same as cointegration?

No. Correlation shows how assets move together, while cointegration tests whether they stay tied to a long-run balance.

What is half-life here?

It is an estimate of how long a gap between paired assets usually takes to close halfway back.

Does it guarantee a pair trade works?

No. Pair relationships can break, so the signals need testing and monitoring.

Details

Original description by the author

Correlation and cointegration analysis — co-movement discovery, deep return-correlation analysis, sector clustering, realized correlation, Engle-Granger / Johansen cointegration, half-life, Kalman dynamic hedge ratio, cross-market linkage analysis, and pair-trading signal generation

repo: HKUDS/Vibe-Trading

Popularity

GitHub stars
37k
Ranking position
#7505
License
MIT
Updated
11/1/2026

Is this skill useful?

0

Sign in to vote.

Comments

  • …

More skills from this repository

Similar skills