*
*  HPFILTER.PRG
*  Example 12.3
*
cal 1959 1 4
allocate 2000:4
open data haversmp.rat
data(format=rats) / 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
*
*  Since lambda is being treated as fixed, the only component which needs
*  to be a frml is y. As relative variances are all that matter, sw is
*  pegged at 1 with sv being lambda.
*
dec rect a
dec rect c
dec frml[vect] y
dec symm sw
dec symm sv
*
compute a  = ||2.0,-1.0|1.0,0.0||
compute c  = ||1.0|0.0||
frml    y  = ||lgdp||
compute sw = ||1.0|0.0,0.0||
compute sv = ||lambda||
*
dlm(a=a,c=c,y=y,sv=sv,sw=sw,exact,type=smooth) 1959:1 2000: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=2000: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 2000:4 = gg(nobs+1-t)

