series y=logreturns
series x=logdy

'run rolling regression

' set window size
!window = 142

' set step size
!step = 1

' get size of workfile
!length = @obsrange

' declare equation for estimation
equation eq1

'calculate number of rolls
!nrolls = @floor((!length-!window)/!step)

'matrix to store coefficient estimates
matrix(2,!nrolls) coefmat ' where 2 is the number of coefficients

'series to store forecast estimates
series fcast

'redundant series for catching start and end points
%start = "@first" '@otod(@ifirst(ser))   
%end = "@last"   '@otod(@ilast(ser))
   
'variable keeping track of how many rolls we've done
!j=0

' move sample !step obs at a time
for !i = 1  to  !length-!window+1-!step step !step
   !j=!j+1
     
   ' set sample for estimation period         
   %first = @otod(@dtoo(%start)+!i-1)
   %last = @otod(@dtoo(%start)+!i+!window-2)
   smpl {%first} {%last}     

   ' estimate equation - where the equation is y=c(1) + c(2)*x1 
   eq1.ls y c x
   
   ' store coefficients
   colplace(coefmat,eq1.@coef,!j)
   
  ' 1-period-ahead forecast
%1pers = @otod(@dtoo(%start)+!i+!window-1) 'start point
%1pere = @otod(@dtoo(%start)+!i+!window) 'end point

if @dtoo(%end) < @dtoo(%1pere) then   'check whether the forecast end point is greater than the workfile end point
      exitloop
   endif  
   
   ' set smpl for forecasting period
   smpl {%1pers} {%1pere}   
   
   ' forecast with command *forecast* (see also *fit*)
   eq1.forecast(f=na) yf     
   
   ' set sampl to obtain the 4th period observation
   smpl {%1pere} {%1pere}   
   
   ' store forecasts
   fcast = yf
next

smpl @all
show coefmat
show fcast.line

d(noerr) yf
