Sign in

Covariance

Covariance is the average product of two variables' deviations from their means: positive when they rise together, negative when they move apart.

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

  1. Arrange the data as a table with one row per observation and one column per variable (or the reverse with rowvar set).
  2. Subtract each column's mean, so every value becomes a deviation.
  3. For each pair of columns, multiply the deviations row by row and sum the products.
  4. Divide by n−1n - 1 for a sample (ddof 1) or by nn for a whole population (ddof 0).
  5. Collect the results in a square matrix. The diagonal holds each variable's variance and the matrix is symmetric.
  6. 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

IfUse instead
You want a unit free strength between -1 and 1 to compare pairsCorrelation
There are many more variables than observationsA shrinkage estimate of the covariance matrix such as Ledoit-Wolf
The relationship is not linearSpearman rank correlation or mutual information

Math foundations

  1. Sample covariance

    cov⁡(x,y)=1n−1∑i=1n(xi−xˉ)(yi−yˉ)\operatorname{cov}(x, y) = \frac{1}{n-1} \sum_{i=1}^{n} (x_i - \bar{x})(y_i - \bar{y})

    The average product of deviations. Dividing by n−1n - 1 instead of nn makes the estimate unbiased for a sample, because the means were estimated from the same data.

  2. Variance as a special case

    cov⁡(x,x)=1n−1∑i=1n(xi−xˉ)2=sx2\operatorname{cov}(x, x) = \frac{1}{n-1} \sum_{i=1}^{n} (x_i - \bar{x})^{2} = s_x^{2}

    The covariance of a variable with itself is its variance. That is why the diagonal of a covariance matrix holds variances.

  3. Covariance matrix

    Σ=1n−1 Xc⊤Xc\Sigma = \frac{1}{n-1} \, X_c^{\top} X_c

    With the centred table XcX_c, one matrix product gives every pairwise covariance at once. Entry (i,j)(i, j) is the covariance of variables ii and jj.

  4. From covariance to correlation

    rij=ΣijΣii Σjjr_{ij} = \frac{\Sigma_{ij}}{\sqrt{\Sigma_{ii}\,\Sigma_{jj}}}

    Dividing by both standard deviations removes the units and gives a number between -1 and 1. This is what to_correlation computes.

  5. Positive semidefiniteness

    v⊤Σ v=var⁡(v⊤x)≥0for every vector vv^{\top} \Sigma \, v = \operatorname{var}\big(v^{\top} x\big) \ge 0 \quad \text{for every vector } v

    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

xi,yix_i, y_i
the i-th observation of the two variables
xˉ,yˉ\bar{x}, \bar{y}
the means of the two variables
nn
number of observations
XcX_c
the table with each column's mean subtracted, n rows by d columns
Σ\Sigma
the covariance matrix, d by d
sx2s_x^{2}
the variance of x
vv
any vector of d weights

Worked by hand

Four pairs: x=1,2,3,4x = 1, 2, 3, 4 and y=2,4,6,8y = 2, 4, 6, 8. The means are 2.5 and 5.

∑(xi−2.5)(yi−5)=(−1.5)(−3)+(−0.5)(−1)+(0.5)(1)+(1.5)(3)=10\sum (x_i - 2.5)(y_i - 5) = (-1.5)(-3) + (-0.5)(-1) + (0.5)(1) + (1.5)(3) = 10
cov⁡(x,y)=104−1=3.333\operatorname{cov}(x, y) = \frac{10}{4 - 1} = 3.333
sx2=53=1.667,sy2=203=6.667s_x^{2} = \frac{5}{3} = 1.667, \qquad s_y^{2} = \frac{20}{3} = 6.667
r=3.3331.667×6.667=3.3333.333=1r = \frac{3.333}{\sqrt{1.667 \times 6.667}} = \frac{3.333}{3.333} = 1

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

  1. 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.

  2. Why must the covariance matrix be symmetric, and why must its diagonal be non-negative?
    A way to think about it

    Swap xx and yy in the formula. Then set y=xy = x and look at what is being summed.

  3. 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.

  4. Two variables have a covariance of zero. Does that make them independent?
    A way to think about it

    Try xx symmetric around zero and y=x2y = x^{2}. Compute the products of deviations for a positive xx and its mirror image.

  5. 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.