Band Pass Filtering

Band Pass Filtering

This is an alternative way to do bandpass filtering. I Still need to update it to support moveable frequency bands. The lowBandpass() is just a ‘trick,’ as it simply subtracts the highBandpass() from the close data, so it is not really accurate in that it removes the low frequencies, just in a rather less-than-ideal manner.

The “spectrum” of the dataset to filter will always be from 0 to 100, so think of filter boundary as %. So, a boundary of 40% means: 40% of the low-frequencies have been removed from the original data to make the red graph, and 40% of the high-frequencies have been removed from the original data to make the green graph.

This came about after reading the excellent tutorial on signal processing in Pine Script (https://www.pinecoders.com/techniques/ds…), as the techniques listed there did not do exactly what I was looking for.

// ——————————————————————————————————————————————
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © duncanstroud

//@version=4
study(“Bandpass Filters v.02”, overlay=false)

get_slope( src ) =>
lookback=1
x1 = bar_index
y1 = src
x2 = bar_index
y2 = src
slope = (y2-y1)/(x2-x1)

lowBandpass( src ,freq) =>
var float output = na
sampleLen=72 // This number is totally arbitrary
_src = get_slope( src )
a = change( _src,freq)
b = (abs(a)/highest(abs(a),freq) * sign(a)) * 100// – rescale values from range of (1,-1) tp (100,-100)
output := b < freq and b > freq*-1 ? na : close

highBandpass( src ,freq) =>
_low = lowBandpass( src ,(100-freq))
newsrc = src sma (_low,1)

filterBnd = input(title=”Filter Boundary (%)”, defval=40, type=input.integer, minval=1, maxval=99,step = 1)
smoothType = input(title=”Smoothing”, defval=”NONE”, type=input.string,options=)
smoothingLen = input(title=”Smoothing Length”, defval=20, type=input.integer, minval=1 )

loFilter = filterBnd

smooth(_src,smoothType) =>
src = _src
if smoothType == “RMA”
src := rma( src , smoothingLen)
else
if smoothType == “SMA”
src := sma ( src , smoothingLen)
else
if smoothType == “EMA”
src := ema ( src , smoothingLen)
else
if smoothType == “WMA”
src := wma ( src , smoothingLen)
else
if smoothType == “NONE”
src := src

lowBand = smooth(lowBandpass(close,filterBnd),smoothType)
highBand = smooth(highBandpass(close,filterBnd),smoothType)

// the ranges are different, so make the screen large of comment out one of the plots.

plot(highBand, color=color.red)
plot(lowBand, color=color.green)
// ——————————————————————————————————————————————

Published at Mon, 25 Jan 2021 23:10:20 +0000

Spread the word. Share this post!

Welcome to The Bitcoin Street Journal

Install
×