'get starting values for ARMA using fast Hannan-Rissanen algorithm
'version 4 
'9/21/2000 h

'y = (input) dependent variable
'p = (input) AR order
'q = (input) MA order
'ar0 = (input) AR order for 1st state long autoregression
'p0 = (output) filled with starting coefficient values
'	  const | ar(1) | ar(2) | ... | ma(1) | ma(2) | ... | s^2

subroutine local sub_HannanRissanen(series y, scalar p, scalar q, scalar ar0, vector p0)
'check input
if (p<0 or q<0 or ar0<0) then
	statusline input order cannot be negative!
	stop
endif
'set const starting to mean
p0(1) = @mean(y)
'demean series
series y1 = y - p0(1)
'1st stage long autoregression
%tmp = ""
for !i=1 to ar0
	%tmp = %tmp + "ar(" + @str(!i) + ") "
next
equation tmp1.ls y1	{%tmp}
'2nd stage OLS
tmp1.makeresid res
%tmp = ""
for !i=1 to p
	%tmp = %tmp + "y1(-" + @str(!i) + ") "
next
for !i=1 to q
	%tmp = %tmp + "res(-" + @str(!i) + ") "
next
tmp1.ls y1 {%tmp}
'store AR coefs
for !i=1 to p
	p0(!i+1) = tmp1.c(!i)
next
'store MA coefs
for !i=1 to q
	p0(!i+1+p) = tmp1.c(!i+p)
next
'compute residual covariance
tmp1.makeresid res
p0(2+p+q) = @sumsq(res)/@obs(res)
endsub

