Indicator · Pine Script v6 · Own pane

Autocorrelation Function (ACF)

by mihakralj

This indicator calculates the statistical autocorrelation coefficient of an input series over a user-defined lookback window at a specified lag.

View on GitHub

GitHub stars99on the repository
Pine versionv6current
Lines of code87
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

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

acf.pine
// Licensed under the Apache License, Version 2.0
// © mihakralj
//@version=6
indicator("Autocorrelation Function (ACF)", "ACF", overlay=false)

//@function Calculates autocorrelation at a specified lag using a circular buffer
//@param src series float Input data series
//@param len simple int Lookback period for calculation
//@param lag simple int Lag order for autocorrelation (default 1)
//@returns float Autocorrelation coefficient between -1 and 1
//@optimized for performance using running sums and biased estimator (divide by n)
acf(series float src, simple int len, simple int lag) =>
    if len <= 0
        runtime.error("Period must be greater than 0")
    if lag < 1
        runtime.error("Lag must be at least 1")
    if len <= lag + 1
        runtime.error("Period must be greater than lag + 1")
    var int p = math.max(1, len)
    var array<float> buffer = array.new_float(p, na)
    var int head = 0, var int count = 0
    float oldest = array.get(buffer, head)
    if not na(oldest)
        count -= 1
    if not na(src)
        array.set(buffer, head, src)
        count += 1
    else
        array.set(buffer, head, na)
    head := (head + 1) % p
    if count <= lag
        na
    else
        // Calculate mean
        float sum = 0.0
        int validN = 0
        for i = 0 to p - 1
            float val = array.get(buffer, i)
            if not na(val)
                sum += val
                validN += 1
        if validN <= lag
            na
        else
            float mean = sum / validN

            // Calculate variance (population): Σ(x - mean)² / n
            float variance = 0.0
            for i = 0 to p - 1
                float val = array.get(buffer, i)
                if not na(val)
                    float diff = val - mean
                    variance += diff * diff
            variance /= validN

            if variance <= 0
                0.0
            else
                // Calculate autocovariance at lag k (biased: divide by n)
                // Need to iterate in temporal order through the circular buffer
                int startIdx = count < p ? 0 : head
                float autocovariance = 0.0
                for t = lag to count - 1
                    int currentIdx = (startIdx + t) % p
                    int laggedIdx = (startIdx + t - lag) % p
                    float xt = array.get(buffer, currentIdx)
                    float xtk = array.get(buffer, laggedIdx)
                    if not na(xt) and not na(xtk)
                        autocovariance += (xt - mean) * (xtk - mean)
                autocovariance /= validN

                // ACF = γ_k / γ_0, clamped to [-1, 1]
                float result = autocovariance / variance
                math.max(-1.0, math.min(1.0, result))

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

// Inputs
i_source = input.source(close, "Source")
i_period = input.int(20, "Period", minval=3)
i_lag = input.int(1, "Lag", minval=1)

// Calculation
acf_value = acf(i_source, i_period, i_lag)

// Plot
plot(acf_value, "ACF", color=color.yellow, linewidth=2)

Overview

Autocorrelation Function (ACF) tracks values using an internal circular buffer, computes sample mean, variance, and autocovariance, and normalizes the output between -1.0 and 1.0. The resulting metric plots in a separate pane to help traders assess trend persistence or mean-reverting cyclical behavior. Configurable options include the price source, calculation period, and lag order.

Details

Published by

mihakralj on GitHub

Type

Indicator, Pine Script v6

Draws

Separate pane below the chart

Category

Trend, Mean reversion, Oscillators & momentum

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
Sourcesourceclosei_source
Periodint20i_period
Lagint1i_lag
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

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]

Schaff Trend Cycle

by everget
948 stars

This indicator plots the Schaff Trend Cycle in a separate pane. It subtracts a slow exponential moving average from a fast one, applies a stochastic cycle twice, and smooths each result to form a 0–100 oscillator. Line color follows the slope, or the upper and

Indicator v4 Oscillators & momentumTrend
Updated 10 days ago · GPL-3.0 GitHub repository of Schaff Trend Cycle

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
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

ADX Histogram

by harryguiacorn
219 stars

This indicator calculates and displays the Average Directional Index (ADX) as a column histogram in a separate pane. It evaluates market trend strength by calculating directional movement metrics based on specified smoothing and DI length inputs. When the ADX

Indicator v5 TrendOscillators & momentum
Updated 1 year ago · None stated GitHub repository of ADX Histogram

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