Guide

Pine Script ta.correlation: Rolling Correlation Guide

Build a rolling correlation panel in Pine Script v6 with ta.correlation: use returns, pick a window length, then add a dashboard and an alert.

•12 min read

You have two charts open, BTCUSDT and ETHUSDT, and they look like they move together. Then one afternoon one of them drops and the other barely twitches, and you realise "they move together" was a feeling, not a number. A rolling correlation turns that feeling into a line you can plot under the chart: a value between -1 and 1 that tells you how closely two series have tracked each other over the last N bars. In Pine Script v6 the function that does it is ta.correlation, and it is one line of code. The hard part is everything around that line: which series to feed it, how long the window should be, and what the output can and cannot tell you.

This guide builds a rolling correlation panel step by step. You will see the function's signature and what it returns, how to pull in a second symbol without introducing lookahead, why correlating raw prices is usually a trap, how to pick a window length with the sampling noise in mind, and how to turn the line into a small dashboard and an alert. Every code block is complete Pine Script v6 that you can paste into the Pine Editor.

What ta.correlation actually computes

ta.correlation(source1, source2, length) returns the Pearson correlation coefficient of two series over the last length bars. Pearson's r takes the covariance of the two windows and divides it by the product of their standard deviations. In plain terms, it asks how often the two series sit above their own window averages at the same time and below them at the same time, and scales the answer so it always lands between -1 and 1.

A value near 1 means the two series rose and fell together inside the window. A value near -1 means one tended to be high when the other was low. A value near 0 means there was no consistent linear relationship in that window. The word linear matters. Pearson's r only measures how well a straight line describes the relationship, so two series can be strongly related in a curved or lagged way and still score close to zero.

The function returns na in two situations you will meet in practice. The first is the warm-up: until length bars of both series exist, there is nothing to correlate. The second is a flat window. If either series is constant across the whole window, its standard deviation is zero and the ratio is undefined, so you get na rather than a number. That second case is rare on price data but common if you correlate something like a signal that is zero for long stretches, so keep it in mind when you feed in your own derived series.

If you want to see the arithmetic without writing any code, the free correlation calculator computes the same Pearson coefficient from two pasted series and shows the Pine Script equivalent next to the result. It runs in your browser and nothing you type is uploaded, which makes it a handy way to sanity check a plot against a number you worked out by hand.

The simplest working version

Here is the smallest useful panel. It correlates the chart's close with the close of a second symbol you choose in the settings.

pine
//@version=6
indicator("Rolling Correlation (prices)", overlay = false)

otherSymbol = input.symbol("BINANCE:ETHUSDT", "Compare with")
length      = input.int(50, "Length", minval = 2)

otherClose = request.security(otherSymbol, timeframe.period, close,
     gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_off)

corr = ta.correlation(close, otherClose, length)

plot(corr, "Correlation", color = color.blue, linewidth = 2)
hline(1, "Perfect positive", color = color.gray)
hline(0, "No linear relationship", color = color.gray)
hline(-1, "Perfect negative", color = color.gray)

Three details are worth a closer look. The minval = 2 on the length matters because a correlation needs at least two points, and shorter windows are meaningless anyway. The lookahead = barmerge.lookahead_off argument keeps the second symbol honest: with lookahead off, the value on a historical bar is the value that was actually known at that bar's close, not a number borrowed from the future. The post on how request.security works explains the setting in depth, and the guide to fetching data from another symbol covers the symbol-string rules, including why the exchange prefix is a good habit.

The hline calls draw fixed reference lines at 1, 0 and -1 so you can read the panel at a glance. They have to be separate calls with constant values, which is why they are not folded into a loop.

Why correlating raw prices misleads you

Run the script above on two assets that both trended upward over the same year and you will probably see a correlation near 1 that barely moves. That result is real in a narrow sense and almost useless in a practical one. Two series that both drift in one direction will correlate strongly even if their day-to-day movements have nothing to do with each other. Statisticians call this a spurious correlation, and it is the single most common mistake in correlation work.

