Concept

Correlation

Correlation, also known as Pearson, Spearman, rolling, correlation matrix, is a Statistics concept. The Library holds 10 implementations, each one a working definition you can pull into Quant.

Top Correlation indicators

The top custom implementations, built on the original standard Correlation formula.

10 total

The standard Correlation indicator

Correlation exactly as classically defined — the faithful reference build of the original formula, free to run in Quant.

What is Correlation?

Correlation measures how consistently two series move together, on a scale from -1 to +1. The standard Pearson coefficient is the covariance of the two series divided by the product of their standard deviations: +1 means perfectly aligned moves, -1 perfectly opposite, 0 no linear relationship. The Spearman variant applies the same formula to ranks instead of raw values, which captures any monotonic relationship and blunts the effect of outliers. Traders usually compute it on returns over a rolling window, because raw trending prices produce inflated, spurious readings.

The mathematics predates its market use by decades. Francis Galton sketched the idea of co-relation in the 1880s while studying heredity, Karl Pearson formalized the product-moment coefficient in the 1890s, and Charles Spearman introduced the rank-based alternative in 1904. Quantitative finance adopted the machinery wholesale: Harry Markowitz's 1952 portfolio theory made the covariance matrix, and the correlations inside it, the central input to diversification, and essentially every risk model since has inherited both the tool and its assumptions.

It matters because almost every multi-asset decision hides a correlation assumption: positions that look diversified but move together behave like one oversized trade, intermarket filters assume yesterday's relationships persist, and relative-value trades need co-movement to lean on. The honest caveats: correlation is unstable over time, says nothing about cause, and describes direction of co-movement only, not size. It also tends to rise sharply across risk assets in stress episodes, precisely when diversification is needed most.

Correlation is also a windowed statistic: a 20-bar estimate reacts fast and whipsaws, a 200-bar estimate is stable but stale, so serious users watch more than one window or rank the current reading against its own history with a percentile rank. And Pearson's coefficient captures only linear dependence. Related tools pick up what it misses: linear regression turns the same relationship into slope and fit, autocorrelation applies the idea to a series' own past, and entropy measures attempt to detect dependence that has no linear shape at all.

How to calculate rolling correlation

Pearson correlation over a rolling window takes four steps, and the returns conversion in step one is the part that guards against spurious readings.

  1. 1Convert each series to returns or one-bar changes. Correlating raw prices overstates the relationship whenever both series trend, even if their day-to-day moves are unrelated.
  2. 2Choose a window N and, over the last N paired observations, compute each series' mean and its deviations from that mean.
  3. 3Multiply the paired deviations and sum them, then divide by the square root of the product of the two series' summed squared deviations. The result is the Pearson coefficient, bounded between -1 and +1.
  4. 4Plot the coefficient bar by bar as an oscillator. For Spearman correlation, replace the values in each window with their ranks first and apply the same arithmetic.

How it's calculated

Measures how tightly two series move together over a rolling window, from -1 (inverse) to +1 (lockstep).

Xˉ=i=1nXin\bar{X} = \frac{\sum_{i=1}^{n} X_i}{n}
Yˉ=i=1nYin\bar{Y} = \frac{\sum_{i=1}^{n} Y_i}{n}
covXY=i=1n(XiXˉ)×(YiYˉ)n\operatorname{cov}_{XY} = \frac{\sum_{i=1}^{n} (X_i - \bar{X}) \times (Y_i - \bar{Y})}{n}
σX=i=1n(XiXˉ)2n\sigma_X = \sqrt{\frac{\sum_{i=1}^{n} (X_i - \bar{X})^2}{n}}
σY=i=1n(YiYˉ)2n\sigma_Y = \sqrt{\frac{\sum_{i=1}^{n} (Y_i - \bar{Y})^2}{n}}
r=covXYσX×σYr = \frac{\operatorname{cov}_{XY}}{\sigma_X \times \sigma_Y}
ρ=16×i=1ndi2n×(n21)\rho = 1 - \frac{6 \times \sum_{i=1}^{n} d_i^2}{n \times (n^2 - 1)}
n: rolling window length in bars (commonly 20)
i: bar index within the window, 1..n
X_i: value of the first series at bar i (price or return)
Y_i: value of the second series at bar i (price or return)
X_bar: mean of X over the window
Y_bar: mean of Y over the window
cov_XY: covariance of X and Y over the window
σ_X: standard deviation of X over the window
σ_Y: standard deviation of Y over the window
r: Pearson correlation coefficient, -1 to +1
rho: Spearman rank correlation, -1 to +1
d_i: difference between the rank of X_i and the rank of Y_i within the window

