*
* HPFILTER.PRG
* Manual Example 12.3
*
cal(q) 1959:1
open data haversample.rat
data(format=rats) 1959:1 2006:4 gdph
log gdph / lgdp
*
* This uses the built-in HP filter in the FILTER instruction
*
filter(type=hp,tuning=1600.0) lgdp / hpfilt
*
* The model:
*
*    g(t)=2g(t-1)-g(t-2)+e(t)
*    y(t)=g(t)+v(t)
*
* The ratio of variances between v and e is the "lambda" in the HP filter
* criterion function.
*
* The state vector is (g(t),g(t-1))
*
compute lambda = 1600.0
*
* As relative variances are all that matter, sw is pegged at 1 with sv being
* lambda.
*
compute [rect] a  = ||2.0,-1.0|1.0,0.0||
compute [vect] c  = ||1.0,0.0||
compute [rect] f  = ||1.0|0.0||
*
dlm(a=a,c=c,y=lgdp,sv=lambda,f=f,sw=1.0,exact,type=smooth) 1959:1 2006:4 estates
set hpsmooth = estates(t)(1)
*
graph(window="HP filter") 2
# lgdp
# hpsmooth
*
* Direct solution of the the system of equations from the first order conditions
* for the minimization problem. Most of the matrix is set using the FMATRIX
* instruction, as, except for the first and last few rows, the rows are 4th
* difference operators.
*
compute nobs=2006:4-1958:4
dec rect hp(nobs+2,nobs+2)
fmatrix hp 1 1
# -2 -1 0 1 2
# 1.0 -4.0 6.0 -4.0 1.0
compute hp(1,1)=1.0,hp(1,2)=-2.0,hp(1,3)=1.0
compute hp(2,1)=-2.0,hp(2,2)=5.0,hp(2,3)=-4.0,hp(2,4)=1.0
compute hp(nobs+2,nobs+2)=1.0,hp(nobs+2,nobs+1)=-2.0,hp(nobs+2,nobs)=1.0
compute hp(nobs+1,nobs+2)=-2.0,hp(nobs+1,nobs+1)=5.0,hp(nobs+1,nobs)=-4.0,hp(nobs+1,nobs-1)=1.0
dec vect yy(nobs+2) dd(nobs+2)
ewise yy(i)=%if(i<=nobs,lgdp(nobs+1-i),0.0)
ewise dd(i)=%if(i<=nobs,1.0,0.0)
compute gg=%solve(lambda*hp+%diag(dd),yy)
*
set hpexact 1959:1 2006:4 = gg(nobs+1-t)

