Indicator · Pine Script v6 · On the chart

Polynomial Fitting (POLYFIT)

by mihakralj

This indicator plots a rolling polynomial regression fitted to a chosen price source over a lookback window.

View on GitHub

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

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

polyfit.pine
// Licensed under the Apache License, Version 2.0
// © mihakralj
//@version=6
indicator("Polynomial Fitting (POLYFIT)", "POLYFIT", overlay=true, precision=8)

//@function Rolling polynomial regression fit of degree d over a lookback window
//@param source Series to fit
//@param period Lookback period (number of data points)
//@param degree Polynomial degree (1=linear, 2=quadratic, 3=cubic, etc.)
//@returns Fitted value at the current bar (polynomial endpoint)
//@description Fits a polynomial P(x) = a_0 + a_1*x + ... + a_d*x^d to the most
//  recent `period` data points using the normal equations (X'X)a = X'y.
//  The x-values are normalized to [0,1] for numerical stability.
//  Solves via Gauss-Jordan elimination with partial pivoting.
//  Output is P(1.0) — the polynomial evaluated at the current bar.
//  Degree 1 = linear regression (endpoint), degree 2 = quadratic fit, etc.
//  Complexity: O(period * degree + degree^3) per bar.
polyfit(series float source, simple int period, simple int degree) =>
    if period < 2
        runtime.error("Period must be at least 2")
    if degree < 1
        runtime.error("Degree must be at least 1")
    int d = math.min(degree, period - 1)
    int m = d + 1

    var array<float> buf = array.new_float(period, na)
    var int head = 0
    var int count = 0
    var float lastValid = na

    float curr = source
    if na(curr) and not na(lastValid)
        curr := lastValid
    if not na(curr)
        lastValid := curr

    if not na(curr)
        array.set(buf, head, curr)
        if count < period
            count += 1
        head := (head + 1) % period

    int n = count
    if n < m + 1
        na
    else
        int start = n < period ? 0 : head
        float nf = float(n)
        float invN = 1.0 / (nf - 1.0)

        int matSize = m * m
        array<float> mat = array.new_float(matSize, 0.0)
        array<float> rhs = array.new_float(m, 0.0)

        for i = 0 to n - 1
            int idx = (start + i) % period
            float y = array.get(buf, idx)
            float x = float(i) * invN

            float xp = 1.0
            for r = 0 to d
                float val_r = array.get(rhs, r)
                array.set(rhs, r, val_r + xp * y)

                float xq = xp
                for c = r to d
                    int pos = r * m + c
                    float val_m = array.get(mat, pos)
                    array.set(mat, pos, val_m + xp * xq)
                    if c != r
                        int pos2 = c * m + r
                        array.set(mat, pos2, val_m + xp * xq)
                    xq *= x
                xp *= x

        for col = 0 to d
            int pivRow = col
            float pivMax = math.abs(array.get(mat, col * m + col))
            for row = col + 1 to d
                float absVal = math.abs(array.get(mat, row * m + col))
                if absVal > pivMax
                    pivMax := absVal
                    pivRow := row
            if pivRow != col
                for k = 0 to d
                    int p1 = col * m + k
                    int p2 = pivRow * m + k
                    float tmp = array.get(mat, p1)
                    array.set(mat, p1, array.get(mat, p2))
                    array.set(mat, p2, tmp)
                float tmpR = array.get(rhs, col)
                array.set(rhs, col, array.get(rhs, pivRow))
                array.set(rhs, pivRow, tmpR)

            float piv = array.get(mat, col * m + col)
            if math.abs(piv) < 1e-30
                break

            float invPiv = 1.0 / piv
            for k = col to d
                int pos = col * m + k
                array.set(mat, pos, array.get(mat, pos) * invPiv)
            array.set(rhs, col, array.get(rhs, col) * invPiv)

            for row = 0 to d
                if row != col
                    float factor = array.get(mat, row * m + col)
                    for k = col to d
                        int p1 = row * m + k
                        int p2 = col * m + k
                        array.set(mat, p1, array.get(mat, p1) - factor * array.get(mat, p2))
                    array.set(rhs, row, array.get(rhs, row) - factor * array.get(rhs, col))

        float result = 0.0
        float xp = 1.0
        for r = 0 to d
            result += array.get(rhs, r) * xp
            xp *= 1.0
        result

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

// Inputs
i_period = input.int(20, "Period", minval=2, tooltip="Number of data points in the fitting window")
i_degree = input.int(2, "Degree", minval=1, maxval=6, tooltip="Polynomial degree: 1=linear, 2=quadratic, 3=cubic")
i_source = input.source(close, "Source")

// Calculation
fit_value = polyfit(i_source, i_period, i_degree)

// Plot
plot(fit_value, "POLYFIT", color=color.yellow, linewidth=2)

Overview

Polynomial Fitting (POLYFIT) builds the normal equations, solves them with Gauss-Jordan elimination and partial pivoting, and returns the polynomial value at the current bar. Period sets the window length, degree sets the curve order from linear upward, and source selects the series. The result is drawn on the price chart. It does not generate trade signals or exits.

Details

Published by

mihakralj on GitHub

Type

Indicator, Pine Script v6

Draws

On the price chart

Category

Trend

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

948 stars

The Adaptive Laguerre Filter calculates a smoothed, dynamically adjusted trendline plotted directly on the main price chart. It dynamically adjusts its damping factor (alpha) based on recent price range variations and median percentile calculations over a spec

Indicator v4 TrendMoving averages
Updated 10 days ago · GPL-3.0 GitHub repository of Adaptive Laguerre Filter
575 stars

This indicator detects equal highs and lows by comparing prices within user-defined left and right bars using a tolerance percentage. It plots horizontal lines on the price chart for equal highs in one color and lows in another. A screener allows input of mult

Indicator v5 Support & resistanceTrend
Updated 1 year ago · MPL-2.0 GitHub repository of ICT Equal Highs and Lows with Screener
330 stars

This script plots three moving averages on the price chart: a fast EMA or SMA with 10 periods, a slow EMA or SMA with 20 periods, and a trend EMA or SMA with 100 periods. It signals trend changes by drawing a white cross when the fast moving average crosses ab

Indicator v4 TrendMoving averages
Updated 2 months ago · None stated GitHub repository of 3 EMA/SMA + Cross [Alorse]
318 stars

This indicator calculates an ATR trailing stop line derived from the highest high minus an average true range multiple over a specified lookback period. It plots the trailing stop line directly on the price chart and colors price bars based on whether the clos

Indicator v5 TrendVolatility & bands
Updated 2 months ago · MIT GitHub repository of ATR Trailing Stoploss

All Candlestick Patterns

by shunjizhan
292 stars

All Candlestick Patterns detects and highlights a wide range of bullish, bearish, and neutral candlestick patterns directly on the price chart. It features optional trend filtering using either a 50-period simple moving average or a combination of 50-period an

Indicator v4 Candlestick patternsTrend
Updated 3 years ago · None stated GitHub repository of All Candlestick Patterns

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