*
* @TsayTest(threshold=threshold series,other options) depvar start end
* # regressors in regression format.
*
* This performs an arranged regression test for threshold
* autoregression. 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.
*
* Options:
*   THRESHOLD=series to use for threshold values
*   D=delay for threshold series [0]
*
*   TITLE=title for output ["Tsay Arranged Autoregression Test"]
*   [PRINT]/NOPRINT   NOPRINT suppresses the printed output
*   GRAPH/[NOGRAPH]   If GRAPH, a SCATTER plot of the threshold series
*                     against the recursive residuals is created.
*
* Variables Defined:
*
*   %CDSTAT   the computed test statistic (REAL)
*   %SIGNIF   the marginal significance level (REAL)
*
* Example: (2 lag autoregression, threshold variable is lag one).
*
*   @tsaytest(threshold=y,d=1) y
*   # constant y{1 2}
*
* Reference:
*   Tsay(1989), "Testing and Modeling Threshold Autoregressive Processes",
*    JASA, vol 84, no 405, pp 231-240.
*
*  Revision schedule:
*    05/2002 Written by Tom Doan, Estima.
*    09/2007 Add PRINT and GRAPH options
*    08/2010 Rewritten to use RLS with ORDER option.
*    11/2010 Add TITLE option
*    11/2017 Add D option. Put output into report
*
procedure tsaytest depvar start end
type series  	depvar
type integer 	start  end
*
option series 	threshold
option switch 	print    1
option switch 	graph    0
option string  title
option integer d        0
*
local series   rresid lthresh
local equation tareqn
local report   treport
local string   ltitle
*
* Pull in the regressors to define the equation.
*
equation tareqn depvar
*
* 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
}
set lthresh = threshold{d}
*
* Compute the recursive least squares estimates ordered by the threshold.
*
rls(noprint,equation=tareqn,order=lthresh) * start end
*
* Regress the recursive residuals on the regressors.
*
set rresid = %resids
linreg(equation=tareqn,noprint,smpl=%valid(rresid)) rresid %regstart() %regend()
test(zeros,all,noprint)
*
if %defined(title)
   compute ltitle=title
else
   compute ltitle="TSAY Arranged Autoregression Test"
*
report(use=treport,action=define,title=ltitle)
report(use=treport,atrow=1,atcol=1,span) ltitle
report(use=treport,atrow=2,atcol=1) "F("+%nreg+","+(%nobs-%nreg)+")" %cdstat "Signif" %signif
report(use=treport,action=format,picture="*.###")
if print
   report(use=treport,action=show)

if graph {
   scatter(footer="Arranged Autoregression Test",$
      hlabel="Threshold series",vlabel="Residual")
   # lthresh rresid
}
end
