correlation-analysis
하는 일
이 스킬은 자산 사이의 상관관계와 공적분을 측정하도록 에이전트를 가르칩니다. 어떤 자산이 함께 움직이는지, 그 연결이 오래가는지 알고 싶은 트레이더와 포트폴리오 설계자를 위한 스킬입니다.
사용하는 경우
- ✓선택한 자산과 함께 움직이는 자산을 찾고 싶을 때.
- ✓두 자산이 장기적으로 연결되어 있는지 페어 트레이딩용으로 시험하고 싶을 때.
- ✓함께 움직이는 정도에 따라 자산을 묶어 보고 싶은 경우.
스킬 링크
https://github.com/HKUDS/Vibe-Trading/blob/main/agent/src/skills/correlation-analysis/SKILL.md복사해서 AI(Claude, ChatGPT, Cursor)에 붙여넣고 지침을 따르도록 요청하세요.
사용 방법
가장 쉬운 방법입니다. 메시지를 복사해 AI에 붙여넣으세요. AI가 스킬을 읽고 지침을 따릅니다.
바로 붙여넣을 수 있는 메시지
Claude Code, Codex, Cursor용입니다. 프로젝트 폴더에서 실행하면 스킬이 설치됩니다.
SKILL.md를 다운로드해 에이전트의 스킬 폴더에 넣으세요.
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.
댓글
- …
이 저장소의 다른 스킬
vibe-trading
37k에이전트에게 백테스트, 팩터 분석, 옵션 가격 결정, 여러 시장의 시장 데이터를 포함하는 완전한 금융 연구 도구 모음을 제공합니다.
adr-hshare
37k에이전트에게 미국 ADR과 홍콩 주식처럼 여러 시장에 상장된 중국 기업의 가격을 비교하는 방법을 보여 줍니다.
akshare
37k에이전트가 API 키 없이 중국과 해외 주식, 선물, 외환, 경제 지표의 무료 시장 데이터를 가져오도록 돕습니다.
alpha-zoo
37k에이전트가 만들어진 주식 팩터 라이브러리를 둘러보고, 선택한 시장에서 팩터 묶음이 수익률을 얼마나 잘 예측하는지 시험하도록 돕습니다.
비슷한 스킬
gitcrawl
394k에이전트가 저장된 GitHub 이슈와 풀 리퀘스트 보관본을 검색하고, 중복 항목을 묶고, GitHub에서 현재 상태를 확인하도록 돕습니다.
slacrawl
394k에이전트가 로컬 Slack 보관본에서 메시지를 검색하고 개수를 세며, 보관본이 얼마나 최신인지 확인하고 필요할 때 새로 고치도록 돕습니다.
goplaces
394k에이전트가 Google Places로 장소를 검색하고, 세부 정보와 리뷰를 가져오고, 장소 이름을 확인하며, 스크립트용 JSON을 출력하도록 돕습니다.