*
* @RunTest( options )  x  start end
* computes a run test for an input series which shows two states (1,0).
*
* 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)
*
*   [PRINT]/NOPRINT
*   TITLE="title for report" ["Runs Test for Series ..."]
*
* 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
*   09/2014 Change to use REPORT. Add check for invalid input.
*           Add PRINT and TITLE options.
*
proc RunTest x start end
type series x
type integer start end
*
option switch estimate 1
option real   pi       0.5
option switch print    1
option string title
*
local integer startl endl i runs k n
local real    last pix z
local report  rreport
local string  ltitle
*
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 x(i)<>0.and.x(i)<>1 {
         disp "@RUNTEST needs input series which is 0-1 dummy"
         return
      }
      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))))
*
compute %cdstat=z,%signif=%ztest(z)
*
if %defined(title)
   compute ltitle=title
else
   compute ltitle="Run Test for Series "+%l(x)
*
report(use=rreport,action=define,title=ltitle)
report(use=rreport,atrow=1,atcol=1,span) ltitle
report(use=rreport,atrow=2,atcol=1) "Observations"  n
report(use=rreport,atrow=3,atcol=1) "Runs"          runs
report(use=rreport,atrow=4,atcol=1) "Prob(success)" pix
report(use=rreport,atrow=5,atcol=1) "Z-score"       z
report(use=rreport,atrow=6,atcol=1) "P-value"       %ztest(z)
*
report(use=rreport,action=format,atcol=2,atrow=4,torow=5,picture="*.###",align=decimal)
report(use=rreport,action=format,atcol=2,atrow=6,picture="#.####")
*
if print
   report(use=rreport,action=show)
*
end
