Indicators··6 min read

Rolling Correlation Between Two Symbols

1 references, link-verified · 1 primaryEditor of record: Shane CantyStandards review editorial standard · audit log

Correlation quantifies the degree to which two price series move together, ranging from perfect positive alignment (+1.0) through independence (0) to perfect negative alignment (−1.0). This indicator calculates the Pearson correlation coefficient over a rolling window, allowing traders to monitor how two assets co-move. Useful for pairs trading, hedge construction, and identifying regime shifts in asset relationships.

//@version=6
indicator("Rolling Correlation Between Two Symbols", overlay=false)

symbol2 = input.symbol("EURUSD", title="Second Symbol")
period = input(20, title="Correlation Period", minval=2)

// Fetch prices from both symbols
price1 = close
price2 = request.security(symbol2, timeframe.period, close)

// Calculate rolling means
mean1 = ta.sma(price1, period)
mean2 = ta.sma(price2, period)

// Calculate deviations from mean
dev1 = price1 - mean1
dev2 = price2 - mean2

// Calculate covariance (average of product of deviations)
covariance = ta.sma(dev1 * dev2, period)

// Calculate standard deviations
std1 = ta.stdev(price1, period)
std2 = ta.stdev(price2, period)

// Calculate correlation (handle division by zero)
denominator = std1 * std2
correlation = denominator > 0 ? covariance / denominator : 0

// Plot correlation
plot(correlation, title="Correlation", color=correlation >= 0 ? color.green : color.red, linewidth=2)

// Reference lines for interpretation
hline(0, title="No Correlation", color=color.gray, linestyle=hline.dashed)
hline(1, title="Perfect Positive", color=color.gray, linestyle=hline.dotted)
hline(-1, title="Perfect Negative", color=color.gray, linestyle=hline.dotted)

How the code works

The indicator fetches the current chart's closing price and retrieves the second symbol's closing price via request.security(), ensuring both are on the same timeframe. It then calculates the rolling mean (SMA) for each series to establish the center point around which variation is measured.

The critical step is computing deviations: subtracting each rolling mean from the corresponding price to isolate the "noise" or movement around the trend. The covariance is approximated as the simple moving average of the product of these deviations. This captures how consistently the two series deviate together; when one moves up and the other does the same, the product is positive; when they diverge, the product is negative.

The denominator is the product of each series' standard deviation, which normalizes the covariance to a scale of −1 to +1. A division-by-zero check prevents errors when volatility is near zero. The result is the Pearson correlation coefficient over the rolling period.

The plot is colored green for positive correlation (assets move in tandem) and red for negative correlation (inverse movement). Reference lines at −1, 0, and +1 provide visual anchors for interpretation.

Reading it on a chart

Correlation oscillates within the band from −1 to +1. Values near +1 indicate the two symbols are moving together; values near −1 indicate inverse movement; values near 0 suggest independence.

In pairs trading, a sudden drop in correlation from historical highs can signal a breakdown in the usual relationship, prompting exit or adjustment. Conversely, a rise in correlation from low levels might indicate re-coupling. Traders watching a currency pair against an equity index might exploit periods of low correlation (offering uncorrelated diversification) or periods of high positive correlation (suggesting one may lead the other).

The rolling window captures changing relationships. A regime shift, such as a shift from uncorrelated to correlated markets during a flight-to-safety event, will appear as a sustained move in the indicator.

Limitations

This correlation measurement is backward-looking, reflecting the relationship over the past N bars. It offers no predictive power; a strong historical correlation does not guarantee future co-movement, especially around macroeconomic breaks or policy shifts.

The Pearson correlation coefficient assumes a linear relationship. If two assets follow a non-linear pattern, the correlation may understate or misrepresent their true dependence.

The rolling window length significantly affects the result. A period that is too short produces noisy, whip-saw-prone values; a period that is too long obscures short-term regime changes. No universal optimal period exists; the choice depends on the trader's time horizon and the asset pair's characteristics.

The indicator does not distinguish causality. A correlation of +0.8 does not indicate which symbol leads or whether one causes the other.

The rolling calculation introduces some lag: correlation values at the bar close reflect data that is already on the chart, preventing lookahead bias, but traders must acknowledge that the relationship shown has already transpired.

Finally, correlation can be unstable during illiquid or low-volume periods, especially for less-traded instrument pairs, producing extreme or unreliable values.

Key definitions

Correlation coefficient: A statistical measure ranging from −1 to +1 that quantifies the linear relationship between two variables; +1 indicates perfect positive co-movement, 0 indicates no linear relationship, and −1 indicates perfect negative co-movement.

Covariance: The expected value of the product of two variables' deviations from their respective means; high covariance indicates both variables tend to deviate in the same direction.

Pearson correlation: The most common form of correlation, calculated as the covariance of two variables divided by the product of their standard deviations.

Rolling window: A fixed-length subset of historical data that shifts forward one bar at a time, allowing a metric to be recalculated at each bar using only the most recent N observations.

Standard deviation: A measure of the dispersion or volatility of a dataset; it quantifies how far individual values typically deviate from the mean.

Pairs trading: A market-neutral strategy that buys one security and shorts another to profit from the convergence or divergence of their prices, often relying on historical correlation.

References

  1. Pearson, K., "On lines and planes of closest fit to systems of points in space," Philosophical Magazine, vol. 2, no. 11, pp. 559-572 (1901).

  2. CME Group, "Correlation and Hedging", Educational Resource. Https://www.cmegroup.com/

  3. SEC Division of Economic and Risk Analysis, "Statistical Methods and Financial Market Analysis." https://www.sec.gov/

  4. TradingView, "Pine Script Reference Manual: Built-in Variables and Functions," Technical Documentation. Https://www.tradingview.com/pine-script-docs/

  5. Wikipédia, "Pearson correlation coefficient," Encyclopædia Britannica Online (2024). Https://en.wikipedia.org/wiki/Pearson_correlation_coefficient

  6. Investopedia, "Correlation: What it means in finance and investing," Educational Content (2024). Https://www.investopedia.com/


Educational research on historical data only. Not investment advice, not a signal, and never a performance promise. Past results do not predict future performance. Every reference is link-verified before publication and every paper is re-audited weekly against the library's editorial standard.

Last reviewed by the PropLedger research pipeline: 2026-09-06. Educational research on historical data, not financial advice.

Educational research on historical data only. Not investment advice, not a signal, and never a performance promise. Past results do not predict future performance. Every reference is link-verified before publication and every paper is re-audited weekly against the library's editorial standard. Found an error? Email support@prop-ledger.org and the paper is corrected or withdrawn.