Indicator · Pine Script v6 · Own pane

Cointegration

by mihakralj

Calculates the statistical cointegration between the current chart instrument and a user-selected secondary ticker using the Engle-Granger method.

View on GitHub

GitHub stars99on the repository
Pine versionv6current
Lines of code125
Settings3inputs
LicenceApache-2.0
Last update4 weeks ago27 Sep 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

125 lines of Pine Script v6 from lib/statistics/cointegration/cointegration.pine, published under Apache-2.0. Keep the author's credit and licence lines when you reuse it.

cointegration.pine
// Licensed under the Apache License, Version 2.0
// © mihakralj
//@version=6
indicator("Cointegration (COINTEGRATION)", "COINTEGRATION", overlay=false)

sma(series float source, simple int period) =>
    if period <= 0
        runtime.error("Period must be greater than 0")
    var int p = period
    var array<float> buffer = array.new_float(p, na)
    var int head = 0
    var float sum = 0.0
    var int valid_count = 0
    float oldest = array.get(buffer, head)
    if not na(oldest)
        sum -= oldest
        valid_count -= 1
    if not na(source)
        sum += source
        valid_count += 1
    array.set(buffer, head, source)
    head := (head + 1) % p
    nz(sum / valid_count, source)

stddev(series float src, int len) =>
    if len <= 0
        runtime.error("Period must be greater than 0")
    var int p = math.max(1, len)
    var array<float> buffer = array.new_float(p, na)
    var int head = 0,  var int count = 0
    var float sum = 0.0, var float sumSq = 0.0
    float oldest = array.get(buffer, head)
    if not na(oldest)
        sum -= oldest
        sumSq -= oldest * oldest
        count -= 1
    float val = nz(src)
    sum += val
    sumSq += val * val
    count += 1
    array.set(buffer, head, val)
    head := (head + 1) % p
    count > 1 ? math.sqrt(math.max(0.0, (sumSq / count) - math.pow(sum / count, 2))) : 0.0

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

//@function Calculates the cointegration of two series using the Engle-Granger method.
//@param series_a series float The first series.
//@param series_b series float The second series.
//@param period int The lookback period for the regression and ADF test.
//@returns float The Augmented Dickey-Fuller test statistic for the residuals. A more negative value suggests stronger evidence of cointegration.
//@optimized for performance and dirty data
cointegration(series_a, series_b, period) =>
    // Validate parameters
    if period <= 1
        runtime.error("Period must be greater than 1")
    beta = correlation(series_a, series_b, period) * (stddev(series_a, period) / stddev(series_b, period))
    alpha = sma(series_a, period) - beta * sma(series_b, period)
    residuals = series_a - (alpha + beta * series_b)
    delta_residuals = residuals - nz(residuals[1])
    lagged_residuals = nz(residuals[1])
    gamma_numerator = sma(delta_residuals * lagged_residuals, period - 1) - sma(delta_residuals, period - 1) * sma(lagged_residuals, period - 1)
    gamma_denominator = sma(lagged_residuals * lagged_residuals, period - 1) - math.pow(sma(lagged_residuals, period - 1), 2)
    gamma = gamma_denominator == 0 ? na : gamma_numerator / gamma_denominator
    regression_error = delta_residuals - gamma * lagged_residuals
    se_gamma_sq = sma(regression_error * regression_error, period - 1) / gamma_denominator
    se_gamma = se_gamma_sq <= 0 or na(se_gamma_sq) ? na : math.sqrt(se_gamma_sq)
    adf_statistic = se_gamma == 0 or na(se_gamma) ? na : gamma / se_gamma
    adf_statistic

// ---------- 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
coint_stat = cointegration(i_source1, i_source2, i_period)

// Plot
plot(coint_stat, "Cointegration ADF Stat", color.yellow, color=color.yellow, linewidth=2)

Overview

Cointegration evaluates the stationarity of the regression residuals and plots the Augmented Dickey-Fuller test statistic in a separate pane, where more negative values indicate stronger cointegration. Configurable inputs include the primary source, the secondary ticker symbol, and the lookback period.

Details

Published by

mihakralj on GitHub

Type

Indicator, Pine Script v6

Draws

Separate pane below the chart

Category

Mean reversion

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

algorithmic-tradingcsharpdotnetpinescriptpythonquantitative-financesimdta-libtechnical-analysistechnical-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

261 stars

This indicator calculates standardized z-scores of price data across four different lookback periods (6, 14, 26, and 100). Standardizing data subtracts the moving average from the price and divides by the standard deviation. It applies a Double Exponential Mov

Indicator v5 Mean reversionVolatility & bands
114 stars

This indicator implements a dual-direction variation of the Williams Vix Fix oscillator in a separate pane. It normalizes price data using min-max scaling to compute both upward and downward synthetic volatility metrics across two selectable calculation modes

Indicator v4 Volatility & bandsMean reversion
Updated 1 year ago · None stated GitHub repository of Combo Williams Vix Fix (Twin)
47 stars

This indicator applies the hyperbolic tangent to a chosen source series and plots the result in a separate pane. It centers the transform on a 200-bar simple moving average of that source, multiplies the deviation by a steepness factor, and maps the output int

Indicator v6 Moving averagesMean reversion
Updated 8 months ago · MIT GitHub repository of Hyperbolic Tangent (TANH)

AutoCorrelation Function

by Anderson-ALGO
9 stars

This indicator calculates sample autocorrelation across multiple lag intervals for a selected price series. It computes correlation values over a user-specified lookback period using raw prices, log returns, absolute log returns, or squared log returns. Plotte

Indicator v4 TrendMean reversion
Updated 5 years ago · None stated GitHub repository of AutoCorrelation Function

Calculates a composite carry and decay oscillator fusing impulse-autocorrelation half-life, a Hurst exponent approximation, path efficiency, and range expansion ratios. It evaluates whether an impulse is likely to persist or mean-revert, plotting the oscillato

Indicator v6 TrendOscillators & momentum
Updated yesterday · MIT GitHub repository of Market Memory & Decay Oscillator [WavesUnchained]

This indicator builds a channel from a Hull moving average of the source and an ATR scaled by a band multiplier, then normalizes price inside that channel into a 0 to 100 oscillator. It smooths the result with a weighted moving average and plots the line in a

Indicator v6 Mean reversionVolatility & bands
Updated 3 months ago · None stated GitHub repository of Radiant Mean Reversion Channels [Pineify]

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