Indicator · Pine Script v6 · Own pane

Pearson's Correlation (CORRELATION)

by mihakralj

This indicator calculates the Pearson correlation coefficient between a chosen source series on the current chart and a secondary external symbol across a user-specified lookback period.

View on GitHub

GitHub stars47on the repository
Pine versionv6current
Lines of code68
Settings3inputs
LicenceMIT
Last update8 months ago28 Feb 2026

Add It to Your TradingView Chart

  1. 1Copy the scriptPress Copy script above, or the copy button on the code below.
  2. 2Open the Pine EditorOpen a TradingView chart and choose Pine Editor at the bottom of the screen.
  3. 3Paste over the templateCreate a new indicator, select all of the template text and paste. Press Save and give it a name.
  4. 4Add it to the chartPress Add to chart, then adjust the settings with the gear icon next to its name.

Source Code

68 lines of Pine Script v6 from indicators/statistics/correlation.pine, published under MIT. Keep the author's credit and licence lines when you reuse it.

correlation.pine
// The MIT License (MIT)
// © mihakralj
//@version=6
indicator("Pearson's Correlation (CORRELATION)", "CORRELATION", overlay=false)

//@function Calculates Pearson correlation coefficient using single pass with circular buffer
//@param src1 series float First series to analyze
//@param src2 series float Second series to analyze
//@param len simple int Lookback period for calculation
//@returns float Pearson correlation coefficient between -1 and 1
//@optimized for performance using combined covariance and variance calculation
correlation(series float src1, series float src2, simple int len) =>
    if len <= 0
        runtime.error("Period must be greater than 0")
    var int p = math.max(1, len)
    var array<float> buffer1 = array.new_float(p, na)
    var array<float> buffer2 = array.new_float(p, na)
    var int head = 0, var int count = 0
    var float sum1 = 0.0, var float sum2 = 0.0
    var float sumSq1 = 0.0, var float sumSq2 = 0.0
    var float sumProd = 0.0
    float oldest1 = array.get(buffer1, head)
    float oldest2 = array.get(buffer2, head)
    if not na(oldest1) and not na(oldest2)
        sum1 -= oldest1, sum2 -= oldest2
        sumSq1 -= oldest1 * oldest1, sumSq2 -= oldest2 * oldest2
        sumProd -= oldest1 * oldest2
        count -= 1
    if not na(src1) and not na(src2)
        sum1 += src1, sum2 += src2
        sumSq1 += src1 * src1, sumSq2 += src2 * src2
        sumProd += src1 * src2
        count += 1
        array.set(buffer1, head, src1)
        array.set(buffer2, head, src2)
    else
        array.set(buffer1, head, na)
        array.set(buffer2, head, na)
    head := (head + 1) % p
    if count > 1
        mean1 = sum1 / count, mean2 = sum2 / count
        cov = (sumProd / count) - mean1 * mean2
        var1 = (sumSq1 / count) - mean1 * mean1
        var2 = (sumSq2 / count) - mean2 * mean2
        stddev1 = math.sqrt(math.max(0.0, var1))
        stddev2 = math.sqrt(math.max(0.0, var2))
        denominator = stddev1 * stddev2
        if denominator != 0
            cov / denominator
        else
            na
    else
        na

// ---------- Main loop ----------

// Inputs
i_source1 = input.source(close, "Source 1")
i_source2_ticker = input.symbol("SPY", "Source 2 Ticker (e.g., SPY, AAPL)")
i_period = input.int(20, "Period", minval=2)

i_source2 = request.security(i_source2_ticker, timeframe.period, close, lookahead=barmerge.lookahead_off)

// Calculation
correlation_value = correlation(i_source1, i_source2, i_period)

// Plot
plot(correlation_value, "Correlation", color=color.yellow, linewidth=2)

Overview

Pearson's Correlation (CORRELATION) processes streaming inputs efficiently using a circular buffer to update single-pass covariance and standard deviations on every bar. The resulting value is plotted in a separate pane, fluctuating between -1 and 1 to indicate perfect inverse or positive linear relationships. Key settings allow customization of the local source series, the comparison ticker symbol, and the correlation lookback length.

Details

Published by

mihakralj on GitHub

Type

Indicator, Pine Script v6

Draws

Separate pane below the chart

Markets

Any symbol

Timeframes

Any timeframe

Risk Notes

No repainting, lookahead or stacked entries were found in its code or README. That says nothing about how well it works: test it first.

Topics

pinescriptpinescript-indicatorstechnical-analysistradingview-indicators

Settings

The inputs you can change from the gear icon on the chart. Defaults are the author's.

SettingTypeDefaultVariable
Source 1sourceclosei_source1
Source 2 Ticker (e.g., SPY, AAPL)symbolSPYi_source2_ticker
Periodint20i_period
Third-party code. ForexR did not write, test or endorse this script, and the summary above was generated automatically from its code and README. Indicators describe the past, and a strategy's backtest can look better than live trading, especially when a script repaints. Check it in the Strategy Tester and on a demo account before you rely on it.

Similar Pine Scripts

Asymmetrical RSI

by everget
948 stars

Asymmetrical RSI is an indicator that computes a custom relative strength index from the rate of change of a user-selected source. It plots the resulting ARSI line in a separate pane with color coding that turns green above the overbought level and red below t

Indicator v4 Oscillators & momentum
Updated 10 days ago · GPL-3.0 GitHub repository of Asymmetrical RSI

This indicator calculates momentum setups based on the Relative Strength Index (RSI) and plots in a separate pane. It offers multiple scanning modes such as Continuous Break, Continuous Retracement, Flip Break, Flip Retracement, and both regular and hidden div

Indicator v6 Oscillators & momentumDivergence Repaints
Updated 1 year ago · MPL-2.0 GitHub repository of Momentum Setup - RSI Directional Momentum Indicator
549 stars

Range Volume Change compares volume inside a chosen session window with the same window on the previous day and plots that change as a percentage. It accumulates volume during the window and, when enabled, volume outside it, drawing growing columns in a separa

Indicator v5 VolumeSessions & time Repaints
Updated 10 months ago · None stated GitHub repository of Range Volume Change

Beep Boop

by magic8bot
409 stars

This indicator calculates a modified MACD oscillator and signal line alongside a trend EMA filter, plotting the output as a stylized column histogram in a separate pane. Instead of plotting true MACD distance, it quantifies positive and negative histogram mome

Indicator v4 Oscillators & momentumTrend
Updated 3 years ago · MIT GitHub repository of Beep Boop

Mojito v3 Strategy

by namuan
318 stars

The Mojito v3 Strategy indicator evaluates volatility term structure by calculating the ratio between front-month and second-month VIX futures contracts. It smooths this ratio using a configurable median filter and compares the result against user-defined uppe

Indicator v5 Volatility & bands
Updated 2 months ago · MIT GitHub repository of Mojito v3 Strategy

More indicators

Trade Your Charts With a Regulated Broker

Compare brokers that connect to TradingView, with spreads, minimum deposits and leverage side by side.

Compare brokers