Indicator · Pine Script v6 · Own pane

Baxter-King Band-Pass Filter

by mihakralj

This indicator plots a Baxter-King symmetric band-pass filter in a separate pane.

View on GitHub

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

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

baxterking.pine
// Licensed under the Apache License, Version 2.0
// © mihakralj
//@version=6
indicator("Baxter-King Band-Pass Filter (BAXTERKING)", "BAXTERKING", overlay=false)

//@function Baxter-King symmetric band-pass filter
//     response at lag K and normalizing weights to sum to zero (removes trend).
//     The filter extracts cyclical components with periodicities between pLow
//     and pHigh bars. Being symmetric, the output is delayed by K bars.
//
//     Ideal band-pass weights:
//       B_0 = (b - a) / pi
//       B_j = (sin(j*b) - sin(j*a)) / (pi*j)  for j >= 1
//     where a = 2*pi/pHigh, b = 2*pi/pLow
//
//     BK normalization: subtract mean of all 2K+1 weights so they sum to zero.
//     This ensures the filter removes any linear trend (DC component = 0).
//
//     Reference: Baxter & King (1999), "Measuring Business Cycles: Approximate
//     Band-Pass Filters for Economic Time Series," Review of Economics and
//     Statistics, 81(4), 575-593.
//
//@param src Input series
//@param pLow Minimum period of the passband (bars). Must be >= 2.
//@param pHigh Maximum period of the passband (bars). Must be > pLow.
//@param K Half-length of the symmetric filter (number of leads/lags).
//          Larger K = better frequency resolution but more data loss at ends.
//          Baxter-King recommend K=12 for quarterly data, K=36 for monthly.
//@returns Cyclical component (oscillates around zero), delayed by K bars.
//@optimized O(K) per bar — single weighted sum over 2K+1 lagged values.
//           Weights are precomputed once. No arrays needed for the convolution
//           since Pine's series indexing handles the lookback naturally.
baxterking(series float src, simple int pLow, simple int pHigh, simple int K) =>
    if pLow < 2
        runtime.error("pLow must be >= 2")
    if pHigh <= pLow
        runtime.error("pHigh must be > pLow")
    if K < 1
        runtime.error("K must be >= 1")

    // Angular frequencies for the passband edges
    float a = 2.0 * math.pi / pHigh  // low cutoff (long period = low freq)
    float b = 2.0 * math.pi / pLow   // high cutoff (short period = high freq)

    // Compute ideal band-pass weights B_0..B_K
    // B_0 = (b - a) / pi
    // B_j = (sin(j*b) - sin(j*a)) / (pi*j) for j >= 1
    float b0_ideal = (b - a) / math.pi
    float wsum = b0_ideal

    // We need to accumulate the sum of all 2K+1 ideal weights for normalization.
    // By symmetry, sum = B_0 + 2 * sum(B_j, j=1..K)
    // We also need each B_j individually for the convolution.

    // Since Pine v6 forbids dynamic arrays in functions, and K is simple int,
    // we unroll the computation: compute each weight, accumulate the weighted
    // sum of src, and track the weight sum for normalization — all in one pass.

    // First pass: compute weight sum for normalization constant
    float idealSum = b0_ideal
    // Unrolled: accumulate sum of B_j for j=1..K
    // We do this with a loop since K is simple int
    float sumBj = 0.0
    for j = 1 to K
        float bj = (math.sin(j * b) - math.sin(j * a)) / (math.pi * j)
        sumBj += bj
    idealSum += 2.0 * sumBj  // symmetric: each B_j appears twice

    // Normalization constant: subtract from each weight so total sums to zero
    float theta = idealSum / (2 * K + 1)

    // Second pass: apply the filter as a weighted sum of src[0..2K]
    // The symmetric filter centered at time t uses src[t-K] through src[t+K].
    // Since Pine is causal (no look-ahead), we center at src[K] (delayed by K).
    // So output at bar t reflects the cycle at bar t-K.

    // Center weight (j=0, applied to src[K])
    float w0 = b0_ideal - theta
    float result = w0 * nz(src[K])

    // Symmetric weights (j=1..K)
    for j = 1 to K
        float bj = (math.sin(j * b) - math.sin(j * a)) / (math.pi * j)
        float wj = bj - theta
        // src[K-j] is the "future" side (but we're looking back from current bar)
        // src[K+j] is the "past" side
        result += wj * (nz(src[K - j]) + nz(src[K + j]))

    result


// ─── Inputs ───
pLow  = input.int(6,  "Min Period (pLow)",  minval=2,  tooltip="Shortest cycle to pass through (bars)")
pHigh = input.int(32, "Max Period (pHigh)", minval=3,  tooltip="Longest cycle to pass through (bars)")
K     = input.int(12, "Filter Half-Length (K)", minval=1, maxval=100,
     tooltip="Number of leads/lags. Larger = better approximation but loses 2K bars. BK recommend 12 for quarterly, 36 for monthly.")

// ─── Calculation ───
float cycle = baxterking(close, pLow, pHigh, K)

// ─── Visualization ───
hline(0, "Zero", color.gray, hline.style_dotted)
plot(cycle, "BK Cycle", color.new(color.blue, 0), 2)

Overview

Baxter-King Band-Pass Filter estimates the cyclical component of a source series for periods between a minimum and a maximum bar length, using ideal band-pass weights shifted so they sum to zero and remove a linear trend. Because the filter is symmetric, the plotted value is delayed by the half-length K. The inputs change the passband edges and the filter length, trading frequency resolution against extra lag and lost samples at the ends. It does not generate trade entries or exits.

Details

Published by

mihakralj on GitHub

Type

Indicator, Pine Script v6

Draws

Separate pane below the chart

Category

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
Min Period (pLow)int6pLow
Max Period (pHigh)int32pHigh
Filter Half-Length (K)int12K
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

Asymmetrical RSI

by everget
948 stars

Asymmetrical RSI is an indicator that computes a custom relative strength index from the rate of change of a user-selected source. It plots the resulting ARSI line in a separate pane with color coding that turns green above the overbought level and red below t

Indicator v4 Oscillators & momentum
Updated 10 days ago · GPL-3.0 GitHub repository of Asymmetrical RSI

This indicator calculates momentum setups based on the Relative Strength Index (RSI) and plots in a separate pane. It offers multiple scanning modes such as Continuous Break, Continuous Retracement, Flip Break, Flip Retracement, and both regular and hidden div

Indicator v6 Oscillators & momentumDivergence Repaints
Updated 1 year ago · MPL-2.0 GitHub repository of Momentum Setup - RSI Directional Momentum Indicator

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 demonstrates an experimental graph-style scatter visualization within a separate pane using Pine Script arrays. It tracks two features across recent bars: the single-bar price change and a scaled 14-period Relative Strength Index. Values are loa

Indicator v4 Oscillators & momentum
Updated 4 years ago · None stated GitHub repository of Example: Graph Style - 4th Dimension RSI

KD指標

by TaichiS
219 stars

This script calculates and plots a Stochastic Oscillator (KD indicator) in a separate chart pane. It determines the fast stochastic value over a 9-period lookback, then applies a 3-period Simple Moving Average (SMA) to create the %K line, and a second 3-period

Indicator v4 Oscillators & momentum
Updated 5 years ago · None stated GitHub repository of KD指標

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