The cure is to correlate changes instead of levels. Instead of asking whether the two prices are high at the same time, ask whether the two returns are positive at the same time. A return strips out the drift and leaves only the bar-to-bar movement, which is what most people mean when they say two markets move together.

pine
//@version=6
indicator("Rolling Correlation (log returns)", overlay = false)

otherSymbol = input.symbol("BINANCE:ETHUSDT", "Compare with")
length      = input.int(50, "Length", minval = 2)

ownReturn   = math.log(close / close[1])
otherReturn = request.security(otherSymbol, timeframe.period, math.log(close / close[1]),
     gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_off)

corr = ta.correlation(ownReturn, otherReturn, length)

plot(corr, "Return correlation", color = color.orange, linewidth = 2)
hline(0, "Zero", color = color.gray)
hline(0.5, "0.5", color = color.new(color.gray, 60))
hline(-0.5, "-0.5", color = color.new(color.gray, 60))

Notice that the return for the second symbol is calculated inside the request.security call. That is deliberate. The expression is evaluated on the other symbol's own bars, so close[1] means the previous bar of that symbol. If you instead fetched the raw close and took math.log(otherClose / otherClose[1]) on the chart's bars, a bar where the other market had no new data would produce a return of zero that never happened. Computing the return at the source avoids that.

Log returns are used here because they add across bars and behave symmetrically for up and down moves. Simple percentage returns would work as well for most purposes. What matters is that you pick one and use it for both series.

Expect the return-based line to look different from the price-based one. It will sit lower, it will swing more, and it will be much more informative. If the price version said 0.95 for months and the return version says 0.6 and wanders between 0.3 and 0.8, the second picture is the honest one.

Choosing a window length

The length argument is a trade-off between responsiveness and noise, and the noise is larger than most people expect. A correlation computed from a short window is an estimate, and estimates from few points are loose. As a rough guide, when the true relationship is close to zero, the typical error in the estimate is about one divided by the square root of the number of observations. With 20 bars that is around 0.22, so a reading of 0.3 is well within the range you would get from two unrelated series. With 100 bars it shrinks to about 0.1.

That is why a 14 or 20 bar correlation looks so jumpy and why a single reading should never be treated as news. A longer window such as 100 bars is steadier but slower to notice that a relationship has broken down. Many people plot two lengths on the same panel, a short one and a long one, and watch for the moments where they disagree.

pine
//@version=6
indicator("Correlation: Fast vs Slow Window", overlay = false)

otherSymbol = input.symbol("BINANCE:ETHUSDT", "Compare with")
fastLen     = input.int(20, "Fast length", minval = 2)
slowLen     = input.int(100, "Slow length", minval = 2)

ownReturn   = math.log(close / close[1])
otherReturn = request.security(otherSymbol, timeframe.period, math.log(close / close[1]),
     gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_off)

fastCorr = ta.correlation(ownReturn, otherReturn, fastLen)
slowCorr = ta.correlation(ownReturn, otherReturn, slowLen)

plot(fastCorr, "Fast", color = color.new(color.orange, 20), linewidth = 1)
plot(slowCorr, "Slow", color = color.blue, linewidth = 2)
hline(0, "Zero", color = color.gray)

bgcolor(fastCorr < slowCorr - 0.3 ? color.new(color.red, 85) : na, title = "Fast well below slow")

The background tint marks bars where the short window has dropped well below the long one. That is a plain description of the data, not a prediction: it says the recent relationship is weaker than the longer-run one, and nothing more. The 0.3 gap is an arbitrary starting point, so expose it as an input once you know what you want.

Timeframe changes the picture as well. On a 1 minute chart, microstructure noise and the timing of individual trades pull correlations around. On a 1 day chart the same two assets may look far more tightly linked. If your conclusion changes when you change the timeframe, that is information about the relationship, not a bug in the script.

Mark it on the chart with the agent

