Indicator · Pine Script v5 · Own pane

Goertzel Algorithm

by mikeyhu70

This indicator applies the Goertzel algorithm, a signal-processing method for measuring a single frequency component, to price in a separate pane.

View on GitHub

GitHub stars1on the repository
Pine versionv5runs as is
Lines of code151
Settings8inputs
LicenceNone statedfile: MPL-2.0
Last update6 months ago15 Apr 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

151 lines of Pine Script v5 from Cycle/Goertzel algorithm (2024 v1.0).ps, published under MPL-2.0 (file header). Keep the author's credit and licence lines when you reuse it.

Goertzel algorithm (2024 v1.0).ps
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/

// The Goertzel algorithm is a technique in digital signal processing (DSP) for efficient evaluation of the individual terms of the discrete Fourier transform (DFT).
// https://en.wikipedia.org/wiki/Goertzel_algorithm

// See also:
// Python implementation of the Goertzel algorithm for calculating DFT terms
// https://gist.github.com/sebpiq/4128537


//@version=5

indicator('Goertzel algorithm (2024 v1.0)', overlay=false,max_bars_back=5000)
len = input(17, title='Period length (recpirocal of frequency)')
block_len = input(1024, title='Measurment Block Length (N in goertzel notation)')
extend_multiplier = input.int(1, title="multipler of len to extend into future", minval=0)
shift_multiplier = input.int(2, title="multipler of len to shift to match cycle with data", minval=0)
shift_sample = input.int(256, title="Number of sample to match shift data", minval=0)
pct_train = input.float(0.90,title="percent indecimal percent data to train", minval=0.25)
auto_shift = input.bool(true,title="Do training of data")


// CONSTANTS

pi = 2 * math.asin(1)
PI = pi
tau = 2 * pi


// The following function takes a vector x (your source) made of N samples, and computes the k-th frequency coefficient (k from 0 to N-1).
// The real part is returned in as Inphase and the imaginary part is returned as Quadrature.
// The Magnitude and Theta are also calculated

// FUNCTIONS

// Goertzel algorithm for integer k
goertzel_int(x, k, N) =>
    // Because our signal is a complex signal we have to comput both the real and imaginary
    w = 2 * pi * k / N  // omega = (2 pi * number of bars in period)/Window length
    w_real = math.cos(w)  // cos of omega (the real portion of omega)
    w_imag = math.sin(w)  // sin of omega (the complex portion of omega)
    c = 2 * w_real  // Coefficient 2* cos of omega (real part)
    y = 0.0
    z1 = 0.0
    z2 = 0.0
    //for n = 1 to N by 1  // Shound this be 0 to N-1???
    for n = len to math.min(N * pct_train, bar_index)  by 1  // Shound this be 0 to N-1???
        y := x[n] + c * z1 - z2
        z2 := z1
        z1 := y
        z1
    Inphase = w_real * z1 - z2  // Real
    Quadrature = w_imag * z1  // Imag
    Power = math.pow(z2, 2) + math.pow(z1, 2) - c * z1 * z2
    Theta = math.atan(Inphase / Quadrature) * 2 * pi  // In radians
    [Inphase, Quadrature, Power, Theta]


// To do implement hamming
hamm_f(_n, _N) =>
    hamm = 0.54 - 0.46 * math.cos(tau * (_n / (_N - 1)))
    hamm

// Inputs
src = input(close)

// dohamm=input(false)

// recirpocal of frequency

k = 0 
max_bars = 0

if barstate.islast
    // Get the maximum available historical bars
    max_bars := bar_index
    // Set block_len to the minimum of max_bars and desired_block_len
    block_len_ = math.min(max_bars, block_len)
    k := block_len_ / len
else
    k := block_len / len

// Create a label to display the maximum available historical bars
var label_id = label.new(bar_index, high, "", style=label.style_none)
label.set_xy(label_id, bar_index + 25, high)
label.set_text(label_id, "Max Historical Bars: " + str.tostring(max_bars))
label.set_textcolor(label_id, color.white)
label.set_size(label_id, size.normal)



[InPhase_real, Quadrature, Power, Theta] = goertzel_int(close, k, block_len)

// Define the range of shift values to test
min_shift = 0
max_shift = len*shift_multiplier

// Initialize variables to store the best shift value and correlation
best_shift = 0
var best_correlation = -1.0 // Declare best_correlation as a float type

InPhase_real_aligned = 0.0
Quadrature_aligned = 0.0
Power_aligned = 0.0
Theta_aligned = 0.0

