What is covariance?
Covariance is a number that shows whether two variables tend to move in the same direction. It is positive when X and Y are usually above their own averages at the same time, negative when one tends to be above average while the other is below, and close to zero when there is no linear pattern.
Formally, it is the average product of each variable's deviation from its mean. Variance is the special case where both variables are the same, so Cov(X, X) = Var(X). Covariance carries the units of X multiplied by the units of Y, which is why its size is hard to read on its own. Pearson correlation removes the units by dividing by the two standard deviations.
This page is about the statistical quantity. It has no connection to the coefficient of variation, which is a standard deviation divided by a mean and is sometimes abbreviated CV or COV.
Covariance formula
There are two versions, and the only difference is the divisor. Use n − 1 when your data is a sample from a larger group and n when the data is the whole group.
Sample covariance
Cov(X, Y) = Σ(xi − x̄)(yi − ȳ) / (n − 1)
Written sXY in many textbooks. Needs at least two pairs.
Population covariance
Cov(X, Y) = Σ(xi − μX)(yi − μY) / N
Written σXY. N is the number of members in the whole population.
Expected-value form
Cov(X, Y) = E[(X − E[X])(Y − E[Y])]
= E[XY] − E[X]E[Y]
Used for random variables and probability tables. The second line follows by expanding the product.
Computational shortcut
Cov(X, Y) = (Σxiyi − n·x̄·ȳ) / (n − 1)
Gives the same sample result. It loses precision when the values are large and close together, so the deviation form is safer in code.
Here n is the number of (x, y) pairs, x̄ and ȳ are the two sample means, and the sum runs over every pair. For the same numbers, the sample value is always n / (n − 1) times the population value. In the worked example below, 34 × 5 / 4 = 42.5.
How to calculate covariance by hand
Take five students, with x as hours studied and y as exam score. The values are chosen so that both means come out as whole numbers.
| Student | x | y | x − 6 | y − 75 | (x − 6)(y − 75) |
|---|---|---|---|---|---|
| 1 | 2 | 60 | −4 | −15 | 60 |
| 2 | 4 | 65 | −2 | −10 | 20 |
| 3 | 6 | 75 | 0 | 0 | 0 |
| 4 | 8 | 80 | 2 | 5 | 10 |
| 5 | 10 | 95 | 4 | 20 | 80 |
| Total | 30 | 375 | 0 | 0 | 170 |
Find the two means
x̄ = (2 + 4 + 6 + 8 + 10) / 5 = 6 and ȳ = (60 + 65 + 75 + 80 + 95) / 5 = 75.
Subtract the mean from every value
These are the deviations in columns 4 and 5. Each column adds to zero, which is a quick check on the arithmetic.
Multiply each pair of deviations
The products are 60, 20, 0, 10 and 80.
Add the products
Σ(x − x̄)(y − ȳ) = 60 + 20 + 0 + 10 + 80 = 170.
Divide by n − 1 or n
Sample covariance = 170 / (5 − 1) = 42.5. Population covariance = 170 / 5 = 34.
Read the sign and check with correlation
The positive sign means students who studied more hours tended to score higher. The sample standard deviations are sX = 3.1623 and sY = 13.6931, so r = 42.5 / (3.1623 × 13.6931) = 0.9815.
Sample covariance 42.5, population covariance 34, correlation 0.9815. The shortcut formula agrees: Σxy = 2,420 and n·x̄·ȳ = 5 × 6 × 75 = 2,250, so (2,420 − 2,250) / 4 = 42.5.
Sample vs population covariance
Pick population covariance when the data contains every member of the group you are describing, for example all twelve monthly figures of a year you are reporting on. Pick sample covariance when the data is a subset used to estimate something about a larger group, which is the usual case in surveys, experiments and coursework.
A sample mean sits closer to the sample's own values than the true population mean would, so dividing the squared-deviation sums by n understates the spread. Dividing by n − 1 corrects for that and is known as Bessel's correction. The same reasoning is behind the population vs sample distinction for variance and standard deviation.
| Item | Sample covariance | Population covariance |
|---|---|---|
| Divisor | n − 1 | n (or N) |
| Common symbol | sXY or Cov(X, Y) | σXY |
| Minimum number of pairs | 2 | 1 |
| Excel function | COVARIANCE.S | COVARIANCE.P |
| Result for the five students | 42.5 | 34 |
The choice matters most for small data sets. With five pairs the sample value is 25% larger than the population value, and with 100 pairs the gap shrinks to about 1%.
How to interpret covariance
Positive, negative and zero covariance
| Sign | Meaning | Pattern in a scatter plot |
|---|---|---|
| Positive | Y tends to be higher when X is higher | Points run from lower left to upper right |
| Negative | Y tends to be lower when X is higher | Points run from upper left to lower right |
| Zero or near zero | No linear trend between X and Y | A shapeless cloud, or a curve with no overall tilt |
A scatter plot shows the sign immediately, and the calculator above draws one with the two means marked. You can build your own with the scatter plot maker.
Why the size of covariance is hard to read
Rescaling a variable rescales the covariance by the same factor, even though the relationship is unchanged. Take six people with heights of 160, 165, 170, 175, 180 and 185 cm and weights of 58, 60, 68, 70, 78 and 77 kg.
| Units (height, weight) | Sample covariance | Correlation r |
|---|---|---|
| Centimetres, kilograms | 75.5 | 0.9682 |
| Metres, kilograms | 0.755 | 0.9682 |
| Inches, pounds | 65.53 | 0.9682 |
The relationship is identical in all three rows, yet the covariance ranges from 0.755 to 75.5. Correlation stays at 0.9682 because it has no units. Covariance does have a ceiling: its absolute value can never exceed sX × sY. That ceiling changes with the data, so there is no universal cutoff such as 1.
Zero covariance does not prove independence
Covariance only picks up linear co-movement. Let X be −1, 0 or 1 with probability 1/3 each, and let Y = X2. Then E[X] = 0 and E[XY] = E[X3] = 0, so Cov(X, Y) = 0, yet Y is completely determined by X. The reverse statement does hold: if X and Y are independent and have finite variances, their covariance is zero.
Outliers can dominate the result
One extreme pair adds one very large product to the sum. In the five-student example, change the last score from 95 to 200. The sample covariance jumps from 42.5 to 147.5, while the correlation falls from 0.9815 to 0.7950 because the standard deviation of y grows even faster. Look at the plot before reporting either number, and see the guide to outliers for ways to spot them.
Covariance vs correlation
Correlation is covariance rescaled to the range −1 to 1: r = Cov(X, Y) / (sX × sY). Dividing by both standard deviations removes the units, so r is the same in centimetres or inches. Another way to see it is that r equals the covariance of the two z-scores.
| Property | Covariance | Pearson correlation |
|---|---|---|
| Symbol | Cov(X, Y), sXY, σXY | r, ρ |
| Range | No fixed range; limited by sX × sY | −1 to 1 |
| Units | Units of X times units of Y | None |
| Changes when a variable is rescaled | Yes | No |
| Shows direction | Yes | Yes |
| Shows strength | No | Yes, for linear relationships |
| Typical use | Covariance matrices, portfolio variance, PCA, regression slopes | Reporting and comparing relationships |
The two are linked to regression as well. The least-squares slope of Y on X is Cov(X, Y) / Var(X), which is covered in the slope and intercept guide. To move between covariance and correlation, use the fourth tab of the calculator or the correlation calculator. If your correlation is rank-based, see Pearson vs Spearman, and remember that neither number shows causation.
Covariance of two random variables
For two discrete random variables with a joint probability table, covariance uses expected values: Cov(X, Y) = E[XY] − E[X]E[Y]. Each expected value is a probability-weighted sum over the table.
| X \ Y | Y = 1 | Y = 2 | P(X = x) |
|---|---|---|---|
| X = 1 | 0.20 | 0.05 | 0.25 |
| X = 2 | 0.15 | 0.20 | 0.35 |
| X = 3 | 0.05 | 0.35 | 0.40 |
| P(Y = y) | 0.40 | 0.60 | 1.00 |
E[X] and E[Y]
E[X] = 1(0.25) + 2(0.35) + 3(0.40) = 2.15. E[Y] = 1(0.40) + 2(0.60) = 1.6.
E[XY]
Multiply x, y and the probability in each cell, then add: 0.20 + 0.10 + 0.30 + 0.80 + 0.15 + 2.10 = 3.65.
Covariance
Cov(X, Y) = 3.65 − 2.15 × 1.6 = 3.65 − 3.44 = 0.21.
The variances are Var(X) = 0.6275 and Var(Y) = 0.24, so the correlation is ρ = 0.21 / √(0.6275 × 0.24) = 0.5411. For independent variables the joint probability factors into the product of the two marginals, which forces E[XY] = E[X]E[Y] and a covariance of zero. See the expected value guide for the sums used here, or the expected value calculator for a single variable.
Covariance matrix
With k variables, the covariance matrix is a k × k table whose entry in row i and column j is Cov(Xi, Xj). The diagonal holds the variances, and the matrix is symmetric because Cov(Xi, Xj) = Cov(Xj, Xi). It is also positive semi-definite, which is what allows methods such as principal component analysis to take its eigenvectors.
For an example, add a third variable to the five students: the number of practice tests taken (3, 5, 4, 7 and 8). The sample covariance matrix is:
| Hours | Score | Tests | |
|---|---|---|---|
| Hours | 10 | 42.5 | 6 |
| Score | 42.5 | 187.5 | 25 |
| Tests | 6 | 25 | 4.3 |
Dividing each entry by the product of the two standard deviations gives the correlation matrix, which has ones on the diagonal: 0.9815 for hours and score, 0.9150 for hours and tests, and 0.8805 for score and tests. The third tab of the calculator produces both matrices from pasted data. The same matrix feeds into multiple linear regression, where the covariances between predictors drive the coefficient estimates.
Covariance in finance
Portfolio risk depends on how asset returns move together. For two assets with weights w1 and w2, the variance of the portfolio return is
σp2 = w12σ12 + w22σ22 + 2·w1·w2·Cov(R1, R2)Take a 60/40 split between two assets whose returns have standard deviations of 20% and 10%. The table shows how the portfolio's standard deviation falls as the covariance falls.
| Correlation | Cov(R1, R2) | Portfolio std dev |
|---|---|---|
| 1.0 | 0.0200 | 16.00% |
| 0.3 | 0.0060 | 13.74% |
| 0.0 | 0.0000 | 12.65% |
| −0.5 | −0.0100 | 10.58% |
At a correlation of 1 the portfolio standard deviation equals the weighted average, 0.6 × 20% + 0.4 × 10% = 16%. Any lower covariance pulls it below that, which is the arithmetic behind diversification. In practice the covariances are estimated from historical return series with the sample formula, and they shift over time. These numbers are invented for illustration and are not investment advice. The finance articles on portfolio diversification statistics and statistics in risk management cover the wider context.
Covariance in Excel, Google Sheets, Python, R and TI-84
Software defaults differ, which is the usual reason a hand calculation and a spreadsheet disagree. Microsoft's COVARIANCE.S page gives =COVARIANCE.S({2,4,8},{5,11,12}) = 9.6667 as a test case, and you can paste those two lists into the calculator to confirm it.
| Tool | Sample covariance | Population covariance | Note |
|---|---|---|---|
| Excel | =COVARIANCE.S(A2:A6, B2:B6) | =COVARIANCE.P(A2:A6, B2:B6) | The older COVAR is kept for compatibility and returns the population version. |
| Google Sheets | =COVARIANCE.S(data_y, data_x) | Multiply the sample result by (n − 1) / n | Google's help page for COVAR does not say which version it returns, so test it against a hand example first. |
| Python (NumPy) | np.cov(x, y)[0, 1] | np.cov(x, y, ddof=0)[0, 1] | Returns the full 2 × 2 matrix. Each row is a variable unless you pass rowvar=False. |
| Python (pandas) | df["x"].cov(df["y"]) | df["x"].cov(df["y"], ddof=0) | df.cov() returns the whole matrix with the sample divisor. |
| R | cov(x, y) | cov(x, y) * (n - 1) / n | R divides by n − 1. |
| TI-84 | r × Sx × Sy | Multiply the sample result by (n − 1) / n | No direct covariance command. Get Sx and Sy from 2-Var Stats and r from LinReg(ax+b) with DiagnosticOn. |
The same five students in code. In every case the sample result is 42.5 and the population result is 34.
# Python
import numpy as np
x = [2, 4, 6, 8, 10]
y = [60, 65, 75, 80, 95]
np.cov(x, y) # [[ 10. , 42.5], [ 42.5, 187.5]] sample
np.cov(x, y, ddof=0) # [[ 8. , 34. ], [ 34. , 150. ]] population
# R
x <- c(2, 4, 6, 8, 10); y <- c(60, 65, 75, 80, 95)
cov(x, y) # 42.5
# Excel, with x in A2:A6 and y in B2:B6
=COVARIANCE.S(A2:A6, B2:B6) # 42.5
=COVARIANCE.P(A2:A6, B2:B6) # 34For more on the Python side, see the statistics for Python article.
Properties of covariance
| Property | Statement | What it is used for |
|---|---|---|
| Symmetry | Cov(X, Y) = Cov(Y, X) | Order of the two variables does not matter |
| Relation to variance | Cov(X, X) = Var(X) | The diagonal of a covariance matrix |
| Scaling and shifting | Cov(aX + b, cY + d) = ac · Cov(X, Y) | Explains the unit effect: shifts change nothing, scale factors multiply |
| Additivity | Cov(X + Z, Y) = Cov(X, Y) + Cov(Z, Y) | Splitting a sum into parts |
| Variance of a sum | Var(X + Y) = Var(X) + Var(Y) + 2 Cov(X, Y) | Portfolio variance, error propagation |
| Independence | Independent implies Cov(X, Y) = 0, but not the reverse | See the Y = X2 example above |
| Upper bound | |Cov(X, Y)| ≤ sX sY | Cauchy–Schwarz inequality; it is why |r| ≤ 1 |
In time series, the covariance of a series with a time-shifted copy of itself is called autocovariance, and the covariance between two different series at a given lag is called cross-covariance. Both use the same product-of-deviations idea as above.
Common mistakes
- Sorting or filtering one list without the other breaks the pairing and changes the answer. Row i of X must stay with row i of Y.
- Software defaults differ. Excel's
COVARandCOVARIANCE.Pdivide by n, whilenp.cov, R'scovandCOVARIANCE.Sdivide by n − 1, so results will not match until you align them. - Calling
np.cov(data)on a table with variables in columns returns a matrix of the wrong shape, because NumPy treats each row as a variable. Passrowvar=False. - A large covariance does not mean a strong relationship. Two variables measured in dollars and grams can produce a huge covariance from a weak association, so check r.
- Covariance misses curved relationships. A U-shaped pattern can have a covariance near zero.
- The conversion Cov = r × sX × sY needs standard deviations with the same divisor as the covariance you want.
Related calculators and guides
Covariance connects descriptive statistics to correlation and regression. These pages cover the topics on either side.
Sources
- Microsoft Support. COVARIANCE.S function, COVARIANCE.P function and COVAR function.
- Google Docs Editors Help. COVARIANCE.S function and COVAR function.
- NumPy documentation. numpy.cov.
- pandas documentation. DataFrame.cov.
- R documentation. cor, var and cov in the stats package.
- Texas Instruments Education. Calculating covariance on TI graphing calculators.
Frequently asked questions
What is covariance?
Covariance measures whether two variables tend to move together. A positive value means they usually rise and fall together, a negative value means one tends to rise when the other falls, and a value near zero means there is no linear trend. Its size depends on the units of both variables, so it is usually read alongside the correlation coefficient.
What is the formula for covariance?
For a sample, Cov(X, Y) = Σ(xi − x̄)(yi − ȳ) / (n − 1). For a population, divide by N instead. The expected-value form is Cov(X, Y) = E[XY] − E[X]E[Y]. For x = 2, 4, 6, 8, 10 and y = 60, 65, 75, 80, 95 the sample covariance is 42.5.
Should I use sample or population covariance?
Use population covariance (divide by n) when your data includes every member of the group you are describing. Use sample covariance (divide by n − 1) when the data is a subset used to estimate a larger group, which covers most surveys, experiments and coursework. The sample value equals n / (n − 1) times the population value.
How do I calculate covariance in Excel?
Use =COVARIANCE.S(array1, array2) for a sample and =COVARIANCE.P(array1, array2) for a population. The older COVAR function returns the population version. For example, =COVARIANCE.S({2,4,8},{5,11,12}) returns 9.6667.
What does negative covariance mean?
Negative covariance means that when one variable is above its mean, the other tends to be below its own mean. A used car's age and its resale price are a typical example. The size of the number says nothing about strength unless you also check the correlation.
Does zero covariance mean the variables are independent?
No. Independent variables have zero covariance, but zero covariance does not imply independence. If X is −1, 0 or 1 with equal probability and Y = X2, the covariance is 0 even though Y is completely determined by X.
What is the difference between covariance and correlation?
Correlation is covariance divided by the product of the two standard deviations, r = Cov(X, Y) / (sX × sY). That makes it unit-free and limited to the range −1 to 1. Covariance keeps the units of X times the units of Y and has no fixed range, which makes it useful as an input to other calculations.
Why is covariance not limited to between −1 and 1?
Covariance is not standardized, so rescaling a variable rescales the covariance. The same height and weight data give 75.5 in centimetres and kilograms but 0.755 in metres and kilograms. The only bound is that the absolute covariance cannot exceed the product of the two standard deviations.
What is a covariance matrix?
A covariance matrix is a square table of every pairwise covariance among k variables. The diagonal holds the variances and the matrix is symmetric. It is used in principal component analysis, multivariate regression and portfolio risk. The Covariance matrix tab above builds one from pasted data.
How do I get covariance from correlation?
Multiply the correlation by the two standard deviations: Cov(X, Y) = r × sX × sY. With r = 0.8, sX = 5 and sY = 12 the covariance is 48. Use standard deviations that match the covariance you want, sample or population.