*
*  For a input series x which shows two states (1,0), computes a run test
*
*  Syntax: @RunTest( options )  x  start end
*  Parameters:
*     x  input series
*     start end   range to analyze [by default, the defined range of x]
*
*  Options:
*    [ESTIMATE]/NOESTIMATE  indicates whether the prob(success) should be estimated or input
*    PI=input probability of 1 [.5] (used if NOESTIMATE)
*
*  Variables Created:
*    %CDSTAT = test statistic (asymptotically N(0,1))
*    %SIGNIF = significance level
*
*  Revision Schedule:
*   10/2002 Written by Tom Doan, Estima
*   05/2007 Minor revisions to output
*
proc RunTest x start end
type series x
type integer start end
*
option switch estimate 1
option real pi 0.5
*
local integer startl endl i runs k n
local real last pix z
*
inquire(series=x) startl>>start endl>>end
*
*  last = value of last valid observation
*  k    = number of observations where x==1
*  n    = number of valid observations
*  runs = number of runs. This is initialized to one, as the first value
*         won't trigger an increment under the logic below. It's incremented
*         each time a valid observation differs from the one which preceded it.
*
compute last=%na
compute runs=1
compute k=0
compute n=0
*
do i=startl,endl
   if %valid(x(i)) {
      if %valid(last).and.x(i)<>last
         compute runs=runs+1
      compute k=k+fix((x(i)==1))
      compute n=n+1
      compute last=x(i)
   }
end do i
*
* If the (default) of estimate is on, the probability of success is estimate using
* k and n Otherwise, the input value is used.
*
if estimate==1
   compute pix=float(k)/n
else
   compute pix=pi
*
* The asymptotic z-score is used. This is the continuity corrected statistic. See
* e.g. Campbell, Lo, MacKinlay, "The Econometrics of Financial Markets"
*
compute z=(runs+.5-2*n*pix*(1-pix))/(2*sqrt(n*piX*(1-pix)*(1-3*pix*(1-pix))))
disp "Run Test for Series "+%l(x)
disp runs "Runs in" n "Observations. Prob(success) = " pix
disp "Z-score" z "p-value" #.##### %ztest(z)
compute %cdstat=z,%signif=%ztest(z)
end