if auto_shift
    // Iterate over the range of shift values
    for shift = min_shift to max_shift
        // Shift the resulting values
        InPhase_real_shifted = InPhase_real[shift]
        Quadrature_shifted = Quadrature[shift]
        Power_shifted = Power[shift]
        Theta_shifted = Theta[shift]

        // Calculate the correlation between the shifted values and the close plot
        sum_xy = 0.0
        sum_x = 0.0
        sum_y = 0.0
        sum_x2 = 0.0
        sum_y2 = 0.0
    
        for i = len to shift_sample - 1
            x = Power_shifted[i]
            y = close[i]
            sum_xy := sum_xy + x * y
            sum_x := sum_x + x
            sum_y := sum_y + y
            sum_x2 := sum_x2 + x * x
            sum_y2 := sum_y2 + y * y
    
        correlation = (sum_xy - sum_x * sum_y / block_len) / math.sqrt((sum_x2 - sum_x * sum_x / block_len) * (sum_y2 - sum_y * sum_y / block_len))

        // Update the best shift value and correlation if a higher correlation is found
        if correlation > best_correlation
            best_correlation := correlation
            best_shift := shift

    // Use the best shift value for the final alignment
    InPhase_real_aligned := InPhase_real[best_shift]
    Quadrature_aligned := Quadrature[best_shift]
    Power_aligned := Power[best_shift]
    Theta_aligned := Theta[best_shift]



plot(InPhase_real, title='InPhase_real', color=color.new(color.red, 0), display=display.none)
plot(Quadrature, title='Quadrature', color=color.new(color.blue, 0), display=display.none)
plot(Theta, title='Theta', color=color.new(color.orange, 0), display=display.none)

plot(auto_shift ? Power_aligned : Power, title='Power', color=color.new(color.green, 0),offset=len*extend_multiplier)

Overview

A period length and a measurement block length set the cycle to test, and a training percentage and shift settings align the fitted wave with recent data and extend it into the future. A label shows the maximum available bars. It is experimental and gives no trade signals.

Details

Published by

mikeyhu70 on GitHub

Type

Indicator, Pine Script v5

Draws

Separate pane below the chart

Category

AI / machine learning

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.

Settings

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

SettingTypeDefaultVariable
Period length (recpirocal of frequency)int17len
Measurment Block Length (N in goertzel notation)int1024block_len
multipler of len to extend into futureint1extend_multiplier
multipler of len to shift to match cycle with dataint2shift_multiplier
Number of sample to match shift dataint256shift_sample
percent indecimal percent data to trainfloat0.90pct_train
Do training of databooltrueauto_shift
srcsourceclosesrc
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

Function: Decision Tree

by ricardosantos79
261 stars

Function: Decision Tree is a Pine Script v4 study that demonstrates a weighted decision-tree path sampler in a separate pane. A small pseudo-random generator reseeds itself from a stored float and picks node indices whose weights are at least the random draw.

Indicator v4 AI / machine learning
Updated 4 years ago · None stated GitHub repository of Function: Decision Tree

This indicator combines a dynamic Seasonal Random Index (SRI) with a dynamic Karobein Oscillator and a pattern-similarity search algorithm in a separate pane. It normalizes SRI into seasoned and deseasoned series, shading the area green or red to signal trend

Indicator v4 Oscillators & momentumTrend
Updated 1 year ago · None stated GitHub repository of Similarity Search, Karobein and Seasonal Random Index

This indicator plots an oscillator in a separate pane. It builds several SuperTrend series across a user-defined factor range and step, using ATR as the band width. On each bar it measures the distance between the close and each SuperTrend output, then groups

Indicator v5 TrendVolatility & bands
Updated 2 years ago · GPL-3.0 GitHub repository of AI SuperTrend Clustering Oscillator [LuxAlgo]
99 stars

This indicator applies the rectified linear unit to the difference between the selected source and a 20-period simple moving average. Positive deviations plot in green and negative deviations plot in red in a separate pane. The only input changes the price ser

Indicator v6 Moving averagesAI / machine learning
Updated 4 weeks ago · Apache-2.0 GitHub repository of Rectified Linear Unit (ReLU)

Markov State Engine classifies market conditions into six distinct regimes, including strong trends, weak trends, compression, and expansion. It evaluates historical state transitions using an exit-conditional Markov model with Laplace smoothing to estimate re

Indicator v6 AI / machine learningTrend
Updated 2 days ago · MIT GitHub repository of Markov State Engine [WavesUnchained]

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