Skip to content

做什么(One-liner)

N 个标的日收益的 N×N 相关矩阵,3 种估计方法:Pearson / Ledoit-Wolf shrinkage / OAS shrinkage。Batch Signals 面板多选 helper + portfolio diversification 诊断工具。

怎么用

Batch Signals / Canvas 拖 portfolio_correlation,填 symbols list(≥2)+ 可选 period(default '6mo')+ 可选 method(default 'pearson')。输出 N×N 矩阵 + shrinkage 系数(LW/OAS)。

典型用法:

symbols=[SPY, QQQ, IWM, EFA, TLT, GLD, DBC], period=1y, method=ledoit_wolf
→ 7×7 PSD 相关矩阵 + shrinkage_coef ≈ 0.08

核心公式

# Preprocessing:
returns = fetch_daily_pct_change(symbols, period)         # 60s cached
X = returns.values                                         # (T, N)

# Method branch:
if method == "pearson":
  M = np.corrcoef(X.T)
  shrinkage = null

elif method == "ledoit_wolf":
  cov, coef = sklearn.covariance.ledoit_wolf(X)
  M = diag_normalize(cov, clip=[-1, 1])
  shrinkage = coef

elif method == "oas":
  cov, coef = sklearn.covariance.oas(X)
  M = diag_normalize(cov, clip=[-1, 1])
  shrinkage = coef

# matrix round(4) on output

假设与适用场景

假设:日频 + yfinance auto_adjust + 至少 2 符号 + 60s cache + 100-符号 hard cap。

适用:美股/ETF/FX 组合多元化诊断、risk parity cov 前置、quarterly review 相关性快照。

不适用:tick、>100 symbols、<2 symbols、非线性相关、时变相关、copula。

输入 / 输出契约

{symbols: list, period: str, method: 'pearson'|'ledoit_wolf'|'oas'}{symbols, period, n_observations, matrix, dropped_symbols, truncated, method, shrinkage, windows}

Matrix round(4); shrinkage null for pearson。

已知局限

  1. Pearson 在 N/T 大时 rank-deficient(推荐 N/T ≥ 0.5 用 LW/OAS)
  2. Matrix round(4) 损失细粒度 shrinkage 差异
  3. 100-符号 hard cap(truncated flag 提示)
  4. Cache TTL 60s (freshness vs 合并)
  5. Symbol alias map hardcoded
  6. 零方差 columns 用 1.0 兜底(_fetch_returns 已过滤,但 defence-in-depth)
  7. 不自动推荐 method based on N/T ratio

参考文献

Pearson (1895) 原始 + Ledoit-Wolf (2004) shrinkage + Chen et al. (2010) OAS + Fama-French (1993) factor model 背景。详见 frontmatter。

Golden Test

tests/golden/fixtures/tier2/portfolio_correlation/3-method parametrized regression over synthetic 3-symbol returns。1e-10 tolerance post-round(4)。9 tests:

  • matches_reference[pearson] / [ledoit_wolf] / [oas] — 3 methods byte-equal
  • determinism — 5 reruns identical
  • diagonal_is_one — 所有方法对角线 = 1.0 contract
  • matrix_symmetric — 对称性 contract
  • rejects_single_symbol — < 2 → error
  • rejects_unknown_method — 非合法方法 → error
  • shrinkage_comparison — OAS > LW on small T/N ordering contract

Reference 是 _fetch_returns monkey-patched 的同步 3-symbol 合成序列(seed=42),绕过 yfinance。

Changelog

  • 1.0.0 (2026-04-20) — 首次 Active(Tier 2 batch 5)

Verifiable intelligence for the decisions that demand scrutiny.