\documentclass[a4paper,10pt]{article} \usepackage{geometry,gretlhds} \usepackage{url,fancyvrb} \usepackage{pifont} \usepackage[utf8]{inputenc} \usepackage{graphicx} \usepackage[authoryear]{natbib} \usepackage{color} \usepackage{dcolumn,amsmath} \usepackage{hyperref} \newenvironment{funcdoc}[1] {\noindent\hrulefill\newline\nopagebreak\texttt{#1}% \nopagebreak\par\noindent\hrulefill% \nopagebreak\par\nopagebreak\smallskip\nopagebreak\par} {\bigskip} % ---------- Ripped from gretl.sty ---------------------------------------- \newcommand{\scriptname}{Listing} \newcommand{\app}[1]{\textsf{#1}} \newcommand{\cmd}[1]{\texttt{#1}} \newcommand{\dtk}[1]{\texttt{\detokenize{#1}}} \newcommand{\varname}[1]{\texttt{#1}} \newcommand{\option}[1]{\texttt{-{}-#1}} \newcommand{\ttsl}[1]{\ttfamily{\textsl{#1}}\normalfont} \newenvironment{textcode}{\par\small\ttfamily} {\normalfont\normalsize\par} \DefineVerbatimEnvironment% {code}{Verbatim} {fontsize=\small, xleftmargin=1em} \DefineVerbatimEnvironment% {scode}{Verbatim} {frame=lines, framesep=2ex, fontsize=\footnotesize, formatcom=\color{myteal}, rulecolor=\color{mygray}} \DefineVerbatimEnvironment% {scodebit}{Verbatim} {fontsize=\small, formatcom=\color{myteal}} \DefineVerbatimEnvironment% {scodebot}{Verbatim} {frame=bottomline, framesep=2ex, fontsize=\small, formatcom=\color{myteal}, rulecolor=\color{mygray}} \renewcommand{\arraystretch}{1.2} \definecolor{mygray}{rgb}{0.85,0.85,0.85} \definecolor{myteal}{rgb}{0.0,0.25,0.15} \definecolor{steel}{rgb}{0.03,0.20,0.45} \def\floatpagefraction{.8} %% add script as float (Listing) \newcounter{script}[section] \renewcommand \thescript {\ifnum \c@chapter>\z@ \thechapter.\fi \@arabic\c@script} \def\fps@script{tbp} \def\ftype@script{1} \def\ext@script{los} \def\fnum@script{\scriptname\nobreakspace\thescript} \newenvironment{script} {\@float{script}} {\end@float} \newenvironment{script*} {\@dblfloat{script}} {\end@dblfloat} \bibliographystyle{apalike} % ---------- End rip ------------------------------------------------------ \newcommand{\PrE}[1]{\ensuremath u_{#1}} % was \varepsilon_{#1} pre v1.95 \newcommand{\StS}[1]{\ensuremath \varepsilon_{#1}} % was u_{#1} pre v1.95 \newcommand{\InfSet}[1]{\ensuremath \mathcal{F}_{#1}} \newcommand{\VarSym}{\ensuremath \Phi} \newcommand{\IRF}[1]{\ensuremath \mathcal{I}_{#1}} \newcommand{\FEVD}[1]{\ensuremath \mathcal{VD}_{#1}} \newcommand{\pder}[2]{\ensuremath\frac{\partial #1}{\partial #2}} \DeclareMathOperator{\VEC}{\mathrm{vec}} \newlength{\irfw} \newlength{\irfh} \setlength{\irfw}{6.5cm} \setlength{\irfh}{35mm} \newcommand{\rk}[1]{\mathrm{rank}\left(#1\right)} \hypersetup{pdftitle={The SVAR addon for gretl}, pdfauthor={Jack Lucchetti and Sven Schreiber}, colorlinks=true, linkcolor=blue, urlcolor=red, citecolor=steel, bookmarks=true, bookmarksnumbered=true, plainpages=false } \title{The SVAR addon for \app{gretl}} \author{Jack Lucchetti and Sven Schreiber} \date{October 2024} \begin{document} \maketitle \tableofcontents \clearpage \section{Introduction} \label{sec:intro} The \texttt{SVAR} package is a collection of \app{gretl} functions to estimate Structural VARs, or SVARs for short. In the remainder of this guide, the emphasis will be put on the scripting interface, which is the recommended way of using the package. However, most of its features are also accessible via the ``Structural VAR'' menu entry (go to \emph{Model $>$ Time Series $>$ Multivariate}) and the corresponding menu-driven interface. The impatient reader, who already has some understanding of what a SVAR is and is looking for a step-by-step guide on how to get her work done quickly via point-and click methods, can consult section \ref{sec:GUI} in the Appendix. In order to establish notation\footnote{Attention: Starting in v1.95 we have changed the notation in an important way, by swapping the symbols for the structural shocks and the reduced-form residuals (forecast errors). The reason is that most of the recent literature uses $u$ for the reduced-form errors, and now we do so, too, which hopefully makes everything a bit easier for users.} and define a few concepts, allow us to inflict on you a 2-page crash course on SVARs. In this context,\footnote{The adjective ``structural'' is possibly one of the most widely used and abused in econometrics. In other contexts, it takes a totally different, and unrelated, meaning.} we call ``structural'' a model in which we assume that the one-step-ahead prediction errors $\PrE{t}$ from a statistical model can be thought of as linear functions of the \emph{structural shocks} $\StS{t}$. In its most general form, a structural model is the pair of equations \begin{eqnarray} \label{eq:one-step-ahead} \PrE{t} & = & y_t - E(y_t | \InfSet{t-1}) \\ \label{eq:PrE-StS-AB} A \PrE{t} & = & B \StS{t} \end{eqnarray} where $\InfSet{t-1}$ is the information set at $t-1$. In practically all cases, the statistical model is a a finite-order VAR and equation \eqref{eq:one-step-ahead} specialises to \begin{equation} \label{eq:VAR} y_t = \mu' x_t + \sum_{i=1}^p \VarSym_i y_{t-i} + \PrE{t} \qquad\mathrm{or}\qquad \VarSym(L) y_t = \mu' x_t + \PrE{t} \end{equation} where the VAR may include an exogenous component $x_t$, which typically contains at least a constant term. The above model is referred to as the AB-model in Amisano-Giannini (1997). The object of estimation are the square matrices $A$ and $B$; estimation is carried out by maximum likelihood. After defining $C$ as $A^{-1}B$, the relationship between prediction errors and structural shocks becomes \begin{equation} \label{eq:PrE-StS-C} \PrE{t} = C \StS{t} \end{equation} and under the assumption of normality the average log-likelihood can be written as \[ \mathcal{L} = \mathrm{const} - \ln |C| - 0.5 \cdot \mathrm{tr}(\hat{\Sigma} (CC')^{-1}) \] As is well known, the above model is under-identified and in order for the log-likelihood to have a (locally) unique maximum, it is necessary to impose some restrictions on the matrices $A$ and $B$. This issue will be more thoroughly discussed in section \ref{sec:SVARid}; for the moment, let's just say that some the elements in $A$ and $B$ have to be fixed to pre-specified values. The minimum number of restrictions is $n^2 + \frac{n^2 - n}{2}$. This, however, is a necessary condition, but not sufficient by itself. The popular case in which $A=I$ is called a C-model. Further, a special case of the C-model occurs when $B$ is assumed to be lower-triangular. This was \citeauthor{sims80}'s (\citeyear{sims80}) original proposal, and is sometimes called a ``recursive'' identification scheme. It has a number of interesting properties, among which the fact that the ML estimator of $C$ is just the Cholesky decomposition of $\hat{\Sigma}$, the sample covariance matrix of VAR residuals. This is why many practitioners, including ourselves, often use the ``recursive model'' and ``Cholesky model'' phrases interchangeably. This has been the most frequently used variant of a SVAR model, partly for its ease of interpretation, partly for its ease of estimation.\footnote{Some may say ``partly for the unimaginative nature of applied economists, who prefer to play safe and maximise the chances their paper isn't rejected rather than risk and be daring and creative''. But who are we to judge?} In the remainder of this document, a lower-triangular C model will be called a ``plain'' SVAR model. If the model is just-identified, $\hat{\Sigma} (CC')^{-1}$ will be the identity matrix and the log-likelihood simplifies to \[ \mathcal{L} = \mathrm{const} - 0.5 \ln |\hat{\Sigma}| - 0.5 n \] Of course, it is possible to estimate constrained models by imposing some extra restrictions; this makes it possible to test the over-identifying restrictions easily by means of a LR test. Except for trivial cases, like the Cholesky decomposition, maximisation of the likelihood involves numerical iterations. Fortunately, analytical expressions for the score, the Hessian and the information matrix are available, which helps a lot;\footnote{As advocated in \citeauthor{AG}, the scoring algorithm is used by default, but several alternatives are available. See subsection \ref{sec:algorithms} below.} once convergence has occurred, the covariance matrix for the unrestricted elements of $A$ and $B$ is easily computed via the information matrix. Once estimation is completed, $\hat{A}$ and $\hat{B}$ can be used to compute the structural VMA representation of the VAR, which is the base ingredient for most of the subsequent analysis, such as Impulse Response Analysis and so forth. If the matrix polynomial $\VarSym(L)$ in equation \eqref{eq:VAR} is invertible, then (assuming $x_t=0$ for ease of notation), $y_t$ can be written as \begin{equation} \label{eq:vma} y_t = \VarSym(L)^{-1}\PrE{t} = \Theta(L) \PrE{t} = \PrE{t} + \Theta_1 \PrE{t-1} + \cdots \end{equation} which is known as the VMA representation of the VAR. Note that in general the matrix polynomial $\Theta(L)$ is of infinite order. From the above expression, one can write the \emph{structural} VMA representation as \begin{equation} \label{eq:svma} y_t = C \StS{t} + \Theta_1 C \StS{t-1} + \cdots = M_0 \StS{t} + M_1 \StS{t-1} + \cdots \end{equation} From equation \eqref{eq:svma} it is immediate to compute the impulse response functions: \begin{equation} \label{eq:IRFdef} \IRF{i,j,h} = \pder{y_{i,t}}{\StS{j, t-h}} = \pder{y_{i,t+h}}{\StS{j, t}} \end{equation} which in this case equal simply \[ \IRF{i,j,h} = \left[ M_h \right]_{ij} \] The computation of confidence intervals for impulse responses could, in principle, be performed analytically by the delta method (see \cite{Lut90}). However, this has two disadvantages: for a start, it is quite involved to code. Moreover, the limit distribution has been shown to be a very poor approximation in finite samples (see for example \cite{FaBra96} or \cite{Kilian98}), so the bootstrap is almost universally adopted, although in some cases it may be quite CPU-heavy. %\pagebreak[4] \section{C models} \label{sec:Cmodel} \subsection{A simple example} As a trivial example, we will estimate a plain Cholesky model. The data are taken from Stock and Watson's sample data \dtk{sw_ch14.gdt}, and our VAR will include inflation and unemployment, with a constant and 3 lags. Then, we will compute the IRFs and their 90\% bootstrap confidence interval.\footnote{Why not 95\%? Well, keeping the number of bootstrap replications low is one reason. Anyway, it must be said that in the SVAR literature few people use 95\%. 90\%, 84\% or even 66\% are common choices.} %\subsubsection{Gretl native \texttt{var} command} In order to accomplish the above, note that we \emph{don't} need to use the \texttt{SVAR} package, as a Cholesky SVAR can be handled by \texttt{gretl} natively. In fact, the script shown in Table \ref{InternalChol-in} does just that: runs a VAR, collects $\hat{\Sigma}$ and estimates $C$ as its Cholesky decomposition. Part of its output is in Table \ref{InternalChol-out}. The impulse responses as computed by \texttt{gretl}'s internal command can be see in Figure \ref{fig:nativeIRF}. See the Gretl User's Guide for more details. \begin{table}[htbp] \begin{scode} # turn extra output off set verbose off # open the data and do some preliminary transformations open sw_ch14.gdt genr infl = 400*ldiff(PUNEW) rename LHUR unemp list X = unemp infl var 3 unemp infl Sigma = $sigma C = cholesky(Sigma) print Sigma C \end{scode} %$ \caption{Cholesky example via \texttt{gretl}'s internal \texttt{var} command} \label{InternalChol-in} \end{table} \begin{table}[htbp] \centering \begin{scode} VAR system, lag order 3 OLS estimates, observations 1960:1-1999:4 (T = 160) Log-likelihood = -267.76524 Determinant of covariance matrix = 0.097423416 AIC = 3.5221 BIC = 3.7911 HQC = 3.6313 Portmanteau test: LB(40) = 162.946, df = 148 [0.1896] Equation 1: u coefficient std. error t-ratio p-value -------------------------------------------------------- const 0.137300 0.0846842 1.621 0.1070 u_1 1.56139 0.0792473 19.70 8.07e-44 *** u_2 -0.672638 0.140545 -4.786 3.98e-06 *** ... Sigma (2 x 2) 0.055341 -0.028325 -0.028325 1.7749 C (2 x 2) 0.23525 0.0000 -0.12041 1.3268 \end{scode} \caption{Cholesky example via \texttt{gretl}'s internal \texttt{var} command --- Output} \label{InternalChol-out} \end{table} \begin{figure}[htbp] \centering \includegraphics{simpleC_gretl} \caption{Impulse response functions for the simple Cholesky model (native)} \label{fig:nativeIRF} \end{figure} %\clearpage \subsection{Base estimation via the \texttt{SVAR} package} \label{sec:baseest} We will now replicate the above example via the \texttt{SVAR} package; in order to do so, we need to treat this model as a special case of the C-model, where $\PrE{t} = C \StS{t}$ and identification is attained by stipulating that $C$ is lower-triangular, that is \begin{equation} \label{eq:cholesky} C = \left[ \begin{array}{ll} c_{11} & 0 \\ c_{12} & c_{22} \end{array} \right]. \end{equation} \begin{table}[htbp] \begin{scode} # turn extra output off set verbose off # open the data and do some preliminary transformations open sw_ch14.gdt genr infl = 400*ldiff(PUNEW) rename LHUR unemp list X = unemp infl list Z = const # load the SVAR package include SVAR.gfn # set up the SVAR Mod = SVAR_setup("C", X, Z, 3) # Specify the constraints on C SVAR_restrict(&Mod, "C", 1, 2, 0) # Estimate SVAR_estimate(&Mod) \end{scode} \caption{Simple C-model} \label{tab:simpleC-base} \end{table} Table \ref{tab:simpleC-base} shows a sample script to estimate the example Cholesky model: the basic idea is that the model is contained in a \app{gretl} bundle.\footnote{Bundles are containers in which a certain object (a scalar, a matrix and so on) is associated to a ``key'' (a string). Technically speaking, a bundle is an associative array like ``hashes'' in Perl or ``dictionaries'' in Python. Fore more info, you'll want to take a look at the Gretl User's Guide, section 11.7.} In this example, the bundle is called \texttt{Mod}, but it can of course take any valid \texttt{gretl} identifier. After performing the same preliminary steps as in the example in Table \ref{InternalChol-in}, we load the package and use the \dtk{SVAR_setup} function, which initialises the model and sets up a few things. This function takes 4 arguments: \begin{itemize} \item a string, with the model type (\texttt{"C"} in this example); \item a list containing the endogenous variables $y_t$; \item a list containing the exogenous variables $x_t$ (may be \texttt{null}); \item the VAR order $p$. \end{itemize} Once the model is set up, you can specify which elements you want to constrain to achieve identification: in fact, the key ingredient in a SVAR is the set of constraints we put on the structural matrices. \texttt{SVAR} handles these restrictions via their implicit form representation $R \theta = d$. As an example, the constraints for the simple case we're considering here can be written in implicit form as \[ R \VEC C = d \] where $R = \left[ 0, 0, 1, 0 \right]$ and $d=0$. There are several ways to constrain a model: the easiest way is to use the \dtk{SVAR_restrict} function, which should be enough in most cases; for alternatives, jump to section \ref{sec:OtherConstraints}. A complete description of the the \dtk{SVAR_restrict} function can be found in appendix \ref{sec:syntax}; suffice it to say here that the result of the function \begin{code} SVAR_restrict(&Mod, "C", 1, 2, 0) \end{code} is to ensure that $C_{1,2} = 0$ (see eq.~\ref{eq:cholesky}). The next step is estimation, which is accomplished via the \dtk{SVAR_estimate} function, which just takes one argument, the model to estimate. The output of the \dtk{SVAR_estimate} function is shown below:\footnote{For compatibility with other packages, $\hat{\Sigma}$ is estimated by dividing the cross-products of the VAR residuals by $T-k$ instead of $T$; this means that the actual figures will be slightly different from what you would obtain by running \texttt{var} and then \texttt{cholesky(\$sigma)}.} note that, as an added benefit, we get asymptotic standard errors for the estimated parameters (estimated via the information matrix).\footnote{You may feel surprised by the fact that in our example the $z$-statistics for two elements of the $C$ matrix are exactly the same. This is no coincidence: in short, the reason why this happens is that the parameter covariance matrix is computed from the information matrix, which is a function of $C$ itself \citep[see][for more details]{AG}. On the other hand, the test shouldn't be taken literally, as under the null hypothesis $C_{11} = 0$ or $C_{22} = 0$ the covariance matrix would become singular, and all the relevant asymptotic theory would break down. To be on the safe side, just take the $z$ values as descriptive statistics in these cases.} \begin{code} Unconstrained Sigma: 0.05676 -0.02905 -0.02905 1.82044 coefficient std. error z-stat p-value -------------------------------------------------------- C[ 1; 1] 0.238243 0.0131548 18.11 2.62e-73 *** C[ 2; 1] -0.121939 0.105142 -1.160 0.2461 C[ 1; 2] 0.00000 0.00000 NA NA C[ 2; 2] 1.34371 0.0741942 18.11 2.62e-73 *** \end{code} At this point, the model bundle contains all the quantities that will need to be accessed later on, including the structural VMA representation \eqref{eq:svma}, which is stored in a matrix called \texttt{IRFs} which has $h$ rows and $n^2$ columns. Each row $i$ of this matrix is $\VEC(M_i)'$, so if you wanted to retrieve the IRF for variable $m$ with respect to the shock $k$, you'd have to pick its $[(k-1)\cdot n + m]$-th column. The number of rows $h$ is closely related to the ``horizon''. The function \dtk{SVAR_setup} initialises automatically the horizon to 24 for monthly data and to 20 for quarterly data. To change it, you just assign the desired value to the \texttt{horizon} element of the bundle, as in \begin{code} Mod.horizon = 40 \end{code} (Since the contemporaneous impact effect is also part of the IRFs, the matrix will have one more row than this horizon specification.) Clearly, this adjustment has to be done \emph{before} the \dtk{SVAR_estimate} function is called. More details on the internal organisation of the bundle can be found in section \ref{sec:bundle_struct} in the appendix. Its contents can be accessed via the ordinary \app{gretl} syntactic constructs for dealing with bundles. For example, the number of observations used in estimating the model is stored as the bundle member \texttt{T}, so if you ever need it you can just use the syntax \texttt{Mod.T}. Once the model has been estimated, it becomes possible to retrieve estimates of the structural shocks, via the function \texttt{GetShocks}, as in: \begin{code} series foo = GetShock(&Mod, 1) series bar = GetShock(&Mod, 2) \end{code} If we append the two lines above to example \ref{tab:simpleC-base}, two new series will be obtained. The formula used is nothing but equation \eqref{eq:PrE-StS-C} in which the VAR residuals are used in place of $\PrE{t}$. \bigskip \textbf {Warning:} If you are working on a subsample of your dataset, keep in mind that the SVAR package follows a different convention than \app{gretl} for handling the actual start of your sample. Ordinary \app{gretl} commands, such as \cmd{var}, will use data prior to your subsampling choice for lags, if present. The SVAR package, on the contrary, will not. An example should make this clear: suppose your dataset starts at 1970Q1, but you restrict your sample range only to start at 1980Q1. The \app{gretl} commands \begin{code} smpl 1980:1 ; list X = x y z var 6 X \end{code} will estimate a VAR with 6 lags, in which the first datapoint for the dependent variable will be 1980Q1 and data from 1978Q3 to 1979Q4 will be used for initialising the VAR. However, \begin{code} smpl 1980:1 ; list X = x y z Mod = SVAR_setup("C", X, const, 6) \end{code} will estimate the same model on a different dataset: that is, the first available datapoint for estimation will be 1981Q3 because data from 1980Q1 to 1981Q2 will be needed for lagged values of the $y_t$ variables. \subsection{Algorithm choice} \label{sec:algorithms} Another thing you may want to toggle before calling \dtk{SVAR_estimate} is the optimisation method: you do this by setting the bundle element \texttt{optmeth} to some number between 0 and 4; its meaning is shown below: \begin{center} \begin{tabular}{rl} \hline \texttt{optmeth} & Algorithm \\ \hline 0 & BFGS (numerical score) \\ 1 & BFGS (analytical score) \\ 2 & Newton-Raphson (numerical score) \\ 3 & Newton-Raphson (analytical score) \\ 4 & Scoring algorithm (\textbf{default}) \\ \hline \end{tabular} \end{center} So in practice the following code snippet \begin{code} Mod.optmeth = 3 SVAR_estimate(&Mod) \end{code} would estimate the model by using the Newton-Raphson method, computing the Hessian by numerically differentiating the analytical score. In most cases, the default choice will be the most efficient; however, it may happen (especially with heavily over-identified models) that the scoring algorithm fails to converge. In those cases, there's no general rule. Experiment! \subsection{Displaying the Impulse Responses} \label{sec:IRF-FEVD} The \texttt{SVAR} package provides a function called \texttt{IRFplot} for plotting the impulse response function on your screen, with a little help from our friend \texttt{gnuplot}; its syntax is relatively simple. \texttt{IRFplot} requires three arguments: \begin{enumerate} \item The model bundle (as a pointer); \item the number of the structural shock we want the IRF to; \item the number of the variable we want the IRF for. \end{enumerate} For example, \begin{code} IRFplot(&Mod, 1, 1) \end{code} The function can be used in a more sophisticated way than this (see later). Its output is presented in Figure \ref{fig:simpleC-noboot.IRF}. As can be seen, it's very similar to the one obtained by \texttt{gretl}'s native command (Figure \ref{fig:nativeIRF}). \begin{figure}[htbp] \centering \includegraphics[scale=0.7]{simpleC_11_noboot} \caption{Impulse response functions for unemployment} \label{fig:simpleC-noboot.IRF} \end{figure} By the way: you can attach labels to the structural shocks if you want. Just store an array of strings with the appropriate number of elements into the model bundle, under the \texttt{snames} key. For example, \begin{code} Mod.snames = strsplit("foo bar baz") \end{code} If you omit this step, the structural shocks will be labelled with names corresponding to the observable variables in your VAR. This doesn't make particular sense in general, but it does in a triangular model, in which there is a one-to-one correspondence, so we decided to make this the default choice. A word on the unit of measurement of IRFs: by their definition (see equation \eqref{eq:IRFdef}), clearly their unit of measurement is the same as the one for the corresponding observable variable $y_{i,t}$. % [old:] % Given that the structural shocks are normalized to have unit % variance, the conventionally used unit size innovation is at the same % time a standard deviation shock. % The direct impact effect in the same % equation then depends on the respective diagonal element of $C$. % [New:] The conventional normalization of unit variances of the structural shocks and of the association of shocks to equations implies that the impact of the i-th structural unit size shock on the i-th variable will be just one standard deviation of the i-th reduced-form error. This is often referred to as a one-standard-deviation shock. % [end new] Sometimes, however, a different convention is adopted, and people want to display IRFs graphically by normalizing the impact effect $\IRF{i,i,0} = 1$. This representation is often labeled as a unit shock, and the necessary division by the respective standard deviation of the reduced-form errors can be achieved by setting the bundle member \cmd{normalize} to 1, as in \begin{code} Mod.normalize = 1 \end{code} before calling \cmd{IRFplot}. Setting it back to its default value of 0 will restore standard behavior. \subsection{Bootstrapping} \label{sec:bootstrap} \begin{table}[htbp] \begin{scode} bfail = SVAR_boot(&Mod, 1024, 0.90) loop i = 1..2 loop j = 1..2 sprintf fnam "simpleC_%d%d.pdf", i, j IRFsave(fnam, &Mod, i, j) end loop end loop \end{scode} \caption{Simple C-model (continued)} \label{tab:simpleC-IRF} %$ \end{table} The next step is computing bootstrap-based confidence intervals for the estimated coefficients and, more interestingly, for the impulse responses: as can be seen in Table \ref{tab:simpleC-IRF}, this task is given to the \dtk{SVAR_boot} function, which takes as arguments \begin{enumerate} \item The model bundle pointer; \item the required number of bootstrap replications (1024 here), which can be omitted if the default value of 2000 is satisfactory;\footnote{There's a hard limit at 16384 at the moment; probably, it will be raised in the future. However, unless your model is very simple, anything more than that is likely to take forever and melt your CPU.} \item the desired size of the confidence interval $\alpha$ (with a default of 0.9 or 90\% coverage probability, so it could have been omitted in the example above). \end{enumerate} For further optional arguments see below and the function reference in the appendix. The function outputs a scalar, which keeps track of how many bootstrap replications failed to converge (none here). Note that this procedure may be quite CPU-intensive. The function can also return in output a table similar to the output to \texttt{Cmodel}, which is used to display the bootstrap means and standard errors of the parameters: \begin{code} Bootstrap results (1024 replications) coefficient std. error z p-value --------------------------------------------------------- C[ 1; 1] 0.232146 0.0183337 12.66 9.57e-37 *** C[ 2; 1] -0.114610 0.143686 -0.7976 0.4251 C[ 1; 2] 0.00000 0.00000 NA NA C[ 2; 2] 1.30234 0.0853908 15.25 1.61e-52 *** Failed = 0, Time (bootstrap) = 20.24 \end{code} This can be achieved by supplying a zero fourth argument to the \dtk{SVAR_boot} function, as in \begin{code} bfail = SVAR_boot(&Mod, 1024, 0.90, 0) \end{code} Once the bootstrap is done, its results are stored into the bundle for later use: upon successful completion, the model bundle will contain another bundle called \texttt{bootdata}. This contains some information on the bootstrap details, such as the confidence interval $\alpha$ and others; in addition, it will contain three matrices in which each column is one of the $n^2$ IRFs, and the rows contain \begin{enumerate} \item the lower limit of the confidence interval in the \dtk{lo_cb} matrix; \item the upper limit of the confidence interval in the \dtk{hi_cb} matrix; \item the medians in the \texttt{mdns} matrix. \end{enumerate} where $h$ is the IRF horizon. In practice, the bootstrap results may be retrieved as follows (the medians in this example): \begin{code} bfail = SVAR_boot(&Mod, 1024, 0.90) scalar h = Mod.horizon bundle m = Mod.bootdata matrix medians = m.mdns \end{code} However, if you invoke \texttt{IRFplot()} after the bootstrap, the above information will be automatically used for generating the graph. In this case, you may supply \texttt{IRFplot()} with a fourth argument, an integer from 0 to 2, to place the legend to the right of the plot (value: 1), below it (value: 2) or omit it altogether (value: 0). The default, which applies if you omit the parameter, is 1. Another \texttt{SVAR} function, \texttt{IRFsave()}, is used to store plots the impulse responses into graphic files files for later use;\footnote{The format is dictated by the extension you use for the output file name: since this job is delegated to \texttt{gnuplot}, all graphical formats that \texttt{gnuplot} supports are available, including pdf, PostScript (via the extension \texttt{ps}), PNG (via the extension \texttt{png}) or Scalable Vector Graphics (via the extension \texttt{svg}). } its arguments are the same as \texttt{IRFplot()}, except that the first argument must contain a valid filename to save the plot into. In the above example, this function is used within a loop to save all impulse responses in one go. The output is shown in Figure \ref{fig:simpleC.IRF}. \begin{figure}[htbp] \centering \begin{tabular}{cc} \includegraphics[width=\irfw, height=\irfh]{simpleC_11} & \includegraphics[width=\irfw, height=\irfh]{simpleC_12} \\ \includegraphics[width=\irfw, height=\irfh]{simpleC_21} & \includegraphics[width=\irfw, height=\irfh]{simpleC_22} \end{tabular} \caption{Impulse response functions for the simple Cholesky model} \label{fig:simpleC.IRF} \end{figure} The default method for performing the bootstrap is the the most straightforward residual-based bootstrap, that is the one put forward by \cite{Runkle87}. As an alternative, one may use bias-correction, which comes in two flavors, both inspired by the procedure known as ``bootstrap-after-bootstrap'' \citep{Kilian98}. % Comment by Sven: % I don't think we have to belittle our bias correction by saying % that "fancy" alternatives are not implemented. Following our discussion, % those are not sooo fancy, after all. So I commented out the footnote. %\footnote{None of the % fancier alternatives listed, for example, in \cite{Brug06} are % available. They are planned, though.} The one which corresponds more closely to \citeauthor{Kilian98}'s procedure is what what we call the ``Full'' variant; The ``Partial'' variant applies the bias correction only for adjusting the VAR coefficients used for generating the bootstrap replications, but \emph{not} for computing the VMA representation. The interested user may want to experiment with both. The ``Partial'' and ``Full'' variant may either be enabled by setting the bundle member \texttt{biascorr} to 1 and 2, respectively, before calling \dtk{SVAR_boot}. For an example, look at the example file \dtk{bias_correction.inp}. Alternatively, that choice can be specified as the final (sixth) argument when calling \dtk{SVAR_boot}. Another bootstrap choice which can either be specified before the call to \dtk{SVAR_boot} or directly in that call is to use the so-called \emph{wild} bootstrap, or the residual-based moving blocks bootstrap (MBB) proposed by \cite{BrugJenTrenk16}. As regards the wild bootstrap, instead of resampling the residuals to create a new draw of artificial bootstrap data, for each time period $t$ it takes the original estimated residual vector and multiplies it by a random number $w_t$ with mean 0 and variance 1. This procedure is able to account for several forms of heteroskedasticity in the errors. For IRFs the MBB-based confidence bands may have better coverage properties especially at short horizons. Activate any of these options by setting the bundle member \texttt{boottype} to the appropriate value, as per the following table. \begin{center} \begin{tabular}{rccl} \hline \texttt{boottype} & Argument in \dtk{SVAR_boot} & Distribution & Description\\ \hline 1 & \emph{resampling}, \emph{resample} & (none) & non-wild\\ 2 & \emph{wild}, \emph{wildN} & Gaussian & $w_t \sim N(0,1)$ \\ 3 & \emph{wildR} & Rademacher & $P(w_t = \pm 1) = 0.5$ \\ 4 & \emph{wildM} & Mammen & $w_t = \begin{cases} -1/\phi & \frac{\phi}{\sqrt{5}} \\ \phi & 1 - \frac{\phi}{\sqrt{5}} \end{cases}$ \\ 5 & \emph{MBB} & (none) & moving blocks (non-wild) \\ \hline \end{tabular} \end{center} where $\phi$ is the golden ratio (about 1.1618). The value 1 is the default and implies the usual residual resampling. For example, the following invocation calls for a Gaussian wild bootstrap with partial bias correction (and through the 0 in fourth position activates the table printout as explained above): \begin{code} SVAR_boot(&Mod, 5000, 0.95, 0, "wild", 1) \end{code} Finally: if you change the \texttt{optmeth} bundle element before \dtk{SVAR_boot} is called, the choice affects the estimation of the bootstrap artificial models. Hence, you may use one method for the real data and another method for the bootstrap, if you so desire. If you use the MBB option you can also add the \texttt{movblocklen} bundle element (again, before the call to \dtk{SVAR_boot}) to give a positive integer that sets a non-automatic choice for the block length of the bootstrap innovations; the automatic choice currently being 10\% of the sample length. \subsection{More general restrictions and a shortcut} \label{sec:OtherConstraints} The internal element of the model bundle which contains the constraints for a C model is a matrix called \texttt{Rd1} and the number of its rows is kept as bundle element \texttt{nc1}. This matrix contains the restrictions in a C model of the form \[ R \VEC C = d \] by stacking horizontally the $R$ matrix and the $d$ vector, so that a matrix $R^* = [R | d ]$ is stored as \texttt{Rd1}. All the \dtk{SVAR_restrict} function does is adding rows to $R^*$ and checking for redundant or inconsistent restrictions. However, if you feel like building the matrix $R^*$ via \app{gretl}'s ordinary matrix functions, all you have to do is to fill up the bundle elements \texttt{Rd1} and \texttt{nc1} properly before calling \dtk{SVAR_estimate()}. As an example, take the script contained in Table \ref{tab:simpleC-base}, where we identify our C-model via the (rather silly) constraint $c_{11} = c_{12}$. The equation above would specialise to \[ [1 \quad -1 \quad 0 \quad 0 ] \VEC C = 0 \] and all you would have to do in order to modify the script to that effect would be substituting the line \begin{code} SVAR_restrict(&Mod, "C", 1, 2, 0) \end{code} with \begin{code} Mod.Rd1 = {1, -1, 0, 0, 0} Mod.nc1 = 1 \end{code} Estimating the resulting model would give you \begin{code} coefficient std. error z p-value ------------------------------------------------------- C[ 1; 1] 0.230119 0.0127062 18.11 2.62e-73 *** C[ 2; 1] 0.230119 0.0127062 18.11 2.62e-73 *** C[ 1; 2] -0.0616835 0.0182892 -3.373 0.0007 *** C[ 2; 2] 1.32947 0.0755748 17.59 2.87e-69 *** Log-likelihood = -276.913 \end{code} where the two first coefficients are equal, as required. That said, in many cases a triangular, Cholesky-style specification for the $C$ matrix like the one analysed in this section is all that is needed. When many variables are involved, the setting of the $\frac{n \times (n-1)}{2}$ restrictions via the \dtk{SVAR_restrict} function could be quite boring, although easily done via a loop. For these cases, the \texttt{SVAR} package provides an alternative way: if you supply the \dtk{SVAR_setup} function with the string \texttt{"plain"} as its first argument, the necessary restrictions are set up automatically. Thus, the example considered above in Table \ref{tab:simpleC-base} could by modified by replacing the lines \begin{code} Mod = SVAR_setup("C", X, Z, 3) SVAR_restrict(&Mod, "C", 1, 2, 0) \end{code} with the one-liner \begin{code} Mod = SVAR_setup("plain", X, Z, 3) \end{code} and leaving the rest unchanged. Of course, when you have two variables, such as in this case, there's not much difference, but for larger systems the latter syntax is much more convenient. Another advantage is that, in this case, the solution to the likelihood maximisation problem is known analytically, so no numerical optimisation technique is used at all. This makes computations much faster, and for example allows you to make extravagant choices on, for example, the number of bootstrap replications. Hence, if your C model can be rearranged as a plain triangular model, it is highly advisable to do so. \section{More on plotting} \label{sec:moreplots} Traditionally, analysis of the Impulse Response Functions has been the main object of interest in the applied SVAR literature, but is by no means the only one. After estimation, two more techniques are readily available for inspecting the results: the Forecast Error Variance Decomposition and the Historical Decomposition. Since the results from these two procedures are often visualised as graphs, we will describe them here. \subsection{Plotting the FEVD} \label{sec:fevdplots} Another quantity of interest that may be computed from the structural VMA representation is the Forecast Error Variance Decomposition (FEVD). Suppose we want to predict the future path of the observable variables $h$ steps ahead, on the basis of the information set $\InfSet{t-1}$. From equations \eqref{eq:vma} and \eqref{eq:svma} one obtains that \[ y_{t+h} - \hat{y}_{t+h} = \sum_{k=0}^h \Theta_k E(\PrE{t+h-k}) = \sum_{k=0}^h M_k E(\StS{t+h-k}) \] Since $E(\StS{t+h-k}) = I$ by definition, the forecast error variance after $h$ steps is given by \[ \Omega_h = \sum_{k=0}^h M_k M_k' \] hence the variance for variable $i$ is \[ \omega^2_i = \left[ \Omega_h \right]_{i,i} = \sum_{k=0}^h e_i' M_k M_k' e_i = \sum_{k=0}^h \sum_{l=1}^n ({}_km_{i.l})^2 \] where $e_i$ is the $i$-th selection vector,\footnote{That is, a vector with zeros everywhere except for a 1 at the $i$-th element.} so ${}_km_{i.l}$ is, trivially, the $i,l$ element of $M_k$. As a consequence, the share of uncertainty on variable $i$ that can be attributed to the $j$-th shock after $h$ periods equals \[ \FEVD{i,j,h} = \frac{\sum_{k=0}^h ({}_km_{i.j})^2 }{\sum_{k=0}^h \sum_{l=1}^n ({}_km_{i.l})^2 } . \] \begin{table}[htbp] \begin{scode} fevdmat = FEVD(&Mod) print fevdmat FEVDplot(&Mod, 1) FEVDplot(&Mod, 2) \end{scode} \caption{FEVD: computation and output} \label{tab:FEVDprint} \end{table} As shown in Table \ref{tab:FEVDprint}, after the model has been estimated, it can be passed to another function called \texttt{FEVD} to compute the Forecast Error Variance Decomposition, which is subsequently printed. Its usage is very simple, since it only needs one input (a pointer to the model bundle); like the \cmd{IRFplot} function, you can also attach an extra optional parameter at the end to control the position of the legend. \begin{figure}[htbp] \centering \begin{tabular}{cc} \includegraphics[width=\irfw, height=\irfh]{FEVD_1} & \includegraphics[width=\irfw, height=\irfh]{FEVD_2} \end{tabular} \caption{FEVD for the simple Cholesky model} \label{fig:FEVDplot} \end{figure} Since the FEVD for a particular variable is expressed in terms of shares, it is quite common to depict it graphically as a histogram, with the horizon on the x-axis. This can be accomplished rather simply in SVAR by using the specialised function \cmd{FEVDplot()}, which needs two arguments: a pointer to the model bundle and the number of the variable you want the FEVD for. Running the code in Table \ref{tab:FEVDprint} you should see two graphs similar to Figure \ref{fig:FEVDplot}. For saving the output to a file, its variant \cmd{FEVDsave()} works the same, except you need an extra argument (which goes first) with the filename you choose for the output.\footnote{See also the illustration of the \cmd{IRFsave} function at Section \ref{sec:bootstrap}.} \subsection{Historical decomposition} \label{sec:HD} \begin{table}[htbp] \begin{scode} # turn extra output off set verbose off # open the data and do some preliminary transformations open sw_ch14.gdt genr infl = 400*ldiff(PUNEW) rename LHUR unemp list X = unemp infl list Z = const # load the SVAR package include SVAR.gfn # set up the SVAR Mod = SVAR_setup("C", X, Z, 3) # Specify the constraints on C SVAR_restrict(&Mod, "C", 1, 2, 0) # Estimate SVAR_estimate(&Mod) # Save the historical decomposition as a list of series list HD_infl = SVAR_hd(&Mod, 2) # Just plot the historical decomposition for unemployment HDplot(&Mod, 2) \end{scode} \caption{Simple C-model with historical decomposition} \label{tab:simpleC-hd} \end{table} A natural extension of the FEVD concept (see sections \ref{sec:intro} and \ref{sec:IRF-FEVD}) is the so-called \emph{historical decomposition} of observed time series, which can be briefly described as follows. Consider the representations \eqref{eq:VAR} and \eqref{eq:svma}; clearly, if one could observe the parameters of the system (the coefficients of the $\VarSym(\cdot)$ polynomial and the matrix $\mu$) plus the sequence of structural shocks $\StS{t}$, it would be possible to decompose the observed path of the $y_t$ variables into $n + 1$ distinct components: first, a purely exogenous one, incorporating the term $\mu' x_t$ plus all the feedback effects given by the lag structure $\VarSym(L)$; this is commonly termed the ``deterministic component'' (call it $d_t$). The remainder $y_t - d_t$ can be therefore thought of as the superimposition of separate contributions, given by each structural shock hitting the system at a given time. In practice, we'd think of each individual series in the system as \[ y_{it} - d_{i,t} = M_{i,1}(L) \StS{1,t} + \cdots + M_{i,n}(L) \StS{n,t} \] using representation \eqref{eq:svma}. Note that each element of the sum on the right-hand side of the above equation is uncorrelated (by hypothesis) of all the other ones at all leads and lags. Therefore, the contribution of each shock to the visible path of the variable $y_{it}$ is distinct from the others. In a way, historical decomposition could be considered as a particular form of counterfactual analysis: each component $M_{i,j}(L) \StS{j,t}$ shows what the history of $y_{i,t}$ would have been if the $j$-th shock had been the only one affecting the system. From a technical point of view, the decomposition is computed via a ``rotated'' version of the system:\footnote{I know, I know: strictly speaking, it's not a rotation; for it to be a rotation, you ought to force $C$ to be orthogonal somehow; but let's not be pedantic, OK?} pre-multiplying equation \eqref{eq:VAR} by $C^{-1}$ gives \[ y^*_t = {\mu^*}' x_t + \sum_{i=1}^p \VarSym^*_i y^*_{t-i} + \StS{t} \] where $y^*_t \equiv C^{-1} y_t$ and $\VarSym^*_i \equiv C^{-1} \VarSym_i C$. This makes it trivial to compute the historical contributions of the structural shocks $\StS{t}$ to the rotated variables $y^*_t$, which are then transformed back into the original series $y_t$. The decomposition above can be performed in the SVAR package using the estimated quantities by the \dtk{SVAR_hd} function, which takes two arguments: a pointer to the SVAR model and an integer, indicating which variable you want the decomposition for. Upon successful completion, it will return a list of $n+1$ series, containing the deterministic component and the $n$ separate contributions by each structural shock to the observed trajectory of the chosen variable. The name of each variable so created will be given by the \verb|hd_| prefix, plus the names of the variable and of the shock (\verb|det| for the deterministic component). \begin{figure}[htbp] \centering \includegraphics[scale=0.8]{Cmodel_hd} \caption{Simple C-model example: historical decomposition plot} \label{fig:Cmodel-hd} \end{figure} A traditional way to represent the outcome of historical decomposition is, again, graphical. The most common variant depicts the single contributions as histograms against time and their sum (the stochastic component $y_t - d_t$) as a continuous line. The SVAR package provides a pair of functions for plotting such a graph on screen or saving it to a file, and the go by the name of \cmd{HDplot()} and \cmd{HDsave()}, respectively. See their description in Section \ref{sec:syntax} in the appendix and Figure \ref{fig:Cmodel-hd}, which shows the historical decomposition for the unemployment series we've been using as an example in this section. \section{C-models with long-run restrictions (Blanchard-Quah style)} \label{sec:BlQuah} \begin{table}[htbp] \begin{scode} set verbose off include SVAR.gfn open BlQuah.gdt --frompkg=SVAR set seed 1234 # make results reproducible list X = DY U list exog = const time maxlag = 8 # set up the model BQModel = SVAR_setup("C", X, exog, maxlag) BQModel.horizon = 40 # set up the long-run restriction SVAR_restrict(&BQModel, "lrC", 1, 2, 0) # cumulate the IRFs for variable 1 SVAR_cumulate(&BQModel, 1) # set up names for the shocks BQModel.snames = defarray("Supply", "Demand") # do estimation SVAR_estimate(&BQModel) # retrieve the demand shocks dShock = GetShock(&BQModel, 2) # bootstrap (set 'quiet' off with trailing zero arg) bfail = SVAR_boot(&BQModel, 1024, 0.9, 0) # page 662 IRFsave("bq_Ys.pdf", &BQModel, 1, 1) IRFsave("bq_us.pdf", &BQModel, 1, 2) IRFsave("bq_Yd.pdf", &BQModel, -2, 1) IRFsave("bq_ud.pdf", &BQModel, -2, 2) # now perform historical decomposition list HDDY = SVAR_hd(&BQModel, 1) list HDU = SVAR_hd(&BQModel, 2) # cumulate the effect of the demand shock on DY series hd_Y_Demand = cum(hd_DY_Demand) # reproduce Figure 8 gnuplot hd_Y_Demand --time-series --with-lines --output=display # reproduce Figure 10 gnuplot hd_U_Demand --time-series --with-lines --output=display \end{scode} \caption{Blanchard-Quah example} \label{tab:BlQuah} \end{table} An alternative way to impose restrictions on $C$ is to use long-run restrictions, as pioneered by \cite{BlanQuah1}. The economic rationale of imposing restrictions on the elements of $C$ is that $C$ is equal to $M_0$, the instantaneous IRF. For example, Cholesky-style restrictions mean that the $j$-th shock has no instantaneous impact on the $i$-th variable if $ic$ and $\rk{M} = c$, then $M_{\perp}$ is some matrix such that $M_{\perp}'M = 0$. Note that $M_{\perp}$ is not unique.} Equation \eqref{eq:SVEC-id} can be expressed in vector form as \[ ( J' \otimes \alpha_{\perp}' ) \VEC(C) = 0 ; \] since $\alpha_{\perp}$ has $n-r$ columns, this provides $r\cdot(n-r)$ constraints of the type $R \VEC(C) = d$, that we know how to handle. Note the convention to put those equations on top where the permanent shocks occur. Sometimes this requires a manual re-ordering of the variables, especially if some of them are restricted to be weakly exogenous. Since $0 < r < n$, this system of constraints is not sufficient to achieve identification, apart from the special case $n =2$, $r=1$, so in general the partition between transitory and permanent shocks must be supplemented by extra constraints. Clearly, these can be short-run constraints on both kind of shocks, but long-run constraints only make sense on permanent ones.\footnote{The SVAR addon also allows to apply further long-run constraints manually in a \texttt{SVEC} model, using the same \texttt{lrC} code as before. However, getting these right is sometimes tricky given the reduced rank of the long-run impact matrix. Sometimes, for example, the restrictions might imply a different $\alpha$ matrix from what the reduced-form estimates yielded. These complications are currently not (always) handled automatically and remain the user's responsibility. You should double-check what your long-run constraints actually mean and how they interact.} \subsection{Syntax} \label{sec:KPSWsyntax} Fort this type of model, the model code you have to supply to \dtk{SVAR_setup} is \cmd{"SVEC"}. This means that your model is a C-model in which, however, the structural shocks will be classified as transitory or permanent, depending on the cointegration properties you assume. This is an important point: \texttt{SVAR} is not meant for doing inference on the cointegration part of your model. For determining the cointegration rank of your system and estimating the cointegration $\beta$, you're on your own. Of course, you can use \app{gretl}'s in-built commands, such as \cmd{johansen} and \cmd{vecm}, or pre-set them to some theory-derived value: \texttt{SVAR} won't care, and will blindly accept the matrix $\beta$ you supply it; the cointegration rank is implicitly assumed as the number of columns of the $\beta$ matrix. Another piece of information you must supply separately, prior to estimation, is how you want the deterministic terms (the constant and the trend) in your model to be treated; in practice, which of the famous ``five cases'' you want to apply to your model. In fact, the constant and the trend are subject to a special treatment in this class of models, so they will be dropped from the exogenous list \texttt{X}, if present, when you call \dtk{SVAR_setup} and re-added internally if needed. Unless you have extra exogenous variables, such as centred seasonals, you might just as well leave \texttt{X} as \texttt{null}. The five cases range from the most to the least restrictive, as per Table \ref{tab:5cases}. \begin{table}[htbp] \centering \begin{tabular}{rrl} \hline Code & \cmd{vecm} option & Description\\ \hline 1 & \option{nc} & No constant, no trend \\ 2 & \option{rc} & Restricted constant, no trend \\ 3 & & Unrestricted constant, no trend \\ 4 & \option{crt} & Constant, restricted trend \\ 5 & \option{ct} & Constant, unrestricted trend \\ \hline \end{tabular} \caption{The five cases for deterministic terms in cointegrated systems} \label{tab:5cases} \end{table} This is not the place for explaining the differences between the five options; if you've come this far, you probably know already. If you don't, grab any decent econometrics textbook or the \emph{Gretl User's Guide} and look for the chapter on cointegration and VECMs. For injecting the necessary information into the model bundle once you've set it up, there is a dedicated function whose name is \dtk{SVAR_coint}. It takes three compulsory parameters: the SVAR model (in pointer form), the ``deterministic terms code'' and the cointegration matrix $\beta$. Next is the loading matrix $\alpha$; this argument may be omitted or equivalently passed as an empty matrix \texttt{\{\}}, in which case it will be estimated via OLS. If, on the contrary, it is not empty, then it should be a $n \times r$ matrix that will be accepted at face value. Pre-setting $\alpha$ may be useful, in some cases, to force some of the variables to be weakly exogenous. Note that the \verb!$jbeta! and \verb|$jalpha| standard gretl accessors make it painless to fetch them from a Johansen-style VECM if necessary. This also means that the coefficients of any restricted deterministic terms must be included as part of the given $\beta$ matrix in the cases 2 and 4 (sometimes called $\beta^*$ in the literature). Calling this function will \begin{enumerate} \item Set up a system of constraints such that the $n-r$ permanent shocks will come first in the ordering, followed by the $r$ temporary ones. The shock names will be set accordingly. \item Prepare the estimation of the VECM parameters subject to the constraints implied by the given $\beta$ (and $\alpha$, if not empty): in practice, the matrix $\Sigma$ and the parameters $\mu$ and $\Gamma_i$ in equation \eqref{eq:VECM}. Internally, later everything will be transformed into the VAR form \eqref{eq:VAR} so that the VMA representation can be computed and everything will proceed like in an ordinary C model. \end{enumerate} At that point, the rest of the model can be set up as usual. This involves setting extra restrictions, but note that long-run constraints (including those implied by the properties of $\beta$ and $\alpha$) also depend on estimated autoregressive parameters. Therefore the interplay of short- and long-run constraints can only be analyzed at estimation time, not when the restrictions are specified. Switching on the identification check may in some cases help to uncover redundant or contradictory constraints. In the next subsection, we will provide an extended and annotated example. \begin{table}[htbp] \begin{scode} 1 nulldata 116 2 setobs 4 1970:1 3 include SVAR.gfn 4 5 # grab data from AWM 6 join AWM.gdt YER PCR ITR 7 8 # transform into logs 9 series y = 100 * ln(YER) 10 series c = 100 * ln(PCR) 11 series i = 100 * ln(ITR) 12 list X = c i y 13 14 # find best lag 15 var 8 X --lagselect 16 p = 3 17 18 # check for the "balanced growth path" hypothesis 19 johansen p X 20 vecm p 2 X 21 restrict 22 b[1,1] = -1 23 b[1,2] = 0 24 b[1,3] = 1 25 26 b[2,1] = 0 27 b[2,2] = -1 28 b[2,3] = 1 29 end restrict 30 31 # ok, now go for the real thing 32 x = SVAR_setup("SVEC", X, const, p) 33 matrix b = I(2) | -ones(1,2) 34 SVAR_coint(&x, 3, b, {}, 1) 35 x.horizon = 40 36 SVAR_restrict(&x, "C", 1, 2, 0) 37 38 SVAR_estimate(&x) 39 loop j = 1..3 40 FEVDplot(&x, j) 41 endloop 42 43 SVAR_boot(&x, 1024, 0.90) 44 loop j = 1..3 45 IRFplot(&x, 1, j, 2) 46 endloop \end{scode} \caption{The \texttt{awm.inp} script} \label{tab:awmscript} \end{table} \subsection{A hands-on example} \label{sec:KPSWexample} In this example, we will go through a pseudo-replication of the simpler of the two examples presented in \cite{KPSW91}: the structure of the model will be kept the same, but we will use a different dataset. While the original article used post-WWII data for the US economy, we will use the so-called AWM dataset, which is supplied among \app{gretl}'s sample datasets. AWM stands for Area-Wide Model, and is a quarterly dataset of the Euro area, which spans the 1970-1998 period. It was originally developed by \cite{AWM} but has been used in countless other benchmark studies. The script is supplied in the examples directory as \texttt{Traditional/awm.inp}, but we reproduce it here as table \ref{tab:awmscript} for your convenience. The model comprises three variables, all in logs: real GDP ($y_t$), real private consumption ($c_t$) and real investment ($i_t$); these should, in theory, follow the same stochastic trend (the so-called ``balanced growth path''), so that there ought to be two cointegration relationships: \begin{eqnarray*} c_t &=& y_t + z^c_t \\ i_t &=& y_t + z^i_t \end{eqnarray*} The general idea of the script is: use \app{gretl}'s internal functions to estimate the VECM and test whether the ``balanced growth path'' hypothesis is in fact tenable on this particular dataset. Then, set up the structural part of the model, estimate it and do a few plots. \begin{figure}[htbp] \centering \includegraphics[height=4.75cm]{awm-irfy} \includegraphics[height=4.75cm]{awm-irfc} \includegraphics[height=4.75cm]{awm-irfi} \caption{Impulse responses to a permanent shock} \label{fig:AWM-irfs} \end{figure} More in detail, the script goes like this: \begin{description} \item[Lines 1--7] Create an empty quarterly dataset, populate it with the relevant variables from the \texttt{AWM.gdt} file. \item[lines 8--13] Transform the series to logarithms and group them into the list \texttt{X}. \item[lines 14--30] Run some preliminary checks: find the best lag length for the VAR, check that the cointegration rank is in fact 2 and that the cointegration matrix is the one hypothesised by economic theory. \item[Line 32] Set up the SVAR object. Note the usage of the \texttt{SVEC} code. \item[Lines 33--36] Set up the cointegration infrastructure (deterministic terms, $\beta$, etcetera). \item[lines 35--36] Set the horizon for IRF computation to a higher value than the default and add an extra restriction to one of the temporary shocks to achieve identification. Here we assume that the idiosyncratic shock on investment does not affect consumption instantaneously. \item[lines 38--42] Estimate the model and plot the FEVD graphs. \item[lines 43--46] Bootstrap the model and plot the IRFs with a 90\% confidence interval. \end{description} A selection of the output is shown below, while Figure \ref{fig:AWM-irfs} is the equivalent of \citeauthor{KPSW91}'s figure 2 (p. 820).\footnote{Note the usage of the fourth, optional parameter in the call to IRFplot to move the legend to the bottom of the figure.} Considering that the data span a different period and describe a different economy, the similarity between the original figure and the replicated one is quite remarkable. \begin{code} # ok, now go for the real thing ? x = SVAR_setup("SVEC", X, const, p) ? matrix b = I(2) | -ones(1,2) Generated matrix b ? SVAR_coint(&x, 3, b, {}, 1) Unestricted constant, beta = 1.00000 0.00000 0.00000 1.00000 -1.00000 -1.00000 alpha is unrestricted ? x.horizon = 40 ? SVAR_restrict(&x, "C", 1, 2, 0) ? SVAR_estimate(&x) Optimization method = Scoring algorithm Unconstrained Sigma: 0.29538 0.39670 0.22203 0.39670 1.64419 0.55188 0.22203 0.55188 0.32538 coefficient std. error z p-value --------------------------------------------------------- C[ 1; 1] 0.485389 0.0391266 12.41 2.44e-35 *** C[ 2; 1] 1.09533 0.0948831 11.54 7.92e-31 *** C[ 3; 1] 0.516670 0.0406739 12.70 5.71e-37 *** C[ 1; 2] 0.00000 0.00000 NA NA C[ 2; 2] 0.373888 0.0245469 15.23 2.18e-52 *** C[ 3; 2] -0.211184 0.0138649 -15.23 2.18e-52 *** C[ 1; 3] 0.244504 0.0160525 15.23 2.18e-52 *** C[ 2; 3] -0.551965 0.0501828 -11.00 3.86e-28 *** C[ 3; 3] -0.117619 0.0210737 -5.581 2.39e-08 *** Estimated long-run matrix longrun (3 x 3) 1.1036 0.0000 0.0000 1.1036 0.0000 0.0000 1.1036 0.0000 0.0000 Log-likelihood = -295.974 \end{code} %%%%%%%%%%%%%%%%%%% % sign restrictions \section{Set-identified SVARs}\label{sec:SR} Starting with version 1.9 the SVAR addon also makes it possible to estimate set-identified structural VAR models. What is currently still missing is a graphical interface and some other final bits of integration. With this new functionality there is surely also an extended potential for wrong and unsupported user input which may not always be caught properly. For example, calling some of the traditional functions when working with a set identified model may lead to breakage. This will be fixed and improved as time goes by. Some artificial as well as real-life example scripts are included with SVAR to demonstrate the usage of sign restrictions and set identification in general. These are: \texttt{ChoMoreno.inp}, \texttt{exotic1.inp}, \texttt{exotic2.inp}, \dtk{spaghetti_plot.inp}, \dtk{mixed_example.inp}, \dtk{supply_demand.inp}, \dtk{KilianMurphy_relaxed.inp}, and \dtk{Uhlig_example.inp} \subsection{Notation} At the risk of repeating some parts of earlier sections, here is some notation first: the reduced-form VAR is assumed to be \[ y_t = \mu_t + \sum_{i=1}^p \Phi_i y_{t-1} + \PrE{t}, \] where $\PrE{t} = y_t - E(y_t |F_{t-1})$ and $\Sigma \equiv E(\PrE{t} \PrE{t}')$; $F_{t-1}$ is the information set at $t-1$. The structural model can be written as \[ A \PrE{t} = B \StS{t} . \] The relationship between the VAR shocks and the structural ones is, therefore, \[ \PrE{t} = C \StS{t} , \] where $C = A^{-1} B$, which entails $\Sigma = CC'$. In order to write down the VMA representation, we assume that the $\Phi(L)$ polynomial is invertible, so $y_t$ can be written as $ y_t = m_t + \Theta(L) \PrE{t}$, where $\Theta(L) = \Phi(L)^{-1}$. Therefore, the structural VMA representation of the process is \begin{equation} \label{eq:structVMA} y_t = m_t + M_0 \StS{t} + M_1 \StS{t-1} + \cdots \end{equation} where $M_i = \Theta_i C$; since $\Theta_0 = I$, $M_0$ is simply equal to $C$. As for $C$, it is assumed that it can be written as \begin{equation} \label{eq:rotation} C = K Q \end{equation} where $K$ is the Cholesky decomposition of $\Sigma$ and $Q$ is an orthogonal matrix $Q'Q = I$. Set identification is typically achieved by stipulating conditions on the elements of the $M_i$ matrices. \subsection{Set identification} The apparatus we have makes it possible to handle very general set constraints on the $M_i$ matrices, that can be expressed as $g(M_i) \in A$, where $g$ is a pretty arbitrary function and $A$ is a pretty arbitrary set. In most cases, however, identification is attained by simple \emph{sign restrictions}, that is constraints of the kind \[ [M_k]_{i,j} > 0 \qquad \mathrm{or} \qquad [M_k]_{i,j} < 0 \] where we're using the notation $[A]_{i,j}$ to indicate the element on row $i$ and column $j$ of the matrix $A$ and of course $k$ can be any non-negative integer. The general case may be more involved; a real-life example is provided by the ``elasticity bounds'' constraints used in \citet{KilianMurphy2014}, where you have \[ a < \frac{[M_k]_{i,j}}{[M_k]_{l,j}} < b . \] These constraints are often imposed for a contiguous range of lags: when $h=0$, restrictions implicitly apply to $C$, since $M_0 = C$; however, one could conceivably impose restrictions on $\underline{H} \le h \le \overline{H}$, where $\underline{H}$ should in most cases (but not always) be 0.\footnote{Something that is impossible, at the moment, is imposing cross-matrix (cross-horizon) constraints, such as, for example, $[M_0]_{i,j} > [M_1]_{i,j}$. This approach might be implemented when we become aware that it is needed or being used already.} Each restriction corresponds to an a-priori idea of the impact of the $j$-th structural shock on the $i$-th variable. Of course, the ordering of the structural shocks is arbitrary, so the user is required to make a choice here (see below). \subsubsection{Sign restrictions (practicalities)} After having initially set up the model bundle appropriately (see below), sign restrictions in the narrow or plain sense are specified through the \dtk{SVAR_SRplain} function. The full documentation is in the appendix, but the gist is: this function gives you a way to indicate the sign of the impact that of a certain shock is assumed to have on a certain variable, and optionally over which set of lags. Internally, each call to \dtk{SVAR_SRplain} adds a row vector to the \texttt{SRest} matrix contained in the bundle referenced as the first argument; the restriction matrix is simply created by stacking these rows vertically. For example, a minimal call of the function would read \begin{code} SVAR_SRplain(&mod, "price", "monetary", "+") \end{code} and it would mean that the shock named \texttt{monetary} has a positive instantaneous impact on \texttt{price}; in other words, $[M_0]_{ij} > 0$, where $i$ is the ordinal number of the variable \texttt{price} in the input list and $j$ is the ordinal number of the string \texttt{monetary} in the \texttt{snames} array inside the model bundle. One could constrain non-instantaneous IRFs by using the full syntax \begin{code} SVAR_SRplain(&mod, "y", "shock", "+", len, start) \end{code} where \texttt{len} and \texttt{start} are nonegative integers. They both default to 0, so for example: \begin{code} SVAR_SRplain(&mod, "bar", "foo", "-", 3) \end{code} means that the shock named \texttt{foo} has a negative impact on the observable variable \texttt{bar} over the horizon from 0 to 3 (hence, four elements of the IRF are constrained). In practice, the number of constraints is \texttt{len}+1. Finally, by indicating a starting lag for the constraint, the sign restrictions would be applied to the responses from \texttt{start} to \texttt{start}+\texttt{len}. Therefore, the code \begin{code} SVAR_SRplain(&mod, "quantity", "supply", "+", 4, 2) \end{code} means that the shock named \texttt{supply} has a positive impact on the observable variable \texttt{quantity} over the horizon from 2 to 6; again, note that the number of restricted IRFs is \texttt{len} $+1 = 5 = (6-2+1)$. \subsubsection{Interval restrictions} A plain sign restriction specifies an interval with upper or lower bound zero into which the impulse response is supposed to fall. A generalization of this idea is to specify an arbitrary interval with a lower or upper bound or both, none of which has to be zero. This idea was already mentioned above in the guise of ``elasticity bounds''. The \dtk{SVAR_SRfull} function allows to use such restrictions, see the appendix for its documentation. These restrictions can be ``static" in the sense that they only apply to a certain horizon, for example on impact; or just like sign restrictions they can be ``dynamic" and associated with a range of horizons. \subsubsection{General (``exotic'') set restrictions} General set restrictions are specified via the function \dtk{SVAR_SRexotic}, which takes 2 mandatory arguments and 2 optional ones (again, see the appendix). The string you pass as argument \#2 must contain a valid hansl expression, in terms of a matrix whose name nust be \texttt{M}, yielding a scalar. This code snippet is assumed to perform some kind of check on the elements of the matrix, the convention being that a non-zero result implies that the restriction holds. For example, the string \begin{code} string boundscheck = "abs(M[1,1]) < 0.1" \end{code} will check whether $-0.1 < [M_i]_{1,1} < 0.1$ for a certain horizon $i$ which must not enter the expression, however. In order to impose this restriction on horizons 0 through 2, i.e. on $M_0, M_1$ and $M_2$, you invoke the function like this: \begin{code} string boundscheck = "abs(M[1,1]) < 0.1" SVAR_SRexotic(&mod, boundscheck, 2) \end{code} If you want more restrictions, you just invoke the function several times with suitable strings as arguments. % (I think the following not suitable/needed for the public: [Sven]) % Internally, the exotic restrictions are stored in a bundle named % \texttt{exoticSR} inside the main model bundle, which contains a % string array (named \texttt{checks}) with the $p$ restriction strings % and a $p \times 2$ matrix called \texttt{spans} with the initial and % final period the restriction applies to (NB: \texttt{spans} is % 1-based, rather than 0-based). \subsection{Mixed restrictions} \label{sec:mixed} In some cases, set restrictions may be supplemented by exact restrictions on the $C$ matrix. The syntax for specifying constraints of this kind is strightforward, and is absolutely similar to the one used for C-models (see section \ref{sec:baseest}). So, for example, to set $C_{4,2} = 0$ you would insert in your script a line like \begin{code} SVAR_restrict(&Mod, "C", 4, 2, 0) \end{code} and more general constraints can be specified by suitably constructing the \texttt{Rd1} member of the model bundle. Since $M_0 = C$ (see equation \ref{eq:structVMA}) these are typically used to set to 0 some instantaneous response; more sophisticated alternatives, though possible, are very seldom used in the literature. Given the peculiar nature of set-based inference there are some limitations on the type of point constraints that can be specified in this context. At present, two types of restrictions are not allowed: \begin{description} \item[cross-shocks constraints]: for example, something like $C_{2,3} = C_{4,1}$ is not allowed, altough it is perfectly possible to set both elements to 0. Note that this does \emph{not} rule out constraints pertaining to the same shock on several variables. For instance, something like $C_{1,3} = C_{2,3}$: this would mean that the instantaneous impact of shock number 3 is the same for variables 1 and 2. This possibility, however, requires setting up an appropriate row of the bundle element \texttt{Rd1} by hand: see Section \ref{sec:OtherConstraints}. \item[non-zero constraints]: that is, something like $C_{i,j} = 1$; this limitation may be relaxed in the future, but we're not aware of non-zero restriction having ever been used in the literature (if anybody has evidence to the contrary, please let us know). \end{description} \subsection{The workflow for set identification} \begin{enumerate} \item First of all the model should be set up as usual through \dtk{SVAR_setup}, but now with model code ``SR''. This automatically arranges for the reduced-form parameters to be estimated (or if you're a Bayesian: to calculate the likelihood-based ingredient to update your prior). \item However, this setup can only initialize the shock names under the key \texttt{snames} generically by copying the variable names. Thus it will normally be useful to modify some of these names with meaningful shock labels. For example: \begin{code} Mod.snames[1] = "monetary" \end{code} \item Next the restrictions have to be formulated and imposed on the model, namely through any number of calls to the functions \dtk{SVAR_SRplain}, \dtk{SVAR_SRfull}, or \dtk{SVAR_SRexotic}. If necessary, add point restrictions using \dtk{SVAR_restrict}. \item The core of set-identified SVAR estimation happens now: a large number of random orthogonal matrices $Q$ are generated, and the IRFs are computed according to equation \eqref{eq:rotation}. If $Q$ is such that all the constraints are satisfied, those IRFs are kept as ``good''. The process goes on until the number of ``good'' draws reaches a prescribed number (typically, a few hundred). The randomized drawing is performed by the function \dtk{SVAR_SRdraw}. This is the heavy number-crunching part.\footnote{With the computing power these days even that will typically not give you enough time to get coffee, unless you need a monster number of draws.} At this stage one also chooses the desired coverage level of the error bands (confidence intervals, credible sets, whatever) presumably to be plotted later. A more detailed description of what this function does is provided in section \ref{sec:SRdraw_details}, although for the precise details there's no substitute to studying the code. \item Plotting; after having collected all the draws which fulfilled the imposed identification restrictions, SVAR offers two variants for the graphical representation of the results, functions again documented in the appendix: \begin{itemize} \item Standard -- these plots resemble the traditional IRF graphs and are produced by the function \dtk{SVAR_SRirf}. The centers of the IRF distributions as well as their lower and upper error bounds are calculated separately for each horizon. It is a well-known criticism that the resulting plotted lines can be a combination of very different draws, possibly distorting the impression that is conveyed by the plot. Other researchers have countered this criticism by remarking that one just needs to know what is being done. So now you know. \item Spaghetti -- this kind of plot is provided by \dtk{SVAR_spagplot} which literally gives the user everything identified by the set restrictions; each accepted draw's IRF is drawn, and one can hopefully judge whether they have the same tendency or are constantly crossing each other. \end{itemize} \end{enumerate} \subsection{Historical and forecast error variance decompositions} The set identification methods revolve around the IRF properties of the admissible models, and several approaches to analyze and display the impulse responses have been presented. What remains to be explained is the usage of other usual types of analyses such as estimates of historical shock developments (historical decomposition, HD) and the relative contributions of the identified shocks to the dynamics of the endogenous variables (forecast error variance decomposition, FEVD).\footnote{Most of these require a fully identified model, i.e. where the number of identified shocks corresponds to the number of endogenous variables. This might be partly generalized in the future.} A well-known complication in the set identification context is that by its very nature there exists no point estimate of the IRFs, but the standard HD and FEVD require unique coefficients. On a technical level, any of the accepted model draws can be chosen and thus there are many possible HD and FEVD variants. Therefore the relevant functions \dtk{SVAR_hd}, \texttt{FEVD}, and also \texttt{GetShock} (which stores the estimated historical shock realization as a gretl series into the workfile) take as an additional argument an integer as an index to pick a certain accepted model draw. For example, the \texttt{ChoMoreno.inp} example script shipped with the SVAR addon produces 256 accepted draws and its model bundle has the name ``mod''. After it is run we could in principle pick arbitrarily any draw between 1 and 256. % 112th accepted draw to produce the HD % for inflation -- which is the 2nd variable in the model -- as follows: % \begin{code} % list inflHD = SVAR_hd(&mod, 2, 112) % \end{code} % In the same fashion we could extract the history of the demand shock (the 1st one) % by writing % \begin{code} % series demandshock = GetShock(&mod, 1, 112) % \end{code} % ... or retrieve the FEVD numbers with this call: % \begin{code} % matrix allfevd = FEVD(&mod, 112) % \end{code} However, the aim is typically to use a draw which is somehow representative of the entire model distribution. Thus the possibility of specifying a draw index manually is only offered for more flexibility as a kind of override option. While it is beyond the scope of this user guide to provide a discussion of the possible conceptual approaches to find a suitable unique model among the many accepted draws, the \texttt{SVAR} addon provides the \dtk{SVAR_SRgetbest} convenience function to help with this task. For example, continuing with \texttt{ChoMoreno.inp}, say you are most interested in the impulse response of inflation (\texttt{INFL}, 2nd variable) to the shock \texttt{Demand} (1st shock) not immediately, but after one quarter. That is, you want to find that accepted model which has a response of inflation to a demand impulse at lag 1 which is as close as possible to the median response across all accepted draws. The relevant call to find this model's index number would be: \begin{code} SVAR_SRgetbest(&mod, "INFL", "Demand", 1, , 1) \end{code} The function is documented in the appendix, but note that the first scalar argument with value 1 chooses the starting IRF horizon where 0 would be equivalent to the contemporaneous impact, so here it is after one period. The following argument would determine how many of the following periods should be considered; here we do not want to consider anything beyond the first lag, so we can leave it at the default value zero and hence do not need to specify that argument. The trailing argument value 1 chooses the median as the target (0 would be the mean).\footnote{The concrete targeted number turns out to be $0.171304$. This could also be found inside the bundle with $nv=2$ and $ns=1$ (and of course $n=3$) as \texttt{mod.SRirfmeds[2, (ns-1)*n + nv]} or equivalently \texttt{mod.SRirfmeds[2, 2]}.} We find that the representative model in this particular sense is the one with index 58; by construction the associated impulse response value is very close to the median, namely $0.171297$. The \dtk{SVAR_SRgetbest} function stores this index number 58 in the model bundle under the key \texttt{bestdraw}. The functions that require a unique model parametrization such as \dtk{SVAR_hd}, \texttt{FEVD}, \texttt{GetShock}, and \texttt{IRFplot} will automatically use the associated draw (unless the user overrides it with her own choice as described above). This carries over to the higher-level interface functions such that you could write calls like the following as always: \begin{code} FEVDplot(&mod, 1) IRFplot(&mod, 1, 2) HDplot(&mod) \end{code} Since a single accepted draw by itself does not contain any information about the parameter uncertainty, this kind of IRF plot only shows a single line without any intervals. For specially designed plots for the set-identified situation please refer to the functions \dtk{SVAR_SRirf} and \dtk{SVAR_spagplot} as explained above. % end sign restrictions part %%%%%%%%%%%%%%%%%%% \bibliography{SVAR} \appendix \pagebreak \section{The GUI interface} \label{sec:GUI} This section introduces the GUI interface with which most of the available calculations can be accomplished as well and which can be accessed via the \emph{Model $>$ Time Series $>$ Multivariate $>$ Structural VAR} menu entry of the the graphical \app{gretl} client. While we recommend using the script interface to access the full capabilities of the SVAR package, the GUI interface may be less intimidating for less experienced users. The GUI component covers everything but \begin{enumerate} \item the SVEC case (see section \ref{sec:SVECs}) where the cointegration properties of the system are exploited for special long-run restrictions. \item Set-restricted models, described in section \ref{sec:SR}. \end{enumerate} For the GUI in the SVEC case there is a preliminary additional function package \emph{SVEC\_GUI} available on the gretl package server which uses this SVAR addon as its backend. \begin{figure}[htbp] \centering \includegraphics[scale=0.5]{GUI_SVAR.png} \caption{Plain Cholesky model through the GUI interface (earlier SVAR version)} \label{fig:GUI-plain} \end{figure} Many important contents of the window displayed in Figure \ref{fig:GUI-plain} should be rather self-explanatory; the model type chooser, the list of endogenous VAR variables, another (optional) list of exogenous variables, the lag order, and further down the number of bootstrap replications along with the nominal bootstrap confidence level (leave the number of replications at the default value zero to skip the bootstrap), and finally the choice of the precise optimization algorithm from the drop-down menu at the bottom, where as before the scoring algorithm is the default. The other function parameters will be explained now. First there are three checkboxes that specify the deterministic terms to be included in the model.\footnote{The seasonal dummies are automatically centered, which should only matter in the rather exotic case without a constant term, however.} Note that it is still possible to manually specify the deterministic terms as in the script interface, namely as part of the exogenous regressor list. Next, the \emph{horizon} parameter sets the desired maximum impulse response horizon as explained above for the script interface, and can be left at zero to invoke the default settings. \subsection{Identifying constraints} The two central inputs for the C and AB model types are the identifying constraints. In the SVAR GUI they must be given as pattern matrices that can only have two types of entries: Each entry with a "missing" value denotes an unrestricted element, and every entry with a valid numerical value will be restricted to just that value. You can either pre-define the pattern matrices before you call the SVAR package and then choose the corresponding name of the matrix in the drop-down menu, or you have to click on the ``+'' button next to the function argument field and specify the matrix on the spot in the following standard \app{gretl} matrix creation dialog.\footnote{Hint: with recent gretl versions it is possible to initialize the matrix to hold only missing values, by entering \texttt{na} or \texttt{nan} as the initial fill value. Then you just have to edit the actually restricted elements afterwards.} If you do not wish to restrict any of the involved matrices, just leave the function argument at the default "null" value. For a C model, as indicated by the function argument labels the first restriction pattern matrix refers to the short-run restrictions, while the second pattern matrix must be used for the long-run restrictions. If you choose an AB model instead, these matrix inputs serve to hold the restrictions on B and A, respectively. Note the reversed ordering of B and A here, which reflects the fact that if A is the identity matrix then B is the same thing as the short-run restriction C matrix, so these latter two matrices belong together. \subsection{Bootstrap parameters and cumulation} The next checkbox after the bootstrap specification concerns the activation of the bias correction that was already explained in relation to the script interface. Following is another checkbox that activates a check for identification, see section \ref{sec:SVARid}. Towards the end of the SVAR GUI window you have another matrix argument which serves to tell the package which of the impulse responses should be provided in cumulated form. You need to provide a (row or column) vector that holds the corresponding integer indices of the variables to be cumulated referring to the list of endogenous variables. Say your list of endogenous variables is ``foo baz bar'' and the responses of \emph{foo} and \emph{bar} should be cumulated, then you would need to pass a vector \texttt{\{1, 3\}} (or \texttt{\{1; 3\}}).\footnote{This way of specifying the responses to be cumulated in the GUI of SVAR may change in the future, perhaps by using another list of variables instead.} Note that you can type an expression of this sort into the matrix entry box directly, as shown in Figure~\ref{fig:matrix-entry}. \begin{figure}[htbp] \centering \includegraphics[scale=0.5]{dialog_mat.png} \caption{Entering a matrix specification directly} \label{fig:matrix-entry} \end{figure} \subsection{The output window} After specifying all necessary function arguments and clicking OK, you are presented---possibly after having to wait for the CPU intensive bootstrap to finish---with a first output window holding the basic estimation results, for example of the C matrix or of the A and B matrices. If the provided restrictions are over-identifying the corresponding LR test result is also printed out. In the SVAR output window (see Figure~\ref{fig:GUI-output} below) three toolbar buttons deserve special mention: The ``Save'' button allows you to save the printed output, but more importantly you can also save the entire bundle that was returned by the SVAR package as an icon (element) of the current \app{gretl} session. When you open (view) the bundle again later, some information about the model specification will also be shown. (And the session can in turn later be saved into a session file.) Next, for saving only selected members of the SVAR bundle there is the ``Save bundle content'' button. Finally you have the ``Graph'' button which provides the access to the central SVAR analyses, namely the impulse responses, the error variance as well as the historical decompositions. \subsection{An example} For example, suppose we wanted to estimate a C model like the one used as example so far, with the only difference that we want the $C$ matrix to be \emph{upper} triangular, rather than lower triangular. Via a script, you would use the function \dtk{SVAR_restrict()}, as in \begin{code} # Force C_{2,1} to 0 SVAR_restrict(&Mod, "C", 2, 1, 0) \end{code} but you can do the same via the GUI interface by using a pattern matrix, which must be a $n \times n$ matrix (that is, the same size as $C$). \begin{figure}[htbp] \centering \includegraphics[scale=0.5]{TMPL.png} \caption{Template matrix} \label{fig:tmpl} \end{figure} Suppose we call the pattern matrix \texttt{TMPL} and that we select the option ``Build Numerically'' (of course, with 2 rows and 2 columns in this example). When you're done, you return to the main SVAR window (be sure to select C-model as the model type). After clicking ``OK'', the results window will appear, as in Figure~\ref{fig:GUI-output}. Note that the estimated $C$ matrix is now upper triangular.\footnote{The same pattern matrix can also be used in scripting for the \dtk{SVAR_restrict()} function, since gretl 2024c.} From the output window, you can save the model bundle to the Icon view by clicking on the leftmost icon\footnote{The visual appearance of the icons on your computer may be different from the one shown in Figure \ref{fig:tmpl}, as they depend on your software setup. The number and ordering of the icons, however, should be the same on all systems.} and re-use it as needed for further processing. \begin{figure}[htbp] \centering \includegraphics[scale=0.5]{Output.png} \caption{Output window} \label{fig:GUI-output} \end{figure} %\appendix \clearpage \section{Some details of the numerical algorithm in \texttt{SVAR\_SRdraw}} \label{sec:SRdraw_details} We explore the space of possible rotations via $H$ random draws from the space of rotation matrices. Once the VAR parameters ($\hat{\Phi}_i$ and $\hat{\Sigma}$) are computed, this can be done by either \begin{enumerate} \item applying the random rotation (\ref{eq:rotation}) to the Cholesky factor of $\hat{\Sigma}$, and computing the $M_i$ matrices from the $\hat{\Phi}_i$ matrices, or \item sampling from the posterior distribution\footnote{The standard Normal-inverse Wishart distribution is used.} of the parameter and get new matrices $\tilde{\Sigma}$ and $\tilde{\Phi}_i$, and then compute the $M_i$ matrices from those. \end{enumerate} Let's call option 1 the ``frequentist'' option and option 2 the ``Bayesian'' option. However, let us be clear that option 1 uses the fixed point estimates of the reduced-form coefficients and therefore does not take parameter uncertainty into account. This current state of affairs could be generalized even within the frequentist paradigm, e.g. by adding another bootstrap layer. Furthermore, option 2 effectively applies some perturbation to the reduced-form coefficients centered around the likelihood point estimates, which essentially corresponds to a flat or uninformative Bayesian prior. Some might argue that this kind of prior is relatively close in spirit to a frequentist approach. In any case, this choice corresponds to a Boolean flag which is the third argument to the \dtk{SVAR_SRdraw} function: the default, 0, is to skip the sampling from the posterior and just use the frequentist point estimates. What happens inside this function? First, the relevant items from the model bundle are copied: this of course includes the VAR parameters and $\hat{\Sigma}$, but we'll also need $(X'X)^{-1}$ for the Bayesian option. Then, for each iteration: \begin{enumerate} \item For the Bayesian option, first we draw from the posterior of the VAR parameters (this is where we need $(X'X)^{-1}$); in the frequentist case, we just use $\hat{\Phi}_i$ and $\hat{\Sigma}$. \item We then create a bundle containing the draw above, a generated rotation matrix $Q$ and the number of deterministic terms in the VAR; this bundle is used by the \verb|gen_irfs| internal function that computes the IRFs for the simulated parameters. Note that: \begin{itemize} \item We generate the rotation matrix $Q$, but we \emph{don't} perform any kind of sign checks on its elements. If no point restriction are present, we just use the QR decomposition algorithm; otherwise, we generate the columns of $Q$ sequentially in such a way that the matrix $C$ in equation \eqref{eq:rotation} satisfies them by construction. Our algorithm is comparable to the one described in \cite{AriasEtAl2018}. \item we generate one $Q$ per iterations, so the number that \citet{KilianLuetkepohl2017book} call $N$ on page\footnote{This is the page of the official CUP version. In the ``unofficial'' pdf file that has been circulating for a while it's on page 432.} 441 (Step 2) is fixed at 1 (this wouldn't be difficult to change if needed); \item we compute all the IRFs up to the desired horizon even if we do not need all of them for checking the sign restrictions. (Perhaps we could optimise this, but the computational gain would likely be marginal.) \end{itemize} \item Now we check if the generated $M_i$ matrices satisfy the restrictions; this entails three steps: \begin{enumerate} \item For each set of sign restrictions, we generate a row vector with $n$ elements telling us if that particular restriction is met by each of the rotated shocks. The convention is that 1 means ``yes'', 0 means ``no'' and -1 means ``yes, but the sign of the shock must be flipped''. \item All these row vectors are coalesced into a matrix and passed to the \verb|check_id| function, that checks if there is a sensible way to map the rotated shocks to the desired structural shocks. Note that this function returns a matrix in which there could be more than one candidate for each shock. The internal function \texttt{normalize} takes care of establishing a one-to-one correspondence; if the sign restrictions are met, then we reshuffle the IRFs taking care of the structural shocks desired ordering and possible sign flips. \item At this point --if the draw is still considered good to go-- the $M_i$ matrices should contain the IRFs in the appropriate positions: $[M_k]_{i,j}$ contains the impact at $k$ steps of the $j$-th shock to the $i$-th observable, where the ordering of the observables is the one implicit in the input list and the order of the shocks is the one given by the \texttt{snames} bundle element. Therefore, we can proceed with checking the exotic restrictions (if any). \item Checking the \emph{exotic} restrictions is done in a conceptually simple way: Provided that the current draw has not failed any of the imposed restrictions up to this point, the derived impulse responses are internally relabeled as ``M" and each of the supplied exotic restriction expression is applied verbatim to the IRF matrix $M$, separately for each of the specified horizons. \item{} [tba: explain check of super-exotic restrictions] \end{enumerate} \item If all the restrictions are met, we accept the draw and store the results away as an element of the bundle array that we eventually return. Otherwise the draw is discarded. \end{enumerate} \clearpage \section{Alphabetical list of (public) functions} \label{sec:syntax} The name of the model bundle which is passed around in pointer form between most of these functions is determined by the user when the bundle is assigned from a call to \dtk{SVAR_setup}. To avoid confusion, it is assumed in the following that that bundle is named \texttt{"Smod"} (although the internal name of the argument inside the local function scope is of course arbitrary and need not be harmonized). (The function signatures below are given as-is with the asterisk ``*'' denoting the pointer argument, but remember that in \emph{gretl}'s language \emph{hansl} in a function call the pointer has to be specified with an ampersand character, as in ``\verb|&Smod|''.) \begin{funcdoc}{FEVD (bundle *Smod, int drawix[0])} \noindent Returns an $h \times n^2$ matrix with the Forecast Error Variance Decomposition from the structural IRFs, as contained in the model \texttt{Smod}. The FEVD for variable $k$ is the block of columns from $(k-1) n + 1$ to $k n$ (where $n$ is the number of variables in the VAR). The \texttt{drawix} argument can typically be omitted, see \texttt{GetShock}. \end{funcdoc} \begin{funcdoc}{FEVDplot (bundle *Smod, int vnum[0], int keypos[0:2:1], int drawix[0])} \noindent Plots on screen the Forecast Error Variance Decomposition for a variable. \noindent Arguments: \begin{enumerate} \item A bundle holding the model. \item The progressive number of the variable (0 means all). \item The position of the legend, if any (optional; default = right). \end{enumerate} The \texttt{drawix} argument can typically be omitted, see \texttt{GetShock}. \end{funcdoc} \begin{funcdoc}{FEVDsave (string outfilename, bundle *Smod, int vnum[0], int keypos[0:2:1], \\ int drawix[0])} \noindent Saves the Forecast Error Variance Decomposition for a variable to a graphic file, whose format is identified by its extension. \noindent Arguments: \begin{enumerate} \item The graphic file name. \item A bundle holding the model. \item The progressive number of the variable (0 means all). \item The position of the legend, if any (optional; default = right). \end{enumerate} The \texttt{drawix} argument can typically be omitted, see \texttt{GetShock}. \end{funcdoc} \begin{funcdoc}{GetShock (bundle *Smod, int i[1], int drawix[0])} \noindent Equivalent to the recommended \dtk{SVAR_getshock}, but with an alternative interface: Instead of specifying the name of the shock of interest its position in the names of shocks array (\texttt{Smod.snames}) must be given in \texttt{i}. \end{funcdoc} \begin{funcdoc}{HDplot (bundle *Smod, int vnum[0], int drawix[0])} \noindent Plots on screen the Historical Decomposition for a variable. \noindent Arguments: \begin{enumerate} \item A bundle holding the model. \item The progressive number of the variable (0 means all). \end{enumerate} The \texttt{drawix} argument can typically be omitted, see \texttt{GetShock}. \end{funcdoc} \begin{funcdoc}{HDsave (string outfilename, bundle *Smod, int vnum[0], int drawix[0])} \noindent Saves the Historical Decomposition for a variable to a graphic file, whose format is identified by its extension. \noindent Arguments: \begin{enumerate} \item The graphic file name. \item A bundle holding the model (pointer form). \item The progressive number of the variable (0 means all). \end{enumerate} The \texttt{drawix} argument can typically be omitted, see \texttt{GetShock}. \end{funcdoc} \begin{funcdoc}{IRFplot (bundle *Smod, int snum, int vnum, int keypos[0:2:1], int drawix[0])} \noindent Plots an impulse response function on screen. \noindent Arguments: \begin{enumerate} \item A bundle holding the model. \item The progressive number of the shock (may be negative, in which case the IRF is flipped). \item The progressive number of the variable. \item The position of the legend, if any (optional; default = right). \end{enumerate} The \texttt{drawix} argument can typically be omitted, see \texttt{GetShock}. \end{funcdoc} % \begin{funcdoc}{IRF_plotdata (bundles bs, scalar coveralpha[0.9])} % \noindent [Function name and usage subject to change.] % Relating to a set identified (sign restricted) model, this function uses % all accepted draws to construct some summary measures needed for the % (standard) IRF plots, like horizon-by-horizon means and quantiles. % Although it is by nature more like a private function, it is formally public to % enable certain kinds of unsupported hacks (see elsewhere). % \end{funcdoc} \begin{funcdoc}{IRFsave (string outfilename, bundle *Smod, int snum, int vnum, int keypos[0:2:1], int drawix[0])} \noindent Saves an impulse response function to a graphic file, whose format is identified by its extension. \noindent Arguments: \begin{enumerate} \item The graphic file name. \item A bundle holding the model (pointer form). \item The progressive number of the shock (may be negative, in which case the IRF is flipped). \item The progressive number of the variable. \item The location of the legend / key; 0=off, 1=outside/right (default), 2=below \end{enumerate} The \texttt{drawix} argument can typically be omitted, see \texttt{GetShock}. \end{funcdoc} \begin{funcdoc}{\detokenize{SVAR_boot} (bundle *Smod, int rep[0::2000], scalar alpha[0:1:0.9], bool quiet[1],\\ string btypestr[null], int biascorr[-1:2:-1])} \noindent Perform a bootstrap analysis of a model. Returns the number of bootstrap replications in which the model failed to converge. \noindent Arguments: \begin{enumerate} \item A bundle holding the model (pointer form). \item (Optional) the number of bootstrap replications (default: 2000). \item (Optional) the coverage probability used for the confidence bands (e.g.\ for 0.90 the 0.05 and 0.95 quantiles will be used; default: 0.9). \item (Optional) omit the table with bootstrap means and standard errors (default: yes). \item (Optional) the choice of bootstrap type: can be any one of ``resampling'', one of the wild variants---namely ``wildN'' (with ``wild'' as an alias), ``wildR'' or ``wildM''---or ``MBB'' for moving blocks. The default is to leave the choice in the model as-is. \item (Optional) bias correction choice: 0 for none, 1 for partial, 2 for full; the default value of $-1$ preserves whatever setting is the model. \end{enumerate} Note that the bias correction option currently only applies to non-SVEC models. \end{funcdoc} \begin{funcdoc}{\detokenize{SVAR_coint} (bundle *Smod, int dcase[1:5:3], matrix jbeta, matrix jalpha[null],\\ bool verbose[0]), list rexo[null])} \noindent Necessary for a SVEC model, adds the needed information for subsequent estimation. \noindent Arguments: \begin{enumerate} \item A bundle holding the model. \item A code for the constant/trend combination (1 to 5, as per Johansen; default 3). \item The cointegration matrix (required\footnote{In the accompanying but technically separate package \dtk{SVEC_GUI} the corresponding input is optional and would be automatically estimated.}). \item The loadings matrix (optional, will be estimated via OLS if omitted or empty). \item An optional verbosity switch (default 0). \item (Currently unused: list of further restricted exogenous variables) \end{enumerate} \end{funcdoc} \begin{funcdoc}{\detokenize{SVAR_cumulate} (bundle *Smod, int nv)} \noindent Stores into the model the fact that the cumulated IRFs for the \texttt{nv}-th variable are desired. This is typically used jointly with long-run restrictions. \end{funcdoc} \begin{funcdoc}{\detokenize{SVAR_estimate} (bundle *Smod, int verbosity[1])} \noindent Estimates the model by maximum likelihood. Its second argument is a scalar, which controls the verbosity of output. If omitted, standard output is printed. If set to 2 or higher, the output of the identification check is printed, too. If you're sure about it, the identification check before the estimation of the structural form can be suppressed in \dtk{SVAR_setup} (or by manually setting \texttt{Smod.checkident} to 0). \end{funcdoc} \begin{funcdoc}{\detokenize{SVAR_getshock} (bundle *Smod, string sname[null], int drawix[0])} \noindent Returns a series for the current workfile, namely the estimate of the structural shock given in \texttt{sname} via equation \eqref{eq:PrE-StS-AB}, in which VAR residuals are used instead of the one-step-ahead prediction errors $\PrE{t}$. If omitted, the default is to retrieve the first shock. The \texttt{drawix} argument is only meaningful in the set identification (sign restriction) case and overrides from which of the accepted model draws the coefficients should be taken. Normally this draw index should instead be determined with the help of the \dtk{SVAR_SRgetbest} function and can be omitted here. This index can range from 1 to the number of accepted draws. In order to work the SR type model must have been set up such that all accepted draws are stored in the model bundle. (See \dtk{SVAR_setup}, default is yes.) \end{funcdoc} \begin{funcdoc}{\detokenize{SVAR_HD} (bundle *Smod, string vname[null], int drawix[0])} \noindent Returns a list of series with the ``historical decomposition'' of the variable given in \texttt{vname}, decomposing it into a deterministic component and $n$ stochastic components. The names of the resulting series are as follows: if the name of the decomposed variable is \texttt{foo}, then the historical component attributable to the first structural shock is called \dtk{hd_foo_1}, the one attributable to the second structural shock is called \dtk{hd_foo_2}, and so on. Finally, the one for the first deterministic component is called \dtk{hd_foo_det}. If the \texttt{vname} argument is omitted, the default is to target the first variable. The \texttt{drawix} argument can typically be omitted, see \dtk{SVAR_getshock}. \end{funcdoc} \begin{funcdoc}{\detokenize{SVAR_hd} (bundle *Smod, int nv, int drawix[0])} \noindent Equivalent to the recommended \dtk{SVAR_HD}, but with an alternative interface: Instead of specifying the name of the target variable its position in the list of endogenous variables must be given in \texttt{nv}. \end{funcdoc} \begin{funcdoc}{\detokenize{SVAR_ident} (bundle *Smod, int verbose[0])} \noindent Returns a 0/1 scalar checking if a model is identified by applying (among other things) the algorithm described in \cite{AG}. Its second argument controls the verbosity of output. If set to a non-zero value, a representation of the restrictions and a few messages are printed as checks are performed. In case redundant restrictions are found, these are dropped in the model bundle to facilitate further estimation. \end{funcdoc} \begin{funcdoc}{\detokenize{SVAR_namedrestrict} (bundle *Smod, string code, string yname, string sname, scalar d[0])} \noindent An alternative interface for point restrictions, requiring the names of the respective shock and variable pair instead of the index numbers used in \dtk{SVAR_restrict}. An example based on the main sample script is given in the included script file \dtk{simple_C_named.inp}. For the first two arguments \texttt{Smod} and \texttt{code}, see the explanation for \dtk{SVAR_restrict}. However, the type codes \texttt{"Adiag"} and \texttt{"Bdiag"} make no sense here and are not allowed. The next two string arguments \texttt{yname} and \texttt{sname} refer to the variable and shock names in the model; while the shock names have to be user-defined before calling this function, the variable names are automatically taken from the model setup. Using unrecognized names will cause an error. Notice that for the A-matrix in an AB model no shock is directly involved, and thus it may be more natural to use the indexation form in \dtk{SVAR_restrict}. Finally, the scalar restriction value \texttt{d} works again as in \dtk{SVAR_restrict}, with the same default value of zero. \end{funcdoc} \begin{funcdoc}{\detokenize{SVAR_restrict} (bundle *Smod, string code, numeric r, int c[0], scalar d[0])} \noindent Sets up point constraints for an existing model. The function takes at most five arguments: \begin{enumerate} \item A pointer to the model for which we want to set up the restriction(s). \item A code for which type of restriction we want: \begin{description} \item[\texttt{"C"}] Applicable to C-type models (including SVEC). Used for short-run restrictions. \item[\texttt{"lrC"}] Applicable to C-type models (including SVEC in principle). Used for long-run restrictions. \item[\texttt{"A"}] Applicable to AB models. Used for constraints on the $A$ matrix. \item[\texttt{"B"}] Applicable to AB models. Used for constraints on the $B$ matrix. \item[\texttt{"Adiag"}] Applicable to AB models. Used for constraints on the whole diagonal of the $A$ matrix (see below). \item[\texttt{"Bdiag"}] Applicable to AB models. Used for constraints on the whole diagonal of the $B$ matrix (see below). \end{description} \item A numeric input, namely a matrix or an integer, whose interpretation depends on the restriction type: \begin{description} \item[Case 1a] applies to codes \texttt{"C"}, \texttt{"lrC"}, \texttt{"A"} and \texttt{"B"}, and \texttt{r} is a scalar integer: Then the argument indicates the row of the restricted element. This input can be combined with the remaining two optional arguments. \item[Case 1b] applies to the same model codes as before, but \texttt{r} is an n-by-n matrix: Then the input is taken to be a full restriction pattern matrix, i.e. any valid number in that matrix is taken directly as a restricted value, while unrestricted elements must be given as NAs. Typically, a previously created named matrix argument will be used, but an anonymous matrix literal for on-the-fly use is also valid, as per standard hansl syntax. In this matrix usage case, the remaining arguments \texttt{c} and \texttt{d} are redundant and unused. \item[Case 2] applies to codes \texttt{"Adiag"} and \texttt{"Bdiag"}. The argument specifies what kind of restriction is to be placed on the diagonal: any valid scalar indicates that the diagonal of $A$ (or $B$) is set to that value. Almost invariably, this is used with the value 1. IMPORTANT: if this argument is \texttt{NA}, all \emph{non-diagonal} elements are constrained to 0, while diagonal elements are left unrestricted. \end{description} \item An integer: the column of the restricted element, for the codes \texttt{"C"}, \texttt{"lrC"}, \texttt{"A"} and \texttt{"B"}. Otherwise, unused and can then be omitted. \item A scalar: for the codes \texttt{"C"}, \texttt{"lrC"}, \texttt{"A"} and \texttt{"B"}, the fixed value to which the matrix element should be set (may be omitted if 0). Otherwise, unused and can then be omitted. \end{enumerate} A few examples: \begin{itemize} \item \dtk{SVAR_restrict(&M, "C", 3, 2, 0)}; in a C model called \texttt{M}, sets $C_{3,2} = 0$. As a consequence, the IRF for variable number 3 with respect to the shock number 2 starts from zero. \item \dtk{SVAR_restrict(&foo, "A", 1, 2, 0)}; in an AB model called \texttt{foo}, sets $A_{1,2} = 0$. \item \dtk{SVAR_restrict(&MyMod, "lrC", 5, 3, 0)}; in a C model called \texttt{MyMod}, restricts $C$ such that the long-run impact of shock number 3 on variable number 5 is 0. This implies that the cumulated IRF for variable 5 with respect to shock 3 tends to zero. \item \dtk{SVAR_restrict(&Mod2, "B", \{NA, 0; NA, NA\})} specifies a pattern matrix in a 2-dimensional system to restrict the 1,2-element of the B matrix to zero. \item \dtk{SVAR_restrict(&bar, "Adiag", 1)}; in an AB model called \texttt{bar}, sets $A_{i,i} = 1$ for $1 \le i \le n$. \item \dtk{SVAR_restrict(&baz, "Bdiag", NA)}; in an AB model called \texttt{baz}, sets $B_{i,j} = 0$ for $i \ne j$. \end{itemize} If the restrictions are found to conflict with other ones already implied by the pre-existing constraints, they will just be ignored and a warning will be printed. Note that this function can be used (albeit in a limited way) in the context of set-identified models. See section \ref{sec:mixed} for more details. \end{funcdoc} \begin{funcdoc}{\detokenize{SVAR_setup} (string type, list Y, list X, int varorder, bool checkident[1])} \noindent Returns a bundle with the initialised model. \noindent Arguments: \begin{enumerate} \item A type string: valid values are \texttt{"C"}, \texttt{"plain"}, \texttt{"AB"}, \texttt{"SVEC"}, and now also \texttt{"SR"}. \item A list containing the endogenous variables. \item A list containing the exogenous variables. \item A positive integer, the VAR order. \item A switch: For traditional (non set-identified) models it means to activate or suppress the automatic identification check before estimation of the structural form (default on). Otherwise (for type \texttt{"SR"}) this doesn't make sense, and the meaning of the switch is instead whether to store all the produced IRF data from the accepted draws into the model bundle (default yes). Since the bundle's size will be much larger with all the draws, sometimes you may want to avoid the storage. (You do not need to keep the raw data for standard IRF plots, but you will need it for "spaghetti" plots and in case you change your mind about the coverage probability of the error bands later.) \end{enumerate} \end{funcdoc} \begin{funcdoc}{\detokenize{SVAR_spagplot} (bundle Smod, string vname, string sname, string fname (optional))} \noindent Relating to a set identified (sign restricted) model, does a ``spaghetti'' plot of the IRFs, i.e. simply plotting the IRF of each accepted draw as a thin line. This complementary analysis avoids the criticism of aggregating horizon-per-horizon. In order to work the data of the draws must have been stored inside the model bundle (which is the default). The plot will be displayed in interactive mode unless a file name or path location in the ``fname'' argument, in which case the file extension determines the output graphics format produced by gnuplot. \noindent Arguments: \begin{enumerate} \item the model bundle (not pointerized, since nothing will be stored) \item the name of the target variable \item the name of the shock of interest \item optional file name (inside the current workdir) or full path of the output file (default: display plot on screen) \end{enumerate} \end{funcdoc} \begin{funcdoc}{\detokenize{SVAR_SRdraw} (bundle *Smod, int rep, bool DO\_BAYES[0], scalar coveralpha[0.9],\\ int maxiter[10000])} \noindent Relating to a set identified (sign restricted) model, this function draws random rotations of the arbitrary baseline Cholesky model until \texttt{rep} draws satisfying the sign restrictions have come up, or until the \texttt{maxiter} limit is hit. Therefore the number of good draws can be anything between zero and \texttt{rep}. If the DO\_BAYES flag is on, the VAR parameters (including Sigma) are resampled too (from a standard Normal-Wishart distribution); otherwise, they are kept fixed at the OLS estimates. This is the heart of the set identification algorithm and will take a while to run. (The goal is to speed it up in the future, e.g. by parallelizing it on multicore machines.) \emph{Returns}: \texttt{array of bundles}, one for each accepted draws. By default you would \emph{not} need to produce or grab this object directly because this array would be stored inside the main model bundle as member \dtk{acc_draws} and then processed automatically. So only use it under special circumstances. \noindent Arguments: \begin{enumerate} \item pointer to the SVAR model bundle \item the number of (accepted) draws $H$ to aim for \item Boolean flag for the Bayesian option (default = 0 $\to$ frequentist / no parameter uncertainty) \item the desired empirical coverage of the calculated intervals (default 90\%) \item Maximum number of attempted draws (default = 10000) \end{enumerate} \end{funcdoc} \begin{funcdoc}{\detokenize{SVAR_SRexotic} (bundle *Smod, string chkstr, strings shocks, \\ int length[0], int ini[0])} % left bool needs_model undocumented for now (Sven) \noindent Relating to a set identified (sign restricted) model, this is an experimental function serving to specify "exotic" restrictions, i.e. those that intrinsically involve more than one variable-shock pair.\footnote{Here we are not talking about the case of having several restrictions where each of them concerns a different variable-shock pair. Such a scenario is of course already covered by the more standard approaches, see \dtk{SVAR_SRplain, SVAR_SRfull}, simply applying and combining several restrictions. Instead, the question here is how to deal with any additional restriction which intrinsically links more than one impulse response.} See section \ref{sec:SR} for an explanation of the usage. \noindent Arguments: \begin{enumerate} \item model bundle in pointerized form \item A string with a valid numerical evaluation of some function of the individual IRFs. This expression will be evaluated at each of the horizons specified by \texttt{ini} and \texttt{length}. In this expression string the IRF matrix must be hardcoded as "M", so the concrete impulse responses (variable-shock pairs) must appear as "M[2,1]", or "M[2,4]", etc. Cross-horizon restrictions are not possible (yet?). \item array of strings, the collection of all shock names that play a role in this restriction\footnote{% This information is in principle already contained in the restriction expression, but we are too lazy to parse that string properly and want to be on the safe side, so we shift that responsibility to the user -- later on it may also serve as a cross-check to catch unwanted input errors.} \item see \dtk{SVAR_SRplain (length)} \item see \dtk{SVAR_SRplain (ini)} \end{enumerate} \end{funcdoc} \begin{funcdoc}{\detokenize{SVAR_SRfull} (bundle *Smod, string yname, string sname, scalar lo (optional),\\ scalar hi (optional), int ini[0], int fin[0])} \noindent Relating to a set identified (sign restricted) model, this function serves to impose restrictions that are more general than sign restrictions in the narrow sense but are still not "exotic" in the sense that they only conern a single IRF (single variable-shock pair). \noindent Arguments: \begin{enumerate} \item model bundle in pointerized form \item name of the target variable of the relevant IRF \item name of the shock of the relevant IRF \item lower bound for the IRF to satisfy this restriction (default is minus infinity) \item upper bound for the IRF to satisfy this restriction (default is infinity) \item starting horizon from which to evaluate the IRF (default zero is on impact) \item end horizon up to which to evaluate the IRF (default zero is on impact) \end{enumerate} Each of the bounds \texttt{lo, hi} is optional, but at least one of them has to be specified to make it a meaningful restriction. In contrast, both \texttt{ini, fin} could be left at their defaults (be omitted), which would mean a restriction only associated with the impact effect. \end{funcdoc} \begin{funcdoc}{\detokenize{SVAR_SRirf} (bundle Smod, strings whichvars [optional], \\ strings whichshocks [optional], bool meanormed[0])} \noindent Relating to a set identified (sign restricted) model, does IRF plots based on all accepted draws. The empirical coverage level of the plotted confidence bands (or credible sets, if you like) must have been chosen previously at the stage of getting the draws (see \dtk{SVAR_SRdraw}, but also see \dtk{SVAR_SRresetalpha}).% \footnote{% % If you change your mind about the desired coverage level % but want to avoid re-running the computationally intensive drawing stage, the following hack % should work in theory: (1) Set the bundle element \texttt{Smod.SRcoveralpha} to the desired level. % (2) Call the relevant helper function like this: % \dtk{ bundle newIrfdata = IRF_plotdata(Smod.acc_draws, Smod.SRcoveralpha)}. % (3) Copy over the following % elements from \texttt{newIrfdata} to \texttt{Smod} and observe the internally different names: % \dtk{irfSRmeans $\rightarrow$ SRirfmeans, lo_cb $\rightarrow$ SRlo_cb, % hi\_cb $\rightarrow$ SRhi\_cb, irfSRmeds $\rightarrow$ SRirfmeds.} % This hack is not % guaranteed to work in the future. (We should probably add a helper function to automate this.) } \emph{Returns}: \texttt{array of strings}, where each string array element holds the created gnuplot plotting code for one of the chosen set of sign-restricted / set-identified IRF plots, for potential further use. Simply ignore or discard the return value if it is not needed. \noindent Arguments: \begin{enumerate} \item the model bundle (not pointerized, since nothing will be stored) \item array of strings: collection of all target variable names to consider (default: all) \item array of strings: collection of all shock names of interest (default: all) \item switch to choose medians as the center line of the plots (default: 0/mean) \end{enumerate} It is not possible to exclude single variable-shock pairs, simply delete any unwanted plots afterwards. \end{funcdoc} \begin{funcdoc}{\detokenize{SVAR_SRgetbest} (bundle *Smod, string vname, string sname, int ini[0::0], \\ int length[0::0], int disttarg[0:1:0], string loss[null]) } \noindent Relating to a set identified (sign restricted) model, this function returns the (scalar) index number among all accepted draws of that particular draw which has a certain impulse response (as specified by the user in this call) closest to the central tendency of all draws. Also stores this number in the model bundle under ``bestdraw''. \noindent Arguments: \begin{enumerate} \item A bundle holding the model (pointer form). \item The name of the target variable in the interesting IRF. \item The name of the shock in the interesting IRF. \item The first period/horizon at which the IRF should be compared. (Default 0, on impact) \item The length of the horizon over which the IRF should be compared. (Default 0, only for the single period given before) \item A switch choosing whether to target the mean (0) or the median (1) of the IRF distribution. (Default 0) \item The loss function name to evaluate deviations from the target. Possible values are ``quad'' (default) and ``abs''. \end{enumerate} \end{funcdoc} \begin{funcdoc}{\detokenize{SVAR_SRplain} (bundle *Smod, string yname, string sname, string what, \\ int length[0], int ini[0])} \noindent Relating to a set identified model, this function serves to impose standard sign restrictions. \noindent Arguments: \begin{enumerate} \item model bundle in pointerized form \item name of the target variable of the relevant IRF \item name of the shock of the relevant IRF \item either "+" or "-" to specify the wanted sign \item for how many (horizon) periods after \texttt{ini} the restriction should apply (default zero, just at the particular point given by \texttt{ini}) \item starting horizon from which to evaluate the IRF (default zero / on impact) \end{enumerate} Both \texttt{length, ini} could be left at their defaults (be omitted), which would mean a restriction only associated with the impact effect. If only the trailing argument \texttt{ini} is omitted, then the restriction must hold up to horizon \texttt{length}. \end{funcdoc} \begin{funcdoc}{\detokenize{SVAR_SRresetalpha} (bundle *Smod, scalar alpha)} \noindent Relating to a set identified model, this function allows to redefine the desired coverage level of the pointwise confidence intervals without having to repeat the time-consuming model drawing stage. If necessary, this function would typically be called before \dtk{SVAR_SRirf}. \noindent Arguments: \begin{enumerate} \item model bundle in pointerized form \item desired new coverage probability of IRF confidence intervals \end{enumerate} \end{funcdoc} %--------------------------------------------------------------------------------------------------- \section{Contents of the model bundle} \label{sec:bundle_struct} \centering \begin{tabular}{rp{0.8\textwidth}} \hline \multicolumn{2}{c}{\textbf{Basic setup}} \\ \hline \texttt{step} & done so far \\ \texttt{type} & integer, model type (1: PLAIN, 2: C, 3: AB, 4: SVEC)\\ \texttt{n, k} & numbers of endogenous and exogenous variables \\ \texttt{p} & VAR order \\ %\texttt{k} & number of exogenous variables \\ \texttt{T} & number of observations \\ \texttt{t1, t2} & initial and final observations \\ \texttt{Y} & endogenous variables data matrix \\ \texttt{X} & exogenous variables data matrix \\ \dtk{calc_lr} & switch to get long-run matrix \texttt{lrmat} in short-run models \\ \texttt{checkident} & switch indicating whether to check identification before estimation\\ \texttt{calinfo} & bundle, calendar info: the ``t1'', ``t2'' and ``pd'' keys are taken from the corresponding accessors when the model was created. The ``limitobs'' matrix is a 2-row matrix with a numerical representation of the dates for the first and last observations \end{tabular} \begin{tabular}{rp{0.8\textwidth}} \hline \multicolumn{2}{c}{\textbf{VAR}} \\ \hline \texttt{VARpar} & autoregressive parameters \\ \texttt{mu} & coefficients for the deterministic (/exogenous) terms \\ \texttt{U} & residuals from base VAR (As matrix; this used to be \texttt{E} before the notation change in version 1.95. Please adapt your scripts.) \\ \texttt{Sigma} & unrestricted residual covariance matrix \\ \texttt{jalpha} & (SVEC only) cointegration loadings \\ \texttt{jbeta} & (SVEC only) cointegration coefficients \\ \texttt{crank} & (SVEC only) cointegration rank (inferred from jbeta)\\ \texttt{jcase} & (SVEC only) deterministic setup (1 to 5)\\ \end{tabular} \begin{tabular}{rp{0.8\textwidth}} \hline \multicolumn{2}{c}{\textbf{SVAR setup}} \\ \hline \texttt{Rd1} & short-run constraints on B (and therefore C in non-AB models) \\ \texttt{Rd1l} & long-run constraints on C \\ \texttt{Rd0} & short-run constraints on A in AB models \\ \texttt{horizon} & horizon for structural VMA \\ \texttt{cumul} & vector of cumuland variables \\ \texttt{ncumul} & number of cumuland variables \\ \texttt{Ynames} & names for VAR variables (string array)\\ \texttt{Xnames} & names for exogenous (string array) variables, if any \\ \texttt{snames} & names for shocks (string array) \\ \texttt{optmeth} & integer between 0 and 4, optimisation method \\ \texttt{normalize} & switch for shock rescaling, see section \ref{sec:IRF-FEVD} \\ \end{tabular} \begin{tabular}{rp{0.8\textwidth}} \hline \multicolumn{2}{c}{\textbf{SVAR post-estimation}} \\ \hline \texttt{S1, S2, C} & estimated A, B, C \\ % \texttt{S2} & estimated B \\ % \texttt{C} & estimated C \\ \texttt{lrmat} & estimated long-run matrix \\ \texttt{theta} & identified coefficients as vector \\ \texttt{vcv} & covariance matrix of these coefficients \\ \texttt{IRFs} & IRF matrix (see section \ref{sec:baseest})\\ \texttt{LL0, LL1} & Unrestricted and restricted maximized likelihoods \\ \end{tabular} \begin{tabular}{rp{0.8\textwidth}} \hline \multicolumn{2}{c}{\textbf{Bootstrap-related}} \\ \hline \texttt{nboot} & integer, number of bootstrap replications \\ \dtk{boot_alpha} & scalar, bootstrap confidence level (coverage)\\ \texttt{bootdata} & output from the bootstrap (see section \ref{sec:bootstrap})\\ \texttt{biascorr} & 0 for no bias correction, 1 for partial, 2 for full\\ \texttt{BCiter} & integer, number of replications for the bias correction \\ \texttt{boottype} & 1 for standard residual resampling, 2-4 for residual-based wild bootstraps (2: Normal, 3: Rademacher, 4: Mammen), 5 for moving blocks \\ \texttt{movblocklen} & integer, changes the block length for the moving blocks bootstrap (otherwise: use 10\% of the sample length) \end{tabular} \begin{tabular}{rp{0.8\textwidth}} \hline \multicolumn{2}{c}{\textbf{Set-identification (sign restrictions) -related}} \\ \hline \texttt{SRiter} & integer, number of draws actually done \\ \texttt{SRacc} & integer, number of accepted draws stored and used\\ \dtk{SRid_snames} & strings array, names of those shocks that are subject to sign (and similar) restrictions, subset of \texttt{snames}\\ \texttt{SRest} & matrix, internal representation of the (non-exotic) set identification restrictions; each row has: variable id number, lower bound, upper bound, starting horizon, end horizon, shock id number \\ \texttt{exoticSR} & bundle, holding internal representation of exotic (and in the future also super-exotic) restrictions; contains a strings array \texttt{checks} with the user-supplied restriction expressions, a two-column matrix \texttt{spans} with starting and ending horizons for the respective restriction, and a vector \texttt{super} holding indicators (zero or one) whether the restriction is super-exotic\footnote{see the documentation about this special feature, when it is ready}\\ \texttt{SRcoveralpha} & scalar, chosen coverage of the confidence intervals (or credible sets)\\ \texttt{SRirfmeans} & matrix, holding the horizon-by-horizon pointwise means of the accepted IRF draws; horizons in $h+1$ rows and the variable/shock combinations in $n*numshocks$ columns\\ \texttt{SRirfmeds} & matrix, holding the horizon-by-horizon pointwise medians of the accepted IRF draws; dimensions see \texttt{SRirfmeans}\\ \texttt{SRirfserrs} & matrix, the horizon-by-horizon pointwise (pseudo) standard errors of the accepted IRF draws; dimensions see \texttt{SRirfmeans}\\ \dtk{SRlo_cb} & matrix, the horizon-by-horizon pointwise lower bounds of the confidence intervals (or credible sets), quantile-based (not symmetric around the means or medians); dimensions see \texttt{SRirfmeans}\\ \dtk{SRhi_cb} & matrix, ditto for the upper bounds\\ \texttt{storeSRirfs} & switch indicating whether the IRF outcomes from all accepted draws will be stored in the main model bundle (see also \dtk{acc_draws})\\ \dtk{acc_draws} & array of bundles, collecting the outcomes and data of all accepted draws; this member is absent if suppressed at the setup stage. The data type and the stored representation of the draws is still experimental and subject to change.\\ \texttt{bestdraw} & positive integer to index the best of all accepted draws in \dtk{acc_draws} according to criteria specified in call to \dtk{SVAR_SRgetbest}. Zero if undefined. \end{tabular} \section{Changelog (after v1.2)} \label{sec:changelog} \subsection*{for gretl version 2024c, October 2024} \begin{itemize} \item Get rid of version number since SVAR is a gretl addon, and starting with gretl 2024b such official addons inherit the version number directly from gretl itself. \item Extend the \dtk{SVAR_restrict} function to accept full restriction pattern matrices. \item Extend the \dtk{SVAR_SRirf} function to return the created plotting codes in a strings array (returned nothing before, just ran the plots). \item Use a more efficient normal-inverse-Wishart generation algorithm. \item Properly generate the uniformly distributed rotation matrices (internally with the new \dtk{gen_haar} function). \item Fix a bug with the spaghetti plot (for set-id models) in case of partial identification. \item Try to fix more sub-cases with only ``exotic'' restrictions (and no standard set-id restrictions); but probably more work needed. \item Fix minor bug (not noticeable with standard usage): do not internally require the bundle member E from the old-style (pre 1.95) notation anymore. While we're at it, do not carry this compatiblity copy around anymore at all, so the estimated residuals are now exclusively in the matrix member U. \end{itemize} \subsection*{Version 2.1, November 2023} \begin{itemize} \item Add the ``calinfo'' bundle to the model bundle. \item Switch to the ``stacked-bars'' version for historical decomposition plots. \end{itemize} \subsection*{Version 2.0, June/July 2023} \begin{itemize} \item Implement mixed (sign- and zero-) restrictions. Deprecate \cmd{SRgetbest} in favour of \dtk{SVAR_SRgetbest}. \item Move the internal function drawbootres to the extra addon, and along the way fix a bug with the moving blocks bootstrap, the explicit choice of the block length was not honored (probably introduced in 2021). \item Fix for "spaghetti" plots with output paths that include spaces. \end{itemize} \subsection*{Version 1.98, May 2023} \begin{itemize} \item Fix documentation on sign restrictions. \end{itemize} \subsection*{Version 1.97, July 2022} \begin{itemize} \item Fix fatal bug preventing the output of plots with HDsave() and FEVDsave(). Use the new commute() function internally. \end{itemize} \subsection*{Version 1.96, December 2021} \begin{itemize} \item Fix bug in path to plot files on MS Windows. \end{itemize} \subsection*{Version 1.95, June 2021} \begin{itemize} \item Start cleaning up and modernizing the internals, and big jump making 2021a the required gretl version because of that. \item Swap notation to stay in line with most of the literature, $\varepsilon$ are now the structural shocks and $u$ become the prediction errors (reduced form). For SVAR scripting this means that the residual matrix \texttt{E} in the bundle is now called \texttt{U}. \end{itemize} \subsection*{Version 1.94, April 2021} \begin{itemize} \item Fix bug (introduced in 1.32 or so): for AB-models, the $C$ matrix was not updated over bootstrap iterations, leading to zero-width confidence intervals for the impact effect. \item Bump version requirement to 2018c to accommodate some internal changes. \end{itemize} \subsection*{Version 1.93, December 2020} \begin{itemize} \item Add helper function SVAR\_SRresetalpha. (Hide IRF\_plotdata as redundant because of that.) \item Enable saving sign-restriction spaghetti plot to file. \end{itemize} \subsection*{Version 1.92, August/September 2020} \begin{itemize} \item Clarify documentation for Bayesian draws in set-id models. \item Replace deprecated funcerr() with errorif(), therefore need gretl 2020b for the sign restriction part. \end{itemize} \subsection*{Version 1.91, April 2020} \begin{itemize} \item Minor plot legend fix for GUI usage; a fix of DoF calculation for Bayesian redrawing; catch the case of no accepted draws more gracefully. \item Introduce new convenience function SRgetbest to find the best draw according to user-specified IRF criterion. \item New functions with alternative interface: SVAR\_HD (wrapper for SVAR\_hd) and SVAR\_getshock (wrapper for GetShock). \end{itemize} \subsection*{Version 1.90, March 2020} \begin{itemize} \item Major new feature: set-identified model estimation (a.k.a. sign restrictions; scripting interface only). \end{itemize} \subsection*{Version 1.52, November 2019} \begin{itemize} \item Fix the Luetkepohl (2008) check for SVECs with weakly exogenous variables, and actually process the existing extra check whether a restriction might be redundant, which is relevant mostly in the case of some weakly exogenous variables. Also for SVECs, check whether a long-run restriction really applies to a permanent shock. \item The identification check output is now suppressed by default to avoid clutter. (It is still run by default, but quietly.) \item Some documentation updates. \end{itemize} \subsection*{Version 1.51, September 2019} \begin{itemize} \item Also add the moving blocks bootstrap by \cite{BrugJenTrenk16} as an option. \end{itemize} \subsection*{Version 1.5, September 2019} \begin{itemize} \item The documentation of the bootstrap $\alpha$ level did not match the actual implementation. This has been changed such that \dtk{boot_alpha} really represents the nominal coverage of the confidence intervals around each impulse response. (This quantity is often denoted with $1 - \alpha$ instead, but for backward compatibility we stick to $\alpha$.) Attention: This change means that existing scripts will produce systematically different (wider) confidence bands with this version. \item Add the option 'boottype' to choose some wild bootstrap variants to account for heteroskedasticity. \item Reformat the identification check output. \item Add the possibility to choose the bias correction directly in the call to \dtk{SVAR_boot}. \end{itemize} \subsection*{Version 1.4, March 2019} \begin{itemize} \item catches of wrong user input: catch the case when no restrictions are given, to prevent other errors; catch a missing cointegration setup when trying to estimate a SVEC; add a linear dependency check on the exogenous terms in \dtk{SVAR_setup}; catch the case where restrictions would not work (\texttt{imp2exp}) and print out a message \item fixes in the SVEC case especially with further exogenous variables: fix indexing error and mis-concatenation, and companion matrix in \dtk{vecm_est} with exogenous; and fix the restricted terms in the bootstrap \item internal changes: simplify centered seasonals creation in determ(), replace isnull with !exists (and vice versa) \item interface: allow omission of alpha in \dtk{SVAR_coint} \item New argument 'checkident' in SVAR\_setup. Checking identification is now default in script use. \item A new restriction check in the SVEC case (Luetkepohl 2008). \end{itemize} \subsection*{Version 1.36, July 2018} \begin{itemize} \item Update this documentation to reflect previous changes. \item fix a transposed matrix product in SVECM estimation for cases 2 and 4 \end{itemize} \subsection*{Version 1.35, May 2018} \begin{itemize} \item Enable 0 index (meaning ``all'') in plotting functions \end{itemize} \subsection*{Version 1.33 and 1.34, April 2018} \begin{itemize} \item Fix breakage in \verb|init_C| function \item Allow a C-model with no estimated parameters \item Fix constant in cointegrated case \end{itemize} \subsection*{Version 1.31 and 1.32, January 2018} \begin{itemize} \item Update this documentation to reflect some previous changes. \item Fix failing printout for bootstrap. (v1.32: Sanitize further the printout of the long-run matrix.) \item Enable long-run matrix calculation and reporting also for SVEC models. \end{itemize} \subsection*{Version 1.3, December 2017} \begin{itemize} \item The full bias correction now also corrects the estimated A/B/C matrices explicitly, not only the implied IRFs. \item Make it clear that long-run restrictions are not supported in AB models. \item Calculate the long-run matrix and put it into the model bundle as \texttt{lrmat}. Also add a boolean switch \dtk{calc_lr} to the model bundle to force its calculation when it would normally not be done (in models with short-run constraints only). \item The case of a SVEC model with Blanchard-Quah restrictions on top might not have been handled correctly, and should be OK now (but the bootstrap is currently not allowed in this case). \item Require \texttt{gretl} version $>$2016c or $>$2017a due to internal changes. \end{itemize} \end{document} %%% Local Variables: %%% mode: latex %%% TeX-master: t %%% End: