Chuyển đến nội dung
Skillpedia
Phân tích và bảng tính37k · #7505

correlation-analysis

Skill này làm gì

Skill này dạy agent đo tương quan và đồng liên kết giữa các tài sản. Skill dành cho trader và người xây dựng danh mục muốn biết tài sản nào chuyển động cùng nhau và liên kết đó có bền không.

Khi nào nên dùng

  • ✓Khi bạn muốn tìm các tài sản chuyển động sát với một tài sản đã chọn.
  • ✓Khi bạn muốn kiểm tra xem hai tài sản có gắn kết lâu dài để giao dịch cặp hay không.
  • ✓Khi bạn muốn nhóm tài sản theo cách chúng chuyển động cùng nhau.

Liên kết skill

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

Sao chép rồi dán vào AI của bạn (Claude, ChatGPT hoặc Cursor) và nhờ nó làm theo hướng dẫn.

Cách dùng

Cách dễ nhất: sao chép tin nhắn và dán vào AI của bạn. AI sẽ đọc skill và làm theo hướng dẫn.

Tin nhắn có sẵn để dán

Hãy dùng skill này để giúp tôi: https://github.com/HKUDS/Vibe-Trading/blob/main/agent/src/skills/correlation-analysis/SKILL.md Đọc tệp SKILL.md tại liên kết đó và làm theo hướng dẫn cho việc của tôi.
Bạn muốn AI tự tìm những skill như thế này?Cài MCP Skillpedia miễn phí: chỉ một dòng, và AI sẽ tìm trong 15.000+ skill trước mỗi việc.Cài đặt trong 1 phút →

Ví dụ cách nhờ AI

“Tìm các cổ phiếu chuyển động sát với cổ phiếu này, rồi kiểm tra cặp nào trong số đó vẫn gắn kết theo thời gian.”

5 skill mới mỗi tuần. Đọc chỉ 1 phút.

Cách hoạt động

Agent tính tương quan giữa mục tiêu và một nhóm tài sản, giữ lại những cặp mạnh nhất, rồi chạy kiểm định đồng liên kết để xác nhận mối liên hệ dài hạn. Sau đó nó có thể tính thời gian khoảng cách thường khép lại và tạo tín hiệu giao dịch cặp.

Nội dung kỹ thuật (SKILL.md gốc)

Lấy nguyên văn từ GitHub, do tác giả viết bằng tiếng Anh.

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) /
Câu hỏi thường gặp

Tương quan có giống đồng liên kết không?

Không. Tương quan cho thấy các tài sản chuyển động cùng nhau thế nào, còn đồng liên kết kiểm tra xem chúng có bám vào một cân bằng dài hạn không.

Half-life ở đây là gì?

Đó là ước tính thời gian để khoảng cách giữa hai tài sản trong cặp thường thu hẹp được một nửa.

Skill có đảm bảo giao dịch cặp thành công không?

Không. Mối quan hệ giữa các cặp có thể đổ vỡ, nên tín hiệu cần được kiểm thử và theo dõi.

Chi tiết

Mô tả gốc của tác giả

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

Độ phổ biến

Sao GitHub
37k
Vị trí xếp hạng
#7505
Giấy phép
MIT
Cập nhật
1/11/2026

Skill này có hữu ích không?

0

Đăng nhập để bình chọn.

Bình luận

  • …

Thêm skill từ kho mã này

Skill tương tự