' rolling forecast using state-space
' for version 4
' last checked 11/3/2000 h

' create workfile
workfile rollfcst q 1968 1982

' fill data
series y
y.fill 3.733,3.567,3.533,3.400,3.400,3.433,3.576,3.567,4.167,4.733,5.167,5.867,5.900,5.900,6.033,5.967,5.767,5.633,5.600,5.333,4.933,4.867,4.833,4.800,5.033,5.133,5.633,6.667,8.133,8.767,8.600,8.433,7.633,7.467,7.833,7.900,7.467,7.100,6.900,6.633,6.200,6.000,5.967,5.833,5.733,5.767,5.800,5.867,6.133,7.500,7.633,7.500,7.333,7.400,7.333,8.367,8.767,9.367,9.500,10.53

'-----------------------------------------------------------------
' brute force rolling forecast 
'-----------------------------------------------------------------

' set window size
!window = 20

' get size of workfile
!length = @obsrange

' get coefficient estimates using first window sample
smpl @first @first+!window-1
equation eq1.ls y c ar(1) ar(2)


' declare series for final results
series yhat1		' point estimates
series yhat1_se		

' set step size
!step = 4

' move sample
for !i = 1  to  !length-!window+1-!step
	' set sample to forecast period
	smpl @first+!i+!window-1 @first+!i+!window-2+!step
	' make forecasts in temporary series first
	eq1.forecast(f=na) tmp_yhat tmp_se
	' store forecasts for last step
	smpl @first+!i+!window-2+!step @first+!i+!window-2+!step
	yhat1 = tmp_yhat
	yhat1_se = tmp_se
next

'-----------------------------------------------------------------
' rolling forecast using state-space
'-----------------------------------------------------------------

' copy coefficients to control variable
!c1 = eq1.c(1)
!ar1 = eq1.c(2)
!ar2 = eq1.c(3)
'!s2 = eq1.@se * eq1.@se
scalar s2 = eq1.@se * eq1.@se

' declare state space object with AR(2) spec
sspace ss1
ss1.append @signal y = !c1 + sv1
ss1.append @state sv1 = !ar1*sv1(-1) + !ar2*sv2(-1) + [var = s2]
ss1.append @state sv2 = sv1(-1)

' compile using ml proc, even with no coefs to estimates
smpl @all
ss1.ml

' set forecast sample
smpl @first+!window @last

' get forecast
ss1.forecast(m=n, n=!step, i=o) @signal yhat2 @signalse yhat2_se

' verify forecasts match from brute force and state-space
show y yhat1 yhat2 yhat1_se yhat2_se

' plot actual and rolling forecasts with confidence bounds

smpl @all

graph graph1.line y yhat2 yhat2+2*yhat2_se yhat2-2*yhat2_se
graph1.options size(8,2) linepat
graph1.setelem(1) lcolor(blue) lpat(solid) legend(actual)
graph1.setelem(2) lcolor(red) lpat(solid) legend(rolling forecasts)
graph1.setelem(3) lcolor(green) lpat(dash1) legend("95% bounds")
graph1.setelem(4) lcolor(green) lpat(dash1) legend()
graph1.legend position(0,0) columns(1)
graph1.addtext(t) Rolling forecast without coefficient update using state-space

show graph1