A correlation line tells you how strongly two series are linked, but it does not show you where on the chart the relationship changed. That is a job for the chart itself. If you use PineScripter's AI chart agent, you can ask for the markup in plain English, then check the line against it.

A request you might type in the chat: "Mark the swing highs and lows on BTCUSDT 4h and draw the levels they cluster into as zones." The agent reads the chart first, including the swing levels with their touch counts and any drawings already there. It then draws with named toolbar tools while its cursor clicks the points, and the whole batch can be undone if the result is not what you wanted.

The agent's markup is a starting point you verify, not an answer. Check the touch counts it reports, switch timeframe to see whether the levels survive, and step through the run in replay one bar at a time. Then compare the dates where a zone gave way with what your correlation panel was doing at that moment, which is a quick way to see whether a drop in correlation lined up with a change in structure or was just noise. The agent works on PineScripter's own chart with crypto spot markets, not on your TradingView chart, and it marks what you ask for rather than judging the market.

The next step is the part that belongs in code. Once you know which stretches matter to you, describe the panel in plain English in the PineScripter editor, for example "plot the 50 bar correlation of log returns between this symbol and ETHUSDT and tint the background when it falls below zero". It writes Pine Script v6, checks the code for compile errors the way TradingView does, and fixes them itself. Follow-up requests change only the affected lines, and the Code Changes view shows what moved.

Turning the line into a dashboard

A plot is good for history. For a quick read on the current bar, a small table is easier on the eye. This version shows the current correlation against two reference symbols and colours the cell by strength.

pine
//@version=6
indicator("Correlation Dashboard", overlay = true)

symA   = input.symbol("BINANCE:ETHUSDT", "Symbol A")
symB   = input.symbol("BINANCE:SOLUSDT", "Symbol B")
length = input.int(50, "Length", minval = 2)

ownReturn = math.log(close / close[1])
retA = request.security(symA, timeframe.period, math.log(close / close[1]),
     gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_off)
retB = request.security(symB, timeframe.period, math.log(close / close[1]),
     gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_off)

corrA = ta.correlation(ownReturn, retA, length)
corrB = ta.correlation(ownReturn, retB, length)

cellColor(float v) =>
    na(v) ? color.gray : v >= 0.6 ? color.new(color.green, 40) : v <= 0 ? color.new(color.red, 40) : color.new(color.yellow, 40)

var table panel = table.new(position.top_right, 2, 3, border_width = 1)

if barstate.islast
    table.cell(panel, 0, 0, "Pair", text_color = color.white, bgcolor = color.new(color.gray, 30))
    table.cell(panel, 1, 0, "r (" + str.tostring(length) + ")", text_color = color.white, bgcolor = color.new(color.gray, 30))
    table.cell(panel, 0, 1, syminfo.ticker + " / A", text_color = color.white)
    table.cell(panel, 1, 1, na(corrA) ? "n/a" : str.tostring(corrA, "0.00"), text_color = color.white, bgcolor = cellColor(corrA))
    table.cell(panel, 0, 2, syminfo.ticker + " / B", text_color = color.white)
    table.cell(panel, 1, 2, na(corrB) ? "n/a" : str.tostring(corrB, "0.00"), text_color = color.white, bgcolor = cellColor(corrB))

The table is only written on the last bar because it describes the present, and var creates it once instead of on every bar. If you want the same idea across a longer list of symbols, see the walk-through of a watchlist table and the step-by-step build of a multi-symbol scanner.

Adding an alert

If you want to hear about it when a relationship weakens, build the condition from the confirmed value of the line and let it fire on bar close.

pine
//@version=6
indicator("Correlation Breakdown Alert", overlay = false)

otherSymbol = input.symbol("BINANCE:ETHUSDT", "Compare with")
length      = input.int(50, "Length", minval = 2)
floorLevel  = input.float(0.3, "Alert when correlation falls below", minval = -1, maxval = 1, step = 0.05)

ownReturn   = math.log(close / close[1])
otherReturn = request.security(otherSymbol, timeframe.period, math.log(close / close[1]),
     gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_off)

