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

//@version=4
study("Laguerre Filter", shorttitle="L filter", overlay=true)

// This is the Laguerre Filter by John F. Ehlers. He published the paper : Time Warp - without space travel.
// This study open gamma and weight of each filter for user to customize the filter design. 
// Each filter can be plotted for evaluation too. 
// Data of the first filter allows to input any bar, eg. 0 for current bar, 1 for one previous, 
//   for the purpose to evulate forecasting idea. 
// Follows Ehlers' paper, this study allows to plot the weighted average line with all filter off. 


src = input(title="Source", defval=hl2)
g0 = input(title="Gamma 0",defval = 0.2, minval=0, maxval=1)
g1 = input(title="Gamma 1",defval = 0.8, minval=0, maxval=1)
g2 = input(title="Gamma 2",defval = 0.8, minval=0, maxval=1)
g3 = input(title="Gamma 3",defval = 0.9, minval=0, maxval=1)

W0 = input(title="weight 0", defval=1)
W1 = input(title="weight 1", defval=2)
W2 = input(title="weight 2", defval=2)
W3 = input(title="weight 3", defval=1)
WW = W0+W1+W2+W3

s0 = input(title="Show filter L0 ?", defval =false)
s1 = input(title="Show filter L1 ?", defval =false)
s2 = input(title="Show filter L2 ?", defval =false)
s3 = input(title="Show filter L3 ?", defval =false)
ss = input(title="Show no filter MA line?", defval =false)

dd = input(title="Filter 0 data delay?", defval = 0)

L0 = 0.0
L1 = 0.0
L2 = 0.0
L3 = 0.0
L0 := (1 - g0) * src[dd] + g0 * nz(L0[1])
L1 := -g1 * L0 + nz(L0[1]) + g1 * nz(L1[1])
L2 := -g2 * L1 + nz(L1[1]) + g2 * nz(L2[1])
L3 := -g3 * L2 + nz(L2[1]) + g3 * nz(L3[1])

filter = (W0*L0 + W1*L1 + W2*L2 + W3*L3 )/WW                 // the price line when filter is on
fixline = (W0*src + W1* src[1] + W2* src[2] + W3*src[3])/WW  // ie When filter is off

colorL = filter>filter[1]? color.olive:color.fuchsia

plot(s0? L0:na, color=color.red, title="filter L0")
plot(s1? L1:na, color=color.lime, title="filter L1")
plot(s2? L2:na, color=color.aqua, title="filter L2")
plot(s3? L3:na, color=color.gray, title="filter L3")

plot(filter, color=colorL, title="L filtered", linewidth=2)
plot(ss? fixline: na, color=color.blue, title="No filter")