Population and sample divisors (n vs n - 1) cancel in r, so both give the same coefficient.

The Spearman shortcut formula assumes no tied ranks; with ties, apply the Pearson formula to the ranks.

Rolling correlation recomputes r each bar; a correlation matrix computes the same r for every pair in a basket, and returns are often preferred over raw prices.

How traders use it

  • As a portfolio exposure check: highly correlated positions stack the same risk, so correlation feeds position sizing and concentration limits rather than entry signals.
  • As a directional filter: strategies condition entries on a driver series, for example trading a currency or index only when its rolling correlation with the dollar index or yields behaves the way the setup expects.
  • As the first screen for relative value: pairs traders shortlist highly correlated instruments, then test cointegration separately, because two assets can be tightly correlated bar to bar while their spread drifts apart indefinitely.
  • As a regime alarm: a rolling coefficient that collapses toward zero or flips sign flags that a historical relationship has broken, which matters most for hedges built on it.
  • As an input to standardized spreads: once two instruments qualify, the spread between them is tracked as a z-score so that stretched has a definition; the correlation estimate justifies the pair, the z-score times the trade.
  • For stress-testing assumptions: portfolio simulations such as Monte Carlo price paths embed a correlation matrix, and rerunning them with stressed correlations shows how much of a strategy's smoothness depends on relationships holding.

Correlation vs related concepts

Autocorrelation: Autocorrelation is a series correlated with its own past at some lag, a single-asset measure of persistence or mean reversion. Correlation as usually quoted compares two different instruments over the same bars.

Linear Regression: Correlation and regression are two views of the same fit: the coefficient measures how tight the linear relationship is, while regression estimates its slope and intercept, the numbers a hedge is built from. Correlation says the line fits; regression says what the line is.

Z-score: A z-score standardizes one series against its own mean and deviation; correlation compares two series. They meet in the formula: the Pearson coefficient is the average product of the two series' z-scores.

More Correlation implementations

Concept family

Statistics

46 concepts mapped · 46 in the Library

Correlation FAQ

Should correlation be calculated on prices or returns?

Returns. Price series trend, and two unrelated trending series can show a strong price correlation purely because both drift, a classic spurious-regression effect. Differencing to returns removes the shared drift so the coefficient reflects genuine bar-to-bar co-movement. Relationships between price levels themselves are better examined with cointegration tests.

What is the difference between Pearson and Spearman correlation?

Pearson measures linear association on the raw values, so a few outsized returns can dominate the estimate. Spearman converts each window to ranks first and measures whether the relationship is consistently monotonic. With fat-tailed financial data (see distribution-of-returns profiling) the two can disagree; Spearman is generally the more robust of the pair, at the cost of ignoring magnitudes.

What counts as a strong correlation between assets?

Context-dependent. As loose convention, absolute values above roughly 0.7 read as strong, 0.3 to 0.7 as moderate, and below 0.3 as weak, but sample size and window length matter as much as the number: a 0.8 over ten bars is noise, while a 0.4 sustained over years can be structurally meaningful.

How reliable are correlations over time?

Treat any figure as a snapshot. Rolling estimates drift with regimes, flip around macro events, and depend heavily on window length: short windows are noisy, long windows average over structurally different periods, and adaptive estimators such as a Kalman filter exist precisely because no fixed window stays right for long. Stress episodes are the sharpest failure mode, when correlations across risk assets tend to jump toward +1 and hedges calibrated on calm data disappoint.

Does correlation imply that one asset drives the other?

No. Correlation is symmetric and silent about cause: both assets may respond to a third factor, the relationship may be coincidence over the sample, or the direction of influence may alternate. Lead-lag questions need different tools. Treat correlation as a description of co-movement, never an explanation of it.

Is correlation the same as beta?

No. Correlation is unitless co-movement. Beta multiplies correlation by the ratio of the two assets' volatilities to express how much one moves per unit move of the other, so two pairs can share a correlation of 0.9 with very different betas. Hedge ratios and index sensitivity are beta questions; diversification screening usually starts with correlation.

Build Correlation your way.

Quant writes, tests, and refines it with you — then it runs on LuxAlgo charting or ports to TradingView.