corr = ta.correlation(ownReturn, otherReturn, length)

plot(corr, "Correlation", color = color.blue, linewidth = 2)
hline(floorLevel, "Floor", color = color.red)

crossedBelow = barstate.isconfirmed and ta.crossunder(corr, floorLevel)
alertcondition(crossedBelow, "Correlation below floor", "Rolling correlation crossed below the floor on {{ticker}}")

Gating on barstate.isconfirmed means the alert condition only evaluates once the bar has closed, so a reading that would flicker across the floor during a live bar does not fire and then vanish. The guides on barstate.isconfirmed and why alerts fire on the wrong bar go into the reasons. An alert like this is a notification that a number moved, not a recommendation to do anything.

Pitfalls that catch people

The first is mismatched sessions. Two crypto spot markets trade around the clock and line up well, but pair a crypto symbol with an equity and the two series have different bars, so the other series carries stale values through the gaps. The returns computed from a stale series are zero or clumped, and the correlation falls for reasons that have nothing to do with the markets.

The second is leaking the future. Setting lookahead on in request.security, which is easy to do when copying older code, can make the second series look as though it knew what was coming, which inflates historical correlations and makes the panel look better than it will on a live bar. Keep it off.

The third is reading too much into one number. A correlation of 0.7 over 50 bars says the two series moved together in that window. It does not say one causes the other, it does not say the relationship will persist, and it does not say anything about direction in the future. Correlations between markets rise and fall with the conditions around them, and they have a habit of changing when conditions change.

The fourth is forgetting that correlation ignores scale. A small asset and a large one can have a correlation of 0.9 while one moves three times as far as the other. If the size of the moves matters for your question, look at the beta, the slope of one return against the other, as well. The ta.stdev guide covers the standard deviations that sit inside both quantities.

Where to go next

You now have a function, a returns-based setup, a window-length rule of thumb, a dashboard and an alert. The natural extensions are a correlation between a symbol and its own lagged self, to look for repeating cycles, and a rolling correlation between an indicator and price, to check whether your indicator is really adding information beyond the price it is computed from. Both use exactly the same call with different inputs.

If you would rather describe the panel than type it, the PineScripter editor turns a plain-English description into Pine Script v6, and its chart runs your script on real market data so you see the plot before pasting it into TradingView. The chart features page lists what the chart and the agent can do.

Disclaimer: PineScripter is a coding tool for Pine Script development. It does not provide financial advice and does not guarantee trading profits. Always backtest strategies thoroughly and understand the risks before live trading.

Frequently asked questions

What does ta.correlation return in Pine Script?

It returns the Pearson correlation coefficient of two series over the last length bars, a float between -1 and 1. It returns na until enough bars exist, and also when either series is constant across the window.

Should I correlate prices or returns?

Returns, in most cases. Two trending price series correlate strongly even when their bar-to-bar movements are unrelated. Correlating log or percentage returns removes the drift and measures how the two markets move together from bar to bar.

What length should I use for a rolling correlation?

There is no single right value. A short window such as 20 bars reacts quickly but is noisy, with a typical error near 0.22 around zero. A window of 100 bars is steadier but slower. Plotting a fast and a slow window together is a common compromise.

Why is my correlation line na for the first bars?

ta.correlation needs a full window of both series before it can compute anything, so the first length minus one bars are na. It is also na if the other symbol has not loaded data for those bars yet.

Does a high correlation mean one market predicts the other?

No. Correlation describes how two series moved together inside a past window. It does not show cause, direction or persistence, and relationships between markets change over time.

Can I use ta.correlation between an indicator and price?

Yes. Both arguments can be any series of float values, so you can correlate an indicator's output with price returns, or two of your own indicators. Make sure neither is constant over the window.

Run your script on real market data and see what it plots →


Disclaimer: PineScripter is a coding tool for Pine Script development. It does not provide financial advice and does not guarantee trading profits. Always backtest strategies thoroughly and understand the risks before live trading.