The Hodrick–Prescott filter (also known as Hodrick–Prescott decomposition) is a mathematical tool used in macroeconomics, especially in real business cycle theory, to remove the cyclical component of a time series from raw data. It is used to obtain a smoothed-curve representation of a time series, one that is more sensitive to long-term than to short-term fluctuations. (source Wikipedia: https://en.wikipedia.org/wiki/Hodrick%E2%80%93Prescott_filter)
Be aware that this indicator is continuously rechecking the complete history to redraw the curve to be perfectly in line with the data serie. So it is repainting the past and should not be used “as is” for live trading.
Compatible only with PRT v11 and onwards.
defparam drawonlastbaronly=true
//PRC_Hodrick-Prescott filter | indicator
//28.09.2020
//Nicolas @ www.prorealcode.com
//Sharing ProRealTime knowledge
// --- settings
nobs =1000 //Number of bars to smooth
lambda =1600 //Higher lambda leads to the smoother data
// --- end of settings
if islastbarupdate and barindex>max(nobs,lambda) then
for i=0 to nobs-1
$output[i]=Close[i]
next
$a[0]=1.0+lambda
$b[0]=-2.0*lambda
$c[0]=lambda
for i=1 to nobs-3 do
$a[i]=6.0*lambda+1.0
$b[i]=-4.0*lambda
$c[i]=lambda
next
$a[1]=5.0*lambda+1
$a[nobs-1]=1.0+lambda
$a[nobs-2]=5.0*lambda+1.0
$b[nobs-2]=-2.0*lambda
$b[nobs-1]=0.0
$c[nobs-2]=0.0
$c[nobs-1]=0.0
//Forward
for i=0 to nobs-1 do
Z=$a[i]-H4*H1-HH5*HH2
HB=$b[i]
HH1=H1
H1=(HB-H4*H2)/Z
$b[i]=H1
HC=$c[i]
HH2=H2
H2=HC/Z
$c[i]=H2
$a[i]=($output[i]-HH3*HH5-H3*H4)/Z
HH3=H3
H3=$a[i]
H4=HB-H5*HH1
HH5=H5
H5=HC
next
//Backward
H2=0
H1=$a[nobs-1]
$output[nobs-1]=H1
for i=nobs-2 downto 0 do
$output[i]=$a[i]-$b[i]*H1-$c[i]*H2
H2=H1
H1=$output[i]
//drawpoint(barindex[i],$output[i],1) coloured(255,255,0)
drawsegment(barindex[i],$output[i],barindex[i+1],$output[i+1]) coloured(255,255,0) style(line,3)
next
endif
return