Overview
Take one observation and ask two questions: is its first value above or below the mean, and is its second? If both are above, or both below, the product of the two deviations is positive. If one is above and the other below, the product is negative. Covariance averages that product over all observations. A positive result means the variables tend to be high together. A negative one means one tends to be high when the other is low. Its size depends on the units of both variables, so it tells you direction clearly but strength only after rescaling to a correlation.
A short history
Covariance came out of the same late nineteenth century work on heredity as correlation, by Francis Galton and Karl Pearson, as the joint counterpart of variance: correlation is covariance rescaled by the two standard deviations. It became central to applied work when Harry Markowitz showed in 1952 that the risk of a portfolio depends on the covariances between its assets, and it underlies principal component analysis, the Kalman filter and the multivariate normal distribution.
How it works
- Arrange the data as a table with one row per observation and one column per variable (or the reverse with rowvar set).
- Subtract each column's mean, so every value becomes a deviation.
- For each pair of columns, multiply the deviations row by row and sum the products.
- Divide by for a sample (ddof 1) or by for a whole population (ddof 0).
- Collect the results in a square matrix. The diagonal holds each variable's variance and the matrix is symmetric.
- To compare strengths, call to_correlation, which divides each entry by the two standard deviations involved.
Watch out for
- The size of a covariance depends on the units. Measuring height in millimetres instead of metres multiplies it by 1000 without changing the relation.
- Covariance only captures straight-line co-movement. Two variables with a strong curved relation can have a covariance of zero.
- Outliers enter as large products of deviations, so one extreme row can dominate the whole estimate.
- With fewer observations than variables the covariance matrix is singular, meaning it cannot be inverted, which breaks methods that need its inverse.
- The template rejects tables that hold NaN, because dropping values pair by pair can produce a matrix that is not a valid covariance matrix.
Use cases
When to use it
As the input to PCA, Mahalanobis distance, Gaussian models and portfolio variance, or to see the direction of a linear relation. To compare how strong relations are, use correlation instead.
In industry
- Portfolio management
- Risk teams estimate a covariance matrix of asset returns and use it to compute the variance of a whole portfolio, following Markowitz's mean variance approach.
- Navigation and robotics
- A Kalman filter carries a covariance matrix that describes the uncertainty of position and velocity estimates and how those uncertainties are linked.
- Dimensionality reduction
- Principal component analysis starts from the covariance matrix of the features and finds the directions in which the data vary most.
Choosing it: what must hold
- Two numeric variables observed together on the same units.
- Variables whose units and scales you intend to keep, since covariance changes when a variable is rescaled.
- Data without extreme outliers, because a single extreme pair can dominate the average product.
When to choose something else
| If | Use instead |
|---|---|
| You want a unit free strength between -1 and 1 to compare pairs | Correlation |
| There are many more variables than observations | A shrinkage estimate of the covariance matrix such as Ledoit-Wolf |
| The relationship is not linear | Spearman rank correlation or mutual information |
Math foundations
Sample covariance
The average product of deviations. Dividing by instead of makes the estimate unbiased for a sample, because the means were estimated from the same data.
Variance as a special case
The covariance of a variable with itself is its variance. That is why the diagonal of a covariance matrix holds variances.
Covariance matrix
With the centred table , one matrix product gives every pairwise covariance at once. Entry is the covariance of variables and .
From covariance to correlation
Dividing by both standard deviations removes the units and gives a number between -1 and 1. This is what to_correlation computes.
Positive semidefiniteness
Any weighted sum of the variables has a variance, and a variance cannot be negative. So a valid covariance matrix has no negative eigenvalue, which is_positive_semidefinite checks.
Symbols
- the i-th observation of the two variables
- the means of the two variables
- number of observations
- the table with each column's mean subtracted, n rows by d columns
- the covariance matrix, d by d
- the variance of x
- any vector of d weights
Worked by hand
Four pairs: and . The means are 2.5 and 5.
The covariance is 3.333 in units of x times units of y. Rescaled, the correlation is exactly 1, because y is twice x.
Visual example
Loading the example.
Try this
- Drag the top right point down to the bottom right corner: its rectangle changes colour and the covariance falls.
- Switch the unit of x to millimetres: the covariance grows a thousandfold while r does not change.
- Add points at the lower right until the negative area outweighs the positive and the sign flips.
Code sample
import numpy as np
from impl import Covariance
from config import CovarianceConfig
cov = Covariance(CovarianceConfig(ddof=1))
print(cov.covariance([1, 2, 3, 4], [2, 4, 6, 8])) # 3.3333
table = np.random.default_rng(0).normal(size=(100, 3)) # 100 observations of 3 variables
c = cov.matrix(table) # shape (3, 3)
print(Covariance.to_correlation(c))Read the implementation (74 lines)
"""Covariance of two variables and the covariance matrix of a table, with optional frequency weights.
NumPy only. The matrix is computed from centred data as X_c^T W X_c / (sum(w) - ddof), which keeps it symmetric
and positive semi-definite by construction.
"""
from __future__ import annotations
import numpy as np
try:
from .config import CovarianceConfig
except ImportError: # run from the template's own folder
from config import CovarianceConfig
class Covariance:
"""Sample or population covariance."""
def __init__(self, config: CovarianceConfig | None = None) -> None:
self.config = config or CovarianceConfig()
def matrix(self, table, weights=None) -> np.ndarray:
"""Covariance matrix.
table: shape (n, d) with columns as variables (or (d, n) when config.rowvar is true).
weights: optional shape (n,), non-negative frequency weights: a row with weight 3 counts as three rows.
Returns shape (d, d); entry [i, j] is the covariance of variables i and j, the diagonal holds variances.
"""
x = np.asarray(table, dtype=float)
if x.ndim != 2:
raise ValueError(f"table must be 2-D, got shape {x.shape}")
if self.config.rowvar:
x = x.T
if np.isnan(x).any():
raise ValueError("table holds NaN; drop or fill missing values first")
n = x.shape[0]
w = np.ones(n) if weights is None else np.asarray(weights, dtype=float).ravel()
if w.size != n:
raise ValueError(f"weights must have one entry per observation ({n}), got {w.size}")
if (w < 0).any():
raise ValueError("weights must be non-negative")
total = w.sum()
if total - self.config.ddof <= 0:
raise ValueError("not enough observations for the chosen ddof")
mean = (w[:, None] * x).sum(axis=0) / total
centred = x - mean
return (centred * w[:, None]).T @ centred / (total - self.config.ddof)
def covariance(self, x, y, weights=None) -> float:
"""Covariance of two variables. x, y: shape (n,). weights: optional shape (n,) frequency weights."""
x = np.asarray(x, dtype=float).ravel()
y = np.asarray(y, dtype=float).ravel()
if x.size != y.size:
raise ValueError(f"x and y must have the same length, got {x.size} and {y.size}")
columns = Covariance(CovarianceConfig(ddof=self.config.ddof, rowvar=False))
return float(columns.matrix(np.column_stack([x, y]), weights)[0, 1])
@staticmethod
def to_correlation(cov) -> np.ndarray:
"""Turn a covariance matrix of shape (d, d) into the correlation matrix cov[i, j] / (sd_i * sd_j)."""
cov = np.asarray(cov, dtype=float)
sd = np.sqrt(np.diag(cov))
if (sd == 0).any():
raise ValueError("a variable with zero variance has no correlation")
return cov / np.outer(sd, sd)
@staticmethod
def is_positive_semidefinite(cov, tol: float = 1e-10) -> bool:
"""True when the matrix is symmetric with no eigenvalue below -tol times its largest eigenvalue."""
cov = np.asarray(cov, dtype=float)
if cov.ndim != 2 or cov.shape[0] != cov.shape[1] or not np.allclose(cov, cov.T):
return False
eigenvalues = np.linalg.eigvalsh(cov)
return bool(eigenvalues.min() >= -tol * max(1.0, abs(eigenvalues.max())))- Repository
- Not published yet
- Needs
- Python 3.10 and NumPy
- Tests
- 8, run with
python3 -m unittest -v
Practice
Call Covariance().covariance on the four pairs above. Then multiply y by 100 and call it again to see the covariance scale while the relation is unchanged. Build a table of 100 rows and 3 columns, call matrix, pass the result to Covariance.to_correlation, and confirm with is_positive_semidefinite that it is a valid covariance matrix.
Check on learning
- The covariance of height and weight is 12 in one study and 1200 in another. Can you conclude that the relation is stronger in the second study?
A way to think about it
Check the units first. Then ask which quantity is unchanged when you switch from metres to centimetres.
- Why must the covariance matrix be symmetric, and why must its diagonal be non-negative?
A way to think about it
Swap and in the formula. Then set and look at what is being summed.
- You have 50 observations of 200 variables. What goes wrong when a method tries to invert the covariance matrix, and why?
A way to think about it
The centred table has at most 49 independent rows. Think about how many directions can have non-zero variance.
- Two variables have a covariance of zero. Does that make them independent?
A way to think about it
Try symmetric around zero and . Compute the products of deviations for a positive and its mirror image.
- A portfolio holds two assets in equal parts. How does the covariance between them change the risk of the portfolio compared with holding either one alone?
A way to think about it
Write the variance of the sum as two variances plus twice the covariance, and consider a negative covariance.