Indicator · Pine Script v6 · On the chart

Autoregressive FIR Moving Average (AFIRMA)

by mihakralj

Calculates and plots an Autoregressive Finite Impulse Response (AFIRMA) moving average directly on the price chart.

View on GitHub

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

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

afirma.pine
// Licensed under the Apache License, Version 2.0
// © mihakralj
//@version=6
indicator("Autoregressive FIR Moving Average (AFIRMA)", "AFIRMA", overlay=true)

//@function Calculates AFIRMA using various windowing functions with optional least squares cubic spline fitting
//@param source Series to calculate AFIRMA from
//@param period Lookback period - window size
//@param windowType Window function type (1:Hanning, 2:Hamming, 3:Blackman, 4:Blackman-Harris)
//@param leastSquares Apply least squares linear regression fitting for autoregressive prediction
//@returns AFIRMA value, calculates from first bar using available data
//@optimized Uses windowing functions with O(n) complexity; least squares adds O(n) for polynomial fitting
afirma(series float src, simple int period, simple int windowType=4, simple bool leastSquares=false) =>
    float result = src
    if period <= 0
        runtime.error("Period must be greater than 0")
    if windowType < 1 or windowType > 4
        runtime.error("WindowType should be in range [1-4]")
    int p = math.min(bar_index + 1, period)

    if p > 1
        var array<float> coefs = array.new_float(1, 0.0)
        var int prevPeriod = 0
        var int prevWindowType = -1
        if p != prevPeriod or windowType != prevWindowType
            coefs := array.new_float(p, 0.0)
            float a0 = 0.35875
            float a1 = -0.48829
            float a2 = 0.14128
            float a3 = -0.01168
            if windowType == 1
                a0 := 0.50
                a1 := -0.50
            else if windowType == 2
                a0 := 0.54
                a1 := -0.46
            else if windowType == 3
                a0 := 0.42
                a1 := -0.50
                a2 := 0.08
            float TWO_PI = 6.28318530718
            float twoPiDivP = TWO_PI / p
            for k = 0 to p - 1
                float kTwoPiDivP = k * twoPiDivP
                float coef = a0 + a1 * math.cos(kTwoPiDivP)
                if a2 != 0.0
                    coef += a2 * math.cos(2.0 * kTwoPiDivP)
                if a3 != 0.0
                    coef += a3 * math.cos(3.0 * kTwoPiDivP)
                array.set(coefs, k, coef)
            prevPeriod := p
            prevWindowType := windowType
        float sum = 0.0
        float weightSum = 0.0
        int validCount = 0
        for i = 0 to p - 1
            float price = src[i]
            if not na(price)
                float coef = array.get(coefs, i)
                sum += price * coef
                weightSum += coef
                validCount += 1
        result := validCount > 0 and weightSum > 0 ? sum / weightSum : src

        if leastSquares and p > 2
            int n = math.min(math.floor((p - 1) / 2), 50)
            if n >= 2
                var float sx = 0.0
                var float sx2 = 0.0
                var int prevN = 0

                if n != prevN
                    sx := 0.0
                    sx2 := 0.0
                    for i = 0 to n - 1
                        sx += i
                        sx2 += i * i
                    prevN := n

                float sy = 0.0
                float sxy = 0.0
                for i = 0 to n - 1
                    float yi = nz(src[i])
                    sy += yi
                    sxy += i * yi

                float denom = n * sx2 - sx * sx
                if math.abs(denom) > 1e-10
                    float slope = (n * sxy - sx * sy) / denom
                    float intercept = (sy - slope * sx) / n

                    var array<float> fittedBuffer = array.new_float(p, na)
                    for i = 0 to n - 1
                        float fitted = intercept + slope * i
                        array.set(fittedBuffer, i, fitted)

                    float lsSum = 0.0
                    float lsCount = 0.0
                    for i = 0 to p - 1
                        float val = i < n ? array.get(fittedBuffer, i) : nz(src[i])
                        if not na(val)
                            lsSum += val
                            lsCount += 1.0

                    result := lsCount > 0 ? lsSum / lsCount : result
    result

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

// Inputs
i_period = input.int(20, "Period", minval=1)
i_source = input.source(close, "Source")
i_windowType = input.int(4, "Window Function", minval=1, maxval=4, tooltip="1:Hanning, 2:Hamming, 3:Blackman, 4:Blackman-Harris")
i_leastSquares = input.bool(false, "Least Squares Method", tooltip="Enable linear regression fitting for autoregressive prediction")

// Calculation
afirma_value = afirma(i_source, i_period, i_windowType, i_leastSquares)

// Plot
plot(afirma_value, "AFIRMA", color=color.yellow, linewidth=2)

Overview

Autoregressive FIR Moving Average (AFIRMA) weights historical price data using selectable windowing functions, including Hanning, Hamming, Blackman, and Blackman-Harris filters. An optional least squares linear regression mode can be enabled to provide autoregressive forecasting adjustments. The script serves strictly as a smoothing and trend-tracking indicator, providing no automated trade execution, buy or sell signals, or exit rules.

Details

Published by

mihakralj on GitHub

Type

Indicator, Pine Script v6

Draws

On the price chart

Category

Moving averages, 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
Sourcesourceclosei_source
Window Functionint4i_windowType
Least Squares Methodboolfalsei_leastSquares
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
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 plots four customizable moving averages directly on the main price chart using default lengths of 3, 8, 21, and 50 periods. It fills the space between adjacent averages in green or maroon depending on trend alignment. Additionally, it computes B

Indicator v5 Moving averagesTrend
Updated 2 months ago · MIT GitHub repository of Multiple Moving Averages

NVDA Trend Ribbon

by longsurf-ai
277 stars

This indicator plots three exponential moving averages and ATR volatility envelopes on the price chart. It compares the fast and slow EMAs to shade a trend ribbon and marks confirmed upward and downward crossovers with triangle labels. Settings change the thre

Indicator v6 TrendMoving averages
Updated yesterday · MIT GitHub repository of NVDA Trend Ribbon
257 stars

Donald SPX - Options Trading is an overlay indicator designed for intraday SPX analysis. It plots a 200-period Weighted Moving Average (WMA) on the price chart while evaluating multi-timeframe market structure across Daily, 15-minute, 5-minute, and 2-minute ba

Indicator v5 Moving averagesTrend Repaints
Updated 6 weeks ago · None stated GitHub repository of Donald SPX - Options Trading

60K均線

by TaichiS
219 stars

This multi-timeframe indicator calculates and plots 20-period and 60-period simple moving averages from the 60-minute timeframe directly onto the price chart. The 20-period average displays as a green line, while the 60-period average appears in blue. It serve

Indicator v4 Moving averagesTrend Repaints
Updated 5 years ago · None stated GitHub repository of 60K均線

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