본문으로 건너뛰기
Skillpedia
분석 및 스프레드시트37k · #7505

correlation-analysis

하는 일

이 스킬은 자산 사이의 상관관계와 공적분을 측정하도록 에이전트를 가르칩니다. 어떤 자산이 함께 움직이는지, 그 연결이 오래가는지 알고 싶은 트레이더와 포트폴리오 설계자를 위한 스킬입니다.

사용하는 경우

  • ✓선택한 자산과 함께 움직이는 자산을 찾고 싶을 때.
  • ✓두 자산이 장기적으로 연결되어 있는지 페어 트레이딩용으로 시험하고 싶을 때.
  • ✓함께 움직이는 정도에 따라 자산을 묶어 보고 싶은 경우.

스킬 링크

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

복사해서 AI(Claude, ChatGPT, Cursor)에 붙여넣고 지침을 따르도록 요청하세요.

사용 방법

가장 쉬운 방법입니다. 메시지를 복사해 AI에 붙여넣으세요. AI가 스킬을 읽고 지침을 따릅니다.

바로 붙여넣을 수 있는 메시지

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.
AI가 이런 스킬을 알아서 찾아 쓰길 원하시나요?무료 Skillpedia MCP를 설치하세요. 한 줄이면 작업마다 스킬 15,000+개 중에서 검색합니다.1분 만에 설치 →

AI에게 요청하는 예시

“이 종목과 함께 움직이는 종목을 찾아 주시고, 그중 어떤 쌍이 시간이 지나도 연결되어 있는지 시험해 주세요.”

매주 새 스킬 5개. 읽는 데 1분.

작동 방식

에이전트는 대상 자산과 비교 대상 자산들 사이의 상관관계를 계산하고, 가장 강한 짝을 남긴 뒤 공적분 검정으로 장기 연결을 확인합니다. 그다음 격차가 평균으로 돌아오는 데 걸리는 기간을 계산하고 페어 트레이딩 신호를 만듭니다.

기술 내용 (원본 SKILL.md)

작성자의 영어 원문을 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) /
자주 묻는 질문

상관관계와 공적분은 같은 것인가요?

아닙니다. 상관관계는 자산이 함께 움직이는 정도를 보여 주고, 공적분은 자산들이 장기 균형에 묶여 있는지를 검정합니다.

반감기는 무엇인가요?

짝을 이룬 자산 사이의 격차가 절반만큼 줄어드는 데 보통 걸리는 시간을 추정한 값입니다.

페어 트레이딩이 성공한다고 보장하나요?

아닙니다. 짝의 관계는 깨질 수 있으므로 신호를 시험하고 계속 모니터링해야 합니다.

상세 정보

작성자의 원본 설명

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

인기도

GitHub 스타
37k
순위
#7505
라이선스
MIT
업데이트
2026. 11. 1.

이 스킬이 유용한가요?

0

로그인 투표하려면 로그인하세요.

댓글

  • …

이 저장소의 다른 스킬

비슷한 스킬