*
*  This performs an arranged regression test for threshold autoregression as
*  described in Tsay, "Testing and Modeling Threshold Autoregressive Processes",
*  JASA 1989, pp 231-240.
*
*  Syntax:
*
*  @tsaytest(threshold=threshold series) depvar start end
*  # regressors
*
*  The regressors aren't required to be lags of depvar only. If the threshold series
*  is a lag of a variable, you will have to create it as a separate series.
*
*  Example (2 lag autoregression, threshold variable is lag one).
*
*  set z = y{1}
*  @tsaytest(threshold=z) y
*  # constant y{1 2}
*
*  Revision schedule:
*    May 2002, Written by Tom Doan, Estima.
*
procedure tsaytest depvar start end
type series  depvar
type integer start  end
*
option series threshold
option switch print 1
option switch graph 0
*
local vec[integer] regressors
local series copy ix rresid initsmpl
local equation tareqn
local integer startl endl initend atime
*
*  Pull in the regressors
*
enter(varying) regressors
*
*  Check to make sure that the threshold and depvar series have been provided
*
if .not.%defined(threshold).or..not.%defined(depvar) {
   display "Syntax: @tsaytest(threshold=threshold series) depvar start end"
   display "        # list of regressors"
   return
}
*
*  Create the working equation and a system including just the one equation
*
equation tareqn depvar
# regressors
*
system tareqn
end(system)
*
*  Figure out the maximum range supported by the variables involved.
*
inquire(regressorlist) startl>>start endl>>end
# depvar regressors threshold
*
*  Make a copy of the threshold variable and sort it, along with a series of
*  entry numbers. (We can't just use RANK on ORDER because it will map ties
*  to an average rank).
*
set copy startl endl = threshold
set ix   startl endl = t
*
order copy startl endl ix
*
*  Figure out which entries should be included in the initializing regression
*  Set a SMPL series to include just those entries. The entire recursive
*  regression process keeps the original data in place, and uses the ADD option
*  on KALMAN to add the entries in the arranged order.
*
compute initend=startl+%eqnsize(tareqn)-1
set initsmpl startl endl = 0.0
do atime=startl,initend
   compute initsmpl(fix(ix(atime)))=1.0
end do atime
*
estimate(noprint,smpl=initsmpl) startl endl rresid
do atime=initend+1,endl
  kalman(add=fix(ix(atime)),rtype=recursive) rresid
end do atime
*
*  Flip the SMPL series around so it excludes the initializing observations
*  which have forced zero residuals.
*
set initsmpl = 1.0-initsmpl
linreg(noprint,smpl=initsmpl) rresid startl endl
# regressors
exclude(noprint)
# regressors
if print {
   disp "TSAY Arranged Autoregression Test"
   disp "F(" %nreg "," %nobs-%nreg ")=" %cdstat "P=" %signif
}
if graph {
   scatter
   # copy rresid
}
end

