'First order model (BEKK-GARCH(1,1)) is assumed.
sym(2) M
vector(2) A1
vector(2) B1

'Create a system
%sys = "sysbekk"
system {%sys}
'{%sys}.append duks = c(1)
'{%sys}.append dukf = c(2)
{%sys}.append logspot = c(1)
{%sys}.append logfirst= c(2)

'Estimate the system as diagonal BEKK
'smpl @first @first+368
smpl @first @first+2440
{%sys}.arch @diagbekk c arch(1) garch(1)

'Save the conditional series
{%sys}.makegarch

'Compute the in-sample hedge ratio
'series hr = garch_02/garch_01_02
series hr = garch_01_02 / garch_02
delete garch*

'Rolling forecasts
'for !i=1 to 154
for !i=1 to 10

   'smpl @first @first+368+!i-1
smpl @first @first+2440+!i-1

   {%sys}.arch @diagbekk c arch(1) garch(1)
   {%sys}.makegarch
   {%sys}.makeresids

   'Generate new series for forecasted variables
   for %y GARCH_01 GARCH_02 GARCH_01_02 RESID01 RESID02
     series {%y}f= {%y}
   next

   'Organize the estimated coefficients into matrix form.
   'Constant is assumed to be the only exogenous variable in each mean equation.
   'Therefore coefficients of variance specification should start at c(3).
   M(1,1)={%sys}.@coefs(3)
   M(1,2)={%sys}.@coefs(4)
   M(2,2)={%sys}.@coefs(5)
   A1(1)={%sys}.@coefs(6)
   A1(2)={%sys}.@coefs(7)
   B1(1)={%sys}.@coefs(8)
   B1(2)={%sys}.@coefs(9)

   'Number of observations used in the estimation
   !n={%sys}.@regobs 

   'Define out of sample forecast horizon
   !h = 1

   'Perform dynamic forecasts via adjusting the sample (do not forget the missing value due to lag structure)
   for !j=1 to !h
      smpl @first+!n+!j @first+!n+!j+1
      GARCH_01f = M(1,1) + A1(1)^2*RESID01f(-1)^2 + B1(1)^2*GARCH_01f(-1)
      GARCH_02f = M(2,2) + A1(2)^2*RESID02f(-1)^2 + B1(2)^2*GARCH_02f(-1)
      GARCH_01_02f= M(1,2) + A1(1)*A1(2)*RESID01f(-1)*RESID02f(-1) + B1(1)*B1(2)*GARCH_01_02f(-1)
      RESID01f = 0
      RESID02f = 0
   next

  'Out-sample hedge ratios 
  series hrf = garch_01_02f / garch_02f

  'Combine in-sample and out-sample hedge ratios into one series
  hr = hrf 
  delete garch* resid0*

next
smpl @all
