Workspace IndexMath › Day 21

Risk/Portfolio Matrices (Covariance, Correlation) TODO

Math · Day 21 / 52 · September — Linear Algebra (Day 18-26)

Concept

When you view multiple assets' returns as a vector, the covariance matrix is the symmetric positive semi-definite matrix collecting the degree of co-movement between every pair. The correlation matrix normalizes each entry by dividing by the standard deviations, removing scale so values become comparable between -1 and 1. For a portfolio weight vector w, the variance is computed as a quadratic form obtained by multiplying the covariance matrix by w on both sides, and this value shrinks below the weighted sum of individual variances the more you mix in assets with low or negative correlation. This is the mathematical essence of diversification. Eigendecomposition shows that the direction of large eigenvalues corresponds to common risk factors, and a core practical point is that with fewer samples the estimated covariance becomes unstable, requiring corrections like shrinkage.

When holding multiple positions at once, the real risk doesn't come from each individual position's volatility, but from the degree to which they move together.

Code & Formula

# 리스크·포트폴리오 행렬(공분산·상관) — 세 자산의 수익률에서 공분산·상관행렬을 구하고
# 포트폴리오 분산 = w^T Σ w 가 개별 분산의 가중합보다 작아지는 분산투자 효과를 확인한다.

import numpy as np

rng = np.random.default_rng(42)
n_days = 500

# 자산 A, B는 서로 강한 양의 상관, 자산 C는 거의 무상관이 되도록 수익률 생성
factor = rng.normal(0, 0.01, n_days)
returns_A = factor + rng.normal(0, 0.003, n_days)
returns_B = factor + rng.normal(0, 0.003, n_days)
returns_C = rng.normal(0, 0.01, n_days)
R = np.vstack([returns_A, returns_B, returns_C])  # shape (3, n_days)

cov = np.cov(R)
corr = np.corrcoef(R)
print("공분산 행렬 Σ:\n", np.round(cov, 6))
print("\n상관계수 행렬:\n", np.round(corr, 3))

w = np.array([1 / 3, 1 / 3, 1 / 3])
portfolio_var = w @ cov @ w  # 이차형식 w^T Σ w
weighted_avg_var = w @ np.diag(cov)  # 상관을 무시하고 개별 분산만 가중합한 값

print(f"\n동일가중 포트폴리오 분산 (w^T Σ w) = {portfolio_var:.6f}")
print(f"상관 무시한 개별분산 가중합          = {weighted_avg_var:.6f}")
print(f"→ 실제 포트폴리오 분산이 더 {'작음' if portfolio_var < weighted_avg_var else '크거나 같음'}: "
      f"C가 A,B와 무상관이라 분산투자 효과가 발생")

Exercise

Compute the covariance and correlation matrices from the daily returns of three or four assets, then numerically search for the weights that minimize portfolio variance as you vary them.

Practical Connection

In prediction markets, positions across multiple markets become correlated whenever the underlying events overlap, so summing each market's risk independently underestimates the actual exposure.

If you study this on a given day, add a note link and a ✅ to this line in the source curriculum (docs/knowledge/math-50-curriculum.md) and this spot will lead straight to the note body. You can also write directly on this page — but regenerating overwrites it, so it's safer to keep anything you want to save as markdown under docs/algorithms/.


한국어

리스크·포트폴리오 행렬(공분산·상관) TODO

Math · Day 21 / 52 · 9월 — 선형대수 (Day 18–26)

개념

여러 자산의 수익률을 벡터로 볼 때, 공분산 행렬은 각 쌍의 동조 정도를 모아 놓은 대칭 양의 준정부호 행렬이다. 상관계수 행렬은 각 성분을 표준편차로 나눠 정규화한 것으로, 스케일을 제거해 -1에서 1 사이 값으로 비교 가능하게 만든다. 포트폴리오 비중 벡터 w에 대해 분산은 w에 공분산 행렬을 양쪽에서 곱한 이차형식으로 계산되며, 상관이 낮거나 음수인 자산을 섞을수록 이 값이 개별 분산의 가중합보다 작아진다. 이것이 분산투자 효과의 수학적 정체이다. 고유분해를 하면 큰 고유값 방향이 공통 위험 요인이 되고, 표본이 적을수록 추정 공분산이 불안정해 축소(shrinkage) 같은 보정이 필요하다는 점도 실무의 핵심이다.

여러 포지션을 동시에 들고 있을 때 진짜 위험은 각 포지션의 변동성이 아니라 그들이 함께 움직이는 정도에서 나온다.

코드 · 수식

# 리스크·포트폴리오 행렬(공분산·상관) — 세 자산의 수익률에서 공분산·상관행렬을 구하고
# 포트폴리오 분산 = w^T Σ w 가 개별 분산의 가중합보다 작아지는 분산투자 효과를 확인한다.

import numpy as np

rng = np.random.default_rng(42)
n_days = 500

# 자산 A, B는 서로 강한 양의 상관, 자산 C는 거의 무상관이 되도록 수익률 생성
factor = rng.normal(0, 0.01, n_days)
returns_A = factor + rng.normal(0, 0.003, n_days)
returns_B = factor + rng.normal(0, 0.003, n_days)
returns_C = rng.normal(0, 0.01, n_days)
R = np.vstack([returns_A, returns_B, returns_C])  # shape (3, n_days)

cov = np.cov(R)
corr = np.corrcoef(R)
print("공분산 행렬 Σ:\n", np.round(cov, 6))
print("\n상관계수 행렬:\n", np.round(corr, 3))

w = np.array([1 / 3, 1 / 3, 1 / 3])
portfolio_var = w @ cov @ w  # 이차형식 w^T Σ w
weighted_avg_var = w @ np.diag(cov)  # 상관을 무시하고 개별 분산만 가중합한 값

print(f"\n동일가중 포트폴리오 분산 (w^T Σ w) = {portfolio_var:.6f}")
print(f"상관 무시한 개별분산 가중합          = {weighted_avg_var:.6f}")
print(f"→ 실제 포트폴리오 분산이 더 {'작음' if portfolio_var < weighted_avg_var else '크거나 같음'}: "
      f"C가 A,B와 무상관이라 분산투자 효과가 발생")

연습

자산 서너 개의 일별 수익률로 공분산·상관 행렬을 계산하고, 비중을 바꿔가며 포트폴리오 분산이 최소가 되는 지점을 수치로 찾아보기.

실무 · Verex 연결

예측시장에서 여러 마켓의 포지션은 기초 사건이 겹치면 상관이 생기므로, 마켓별 리스크를 따로 더하는 방식은 실제 노출을 과소평가한다.

공부한 날 원본 커리큘럼(docs/knowledge/math-50-curriculum.md)의 이 줄에 노트 링크와 ✅ 를 붙이면, 이 자리는 노트 본문으로 바로 이어집니다. 노트 없이 이 페이지에 바로 적어도 됩니다 — 다만 다시 생성하면 덮어쓰이므로, 남길 글은 docs/algorithms/ 의 마크다운으로 쓰는 편이 안전합니다.

← 20. 유한체 GF(p) 위 선형대수 (12월 다리, 스레드 A)22. 고유값/고유벡터 →