Indicator · Pine Script v6 · On the chart

Autoregressive FIR Moving Average (AFIRMA)

by mihakralj

The AFIRMA indicator calculates a weighted moving average via FIR filter coefficients from Hanning, Hamming, Blackman or Blackman-Harris windows.

View on GitHub

GitHub stars47on the repository
Pine versionv6current
Lines of code120
Settings4inputs
LicenceMIT
Last update8 months ago28 Feb 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 indicators/forecasts/afirma.pine, published under MIT. Keep the author's credit and licence lines when you reuse it.

afirma.pine
// The MIT License (MIT)
// © 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 cubic polynomial 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 cubic polynomial 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) optionally applies least-squares cubic polynomial fitting for autoregressive prediction. The script plots the AFIRMA line directly on the price chart as an overlay. Main inputs adjust period length, source series, window type and least-squares option. It initializes from available historical data at bar zero with no lookahead.

Details

Published by

mihakralj on GitHub

Type

Indicator, Pine Script v6

Draws

On the price chart

Category

Moving averages

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

pinescriptpinescript-indicatorstechnical-analysistradingview-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

This overlay indicator plots a Supertrend from an ATR length and factor, four exponential moving averages, and a selectable VWAP or TWAP taken from a chosen timeframe on the price chart. It also shows MACD and stochastic with adjustable lengths, smoothing, ver

Indicator v5 Oscillators & momentumMoving averages
Updated 1 year ago · MPL-2.0 GitHub repository of Momentum Setup: Vijay Thakare Option Buying Scalping Setup
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
285 stars

Mean Reversion Study is an indicator that identifies trade setups combining exponential moving averages, RSI extremes, and engulfing candlestick patterns. It highlights bullish setups when a bullish engulfing candle forms below the EMA while RSI is oversold, a

Indicator v4 Mean reversionCandlestick patterns
Updated 3 years ago · None stated GitHub repository of Mean Reversion Study

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

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