Lesson 4 of 15

Covariance & Correlation

Covariance & Correlation

Covariance measures how two variables move together. A positive covariance means they tend to move in the same direction; negative means opposite.

Sample covariance between XX and YY: Cov(X,Y)=1n1i=1n(xixˉ)(yiyˉ)\text{Cov}(X, Y) = \frac{1}{n-1} \sum_{i=1}^{n} (x_i - \bar{x})(y_i - \bar{y})

Pearson Correlation normalizes covariance to the range [1,1][-1, 1]: ρ=Cov(X,Y)sXsY\rho = \frac{\text{Cov}(X, Y)}{s_X \cdot s_Y}

where sXs_X and sYs_Y are the sample standard deviations.

A correlation of 1 means perfect positive linear relationship, -1 means perfect inverse, and 0 means no linear relationship.

In portfolio construction, correlation determines diversification benefit: assets with low or negative correlation reduce portfolio volatility.

Your Task

Implement:

  • covariance(xs, ys) — sample covariance
  • correlation(xs, ys) — Pearson correlation coefficient
Python runtime loading...
Loading...
Click "Run" to execute your code.