\chapter{Solving DSGE models - advanced topics} \label{ch:soladv}

This chapter is a collection of topics - not all related to each other - that you will probably find interesting or at least understandable, if you have read, and/ or feel comfortable with, the earlier chapter \ref{ch:solbase} on the basics of solving DSGE models. To provide at least some consistency, this chapter is divided into three sections. \textbf{The first section} deals directly with features of Dynare, such as dealing with correlated shocks, finding and saving your output, using loops, referring to external files and dealing with infinite eigenvalues. \textbf{The second section} overviews some of the inner workings of Dynare. The goal is to provide a brief explanation of the files that are created by Dynare to help you in troubleshooting or provide a starting point in case you actually want to customize the way Dynare works.  \textbf{The third section} of the chapter focusses on modeling tips optimized for Dynare, but possibly also helpful for other work.\\

\section{Dynare features and functionality}

\subsection{Other examples}
Other examples of .mod files used to generate impulse response functions are available on the Dynare website. In particular, Jesus Fernandez-Villaverde has provided a series of RBC model variants (from the most basic to some including variable capacity utilization, indivisible labor and investment specific technological change). You can find these, along with helpful notes and explanations, in the \href{http://www.dynare.org/documentation-and-support/examples}{Official Examples} section of the Dynare website.\\

Also, don't forget to check occasionally the \href{http://www.dynare.org/phpBB3}{Dynare contributions and examples forum} to see if any other user has posted an example that could help you in your work; or maybe you would like to post an example there yourself?

\subsection{Alternative, complete example}
The following example aims to give you an alternative example to the one in chapter \ref{ch:solbase}, to learn the workings of Dynare. It also aims to give you exposure to dealing with \textbf{several correlated shocks}. Your model may have two or more shocks, and these may be correlated to each other. The example below illustrates how you would introduce this into Dynare.  Actually, the example provided is somewhat more complete than strictly necessary. This is to give you an alternative, full-blown example to the one described in chapter \ref{ch:solbase}.

\subsubsection{The model}
The model is a simplified standard RBC model taken from \citet{CollardJuillard2003} which served as the original User Guide for Dynare. \\

The economy consists of an infinitely living representative agent who values consumption $c_t$ and labor services $h_t$ according to the following utility function
\[
\mathbb{E}_t \sum_{\tau=t}^\infty \beta^{\tau-t} \left( \log (c_t) - \theta \frac{h_t^{1+\psi}}{1+\psi} \right)
\] 
where, as usual, the discount factor $0<\beta<1$, the disutility of labor $\theta > 0$ and the labor supply elasticity $\psi \geq 0$. \\

A social planner maximizes this utility function subject to the resource constraint
\[
c_t + i_t = y_t
\]
where $i_t$ is investment and $y_t$ output. Consumers are therefore also owners of the firms. The economy is a real economy, where part of output can be consumed and part invested to form physical capital. As is standard, the law of motion of capital is given by
\[
k_{t+1} = \exp (b_t)i_t + (1-\delta)k_t
\]
with $0<\delta<1$, where $\delta$ is physical depreciation and $b_t$ a shock affecting incorporated technological progress. \\

We assume output is produced according to a standard constant returns to scale technology of the form
\[
y_t = \exp (a_t)k_t^\alpha h_t^{1-\alpha}
\]
with $\alpha$ being the capital elasticity in the production function, with $0<\alpha<1$, and where $a_t$ represents a stochastic technological shock (or Solow residual). \\

Finally, we specify a \textbf{shock structure} that allows for shocks to display persistence across time and correlation in the current period. That is
\[
\left( \begin{array}{c}a_t \\
b_t \end{array} \right) = \left( \begin{array}{c c} \rho & \tau \\
\tau & \rho \end{array} \right) \left( \begin{array}{c}a_{t-1} \\
b_{t-1} \end{array} \right) + \left( \begin{array}{c}\epsilon_t \\
\nu_t \end{array} \right)
\]
where $|\rho + \tau|<1$ and $|\rho - \tau|<1$ to ensure stationarity (we call $\rho$ the coefficient of persistence and $\tau$ that of cross-persistence). Furthermore, we assume $\mathbb{E}_t (\epsilon_t)=0$, $\mathbb{E}_t (\nu_t)=0$ and that the contemporaneous variance-covariance matrix of the innovations $\epsilon_t$ and $\nu_t$ is given by
\[
\left( \begin{array}{c c} \sigma_\epsilon^2 & \psi \sigma_\epsilon \sigma_\nu \\
\psi \sigma_\epsilon \sigma_\nu & \sigma_\nu^2 \end{array} \right)
\]
and where $corr(\epsilon_t \nu_s)=0$, $corr(\epsilon_t \epsilon_s)=0$ and $corr(\nu_t \nu_s)=0$ for all $t \neq s$. \\

This system - probably quite similar to standard RBC models you have run into - yields the following first order conditions (which are straightforward to reproduce in case you have doubts\ldots) and equilibrium conditions drawn from the description above. Note that the first equation captures the labor supply function and the second the intertemporal consumption Euler equation.
\[
\begin{aligned}
c_t \theta h_t^{1+\psi} = (1-\alpha)y_t \\
1= \beta \mathbb{E}_t \left[ \left( \frac{\exp(b_t)c_t}{\exp(b_{t+1})c_{t+1}} \right) \left( \exp(b_{t+1}) \alpha \frac{y_{t+1}}{k_{t+1}}+1-\delta \right) \right] \\
y_t = \exp (a_t)k_t^\alpha h_t^{1-\alpha} \\
k_{t+1} = \exp (b_t)i_t + (1-\delta)k_t \\
a_t = \rho a_{t-1} + \tau b_{t-1} + \epsilon_t \\
b_t = \tau a_{t-1} + \rho b_{t-1} + \nu_t
\end{aligned}
\] 

\subsubsection{The .mod file}
To ``translate'' the model into a language understandable by Dynare, we would follow the steps outlined in chapter \ref{ch:solbase}. We will assume that you're comfortable with these and simply present the final .mod file below. Fist, though, note that to introduce shocks into Dynare, we have two options (this was not discussed in the earlier chapter). Either write:\\
\\
\texttt{shocks;\\
var e; stderr 0.009;\\
var u; stderr 0.009;\\
var e, u = phi*0.009*0.009;\\
end;}\\
\\
where the last line specifies the contemporaneous correlation between our two exogenous variables. \\

Alternatively, you can also write: \\
\\
\texttt{shocks;\\
var e = 0.009\textasciicircum 2;\\
var u = 0.009\textasciicircum 2;\\
var e, u = phi*0.009*0.009;\\
end;}\\

So that you can gain experience by manipulating the entire model, here is the complete .mod file corresponding to the above example. You can find the corresponding file in the \textsl{models} folder under \textsl{UserGuide} in your installation of Dynare. The file is called \textsl{Alt\_Ex1.mod}. \\
\\
\\
\texttt{var y, c, k, a, h, b;\\
varexo e, u;\\
parameters beta, rho, alpha, delta, theta, psi, tau;\\
\\
alpha = 0.36;\\
rho   = 0.95;\\
tau   = 0.025;\\
beta  = 0.99;\\
delta = 0.025;\\
psi   = 0;\\
theta = 2.95;\\
\\
phi   = 0.1;\\
\\
model;\\
c*theta*h\textasciicircum (1+psi)=(1-alpha)*y;\\
k = beta*(((exp(b)*c)/(exp(b(+1))*c(+1)))\\
    *(exp(b(+1))*alpha*y(+1)+(1-delta)*k));\\
y = exp(a)*(k(-1)\textasciicircum alpha)*(h\textasciicircum (1-alpha));\\
k = exp(b)*(y-c)+(1-delta)*k(-1);\\
a = rho*a(-1)+tau*b(-1) + e;\\
b = tau*a(-1)+rho*b(-1) + u;\\
end;\\
\\
initval;\\
y = 1.08068253095672;\\
c = 0.80359242014163;\\
h = 0.29175631001732;\\
k = 5;\\
a = 0;\\
b = 0;\\
e = 0;\\
u = 0;\\
end;\\
\\
shocks;\\
var e; stderr 0.009;\\
var u; stderr 0.009;\\
var e, u = phi*0.009*0.009;\\
end;\\
\\
stoch\_simul(periods=2100);}\\

\subsection{Finding, saving and viewing your output} \label{sec:FindOut}
Where is output stored? Most of the moments of interest are stored in global variable \texttt{oo\_} You can easily browse this global variable in Matlab by either calling it in the command line, or using the workspace interface. In global variable \texttt{oo\_} you will find the following (\textsf{\textbf{NOTE!}} variables will always appear in the order in which you declared them in the preamble block of your .mod file):
\begin{itemize}
\item \texttt{steady\_state}: the steady state of your variables
\item \texttt{mean}: the mean of your variables
\item \texttt{var}: the variance of your variables
\item \texttt{autocorr}: the various autocorrelation matrices of your variables. Each row of these matrices will correspond to a variables in time $t$, and columns correspond to the variables lagged 1, for the first matrix, then lagged 2 for the second matrix, and so on. Thus, the matrix of autocorrelations that is automatically displayed in the results after running \texttt{stoch\_simul} has, running down each column, the diagonal elements of each of the various autocorrelation matrices described here. 
\item \texttt{gamma\_y}: the matrices of autocovariances. \texttt{gamma\_y\{1\}} represents variances, while \texttt{gamma\_y\{2\}} represents autocovariances where variables on each column are lagged by one period and so on. By default, Dynare will return autocovariances with a lag of 5. The last matrix (\texttt{gamma\_y\{7\}} in the default case) returns the \textbf{variance decomposition}, where each column captures the independent contribution of each shock to the variance of each variable. 
\end{itemize}

Furthermore, if you decide to run impulse response functions, you will find a global variable \texttt{oo\_.irfs} comprising of vectors named \texttt{endogenous variable\_exogenous variable}, like \texttt{y\_e}, reporting the values of the endogenous variables corresponding to the impulse response functions, as a result of the independent impulse of each exogenous shock. \\

To save your simulated variables, you can add the following command at the end of your .mod file: \texttt{dynasave (FILENAME) [variable names separated by commas]} If no variable names are specified in the optional field, Dynare will save all endogenous variables. In Matlab, variables saved with the \texttt{dynasave} command can be retrieved by using the Matlab command \texttt{load -mat FILENAME}.

\subsection{Referring to external files}
You may find it convenient to refer to an external file, either to compute the steady state of your model, or when specifying shocks in an external file. The former is described in section \ref{sec:ssshock} of chapter \ref{ch:solbase} when discussing steady states. The advantage of using Matlab, say, to find your model's steady state was clear with respect to Dynare version 3, as the latter resorted to numerical approximations to find steady state values. But Dynare version 4 now uses the same analytical methods available in Matlab. For most usage scenarios, you should therefore do just as  well to ask Dynare to compute your model's steady state (except, maybe, if you want to run loops, to vary your parameter values, for instance, in which case writing a Matlab program may be more handy).\\

But you may also be interested in the second possibility described above,
namely of specifying shocks in an external file, to simulate a model based on
shocks from a prior estimation, for instance. You could then retrieve the
exogenous shocks from the oo\_ file by saving them in a file called
datafile.mat. Finally, you could simulate a deterministic model with the shocks
saved from the estimation by specifying the source file for the shocks, using
the \\ \mbox{\texttt{initval\_file(filename = 'datafile.mat')}} command.
But of course, this is a bit of a workaround, since you could also use the built-in commands in Dynare to generate impulse response functions from estimated shocks, as described in chapter \ref{ch:estbase}. \\

\subsection{Infinite eigenvalues}
If you use the command \texttt{check} in your .mod file, Dynare will report your system's eigenvalues and tell you if these meet the Blanchard-Kahn conditions. At that point, don't worry if you get infinite eigenvalues - these are are firmly grounded in the theory of generalized eigenvalues. They have no detrimental influence on the solution algorithm. As far as Blanchard-Kahn conditions are concerned infinite eigenvalues are counted as explosive roots of modulus larger than one. \\

\section{Files created by Dynare} \label{sec:dynfiles}
At times, you may get a message that there is an error in a file with a new name, or you may want to have a closer look at how Dynare actually solves your model - out of curiosity or maybe to do some customization of your own. You may therefore find it helpful to get a brief overview of the internal files that Dynare generates and the function of each one. \\

The dynare pre-processors essentially does three successive tasks:
(i) parsing of the mod file (it checks that the mod file is syntactically
correct), and its translation into internal machine representation (in
particular, model equations are translated into expression trees), (ii) symbolic derivation of the model equations, up to the needed order
(depending on the computing needs), (iii) outputting of several files, which are used from matlab. If the mod
file is ``filename.mod", then the pre-processor creates the following
files:

\begin{itemize}
\item \textbf{filename.m}: a matlab file containing several instructions, notably
the parameter initializations and the matlab calls corresponding to
computing tasks
\item \textbf{filename\_dynamic.m}: a matlab file containing the model equations and
their derivatives (first, second and maybe third).
    Endogenous variables (resp. exogenous variables, parameters) are
contained in a ``y" (resp. ``x", ``params") vector, with an index number
depending on the declaration order.
    The ``y" vector has as many entries as their are (variable, lag)
pairs in the declared model.
    The model equations residuals are stored in a vector named
``residuals".
    The model jacobian is put in ``g1" matrix. Second (resp. third)
derivatives are in ``g2" matrix (resp. ``g3").
    If the ``use\_dll" option has been specified in the model declaration,
the pre-processor will output a C file (with .c extension) rather than a
matlab file. It is then compiled to create a library (DLL) file. Using a
compiled C file is supposed to give better computing performance in
model simulation/estimation.
\item \textbf{filename\_static.m}: a matlab file containing the stationarized
version of the model (i.e. where lagged variables are replaced by
current variables), with its jacobian. Used to compute the steady state.
Same notations than the dynamic file. Replaced by a C file when
``use\_dll" option is specified.
\end{itemize}

\section{Modeling tips}

\subsection{Stationarizing your model}
Models in Dynare must be stationary, such that you can linearize them around a steady state and return to steady state after a shock. Thus, you must first stationarize your model, then linearize it, either by hand, or by letting Dynare do the work.  You can then reconstruct ex-post the non-stationary simulated variables after running impulse response functions.\\

For deterministic models, the trick is to use only stationary variables in $t+1$. More generally, if $y_t$ is $I(1)$, you can always write $y_{t+1}$ as $y_t+dy_{t+1}$, where $dy_t= y_t-y_{t-1}$. Of course, you need to know the value of $dy_t$ at the final equilibrium.\\

Note that in a stationary model, it is expected that variables will eventually go back to steady state after the initial shock. If you expect to see a growing curve for a variable, you are thinking about a growth model. Because growth models are nonstationary, it is easier to work with the stationarized version of such models. Again, if you know the trend, you can always add it back after the simulation of the stationary components of the variables. 

\subsection{Expectations taken in the past}
For instance, to enter the term $\mathbb{E}_{t-1}y_t$, define $s_t=\mathbb{E}_t[y_{t+1}]$ and then use $s(-1)$ in your .mod file. Note that, because of Jensen's inequality, you cannot do this for terms that enter your equation in a non-linear fashion. If you do have non-linear terms on which you want to take expectations in the past, you would need to apply the above manipulation to the entire equation, as if $y_t$ were an equation, not just a variable.

\subsection{Infinite sums}

Dealing with infinite sums is tricky in general, and needs particular care when working with Dynare. The trick is to use a \textbf{recursive
representation} of the sum. For example, suppose your model included:
\[\sum^{\infty}_{j=0}\beta^j x_{t+j}=0, \]

Note that the above can also be written by using an auxiliary variable $S_t$, defined as:
\[S_t\equiv \sum^{\infty}_{j=0}\beta^j x_{t+j},\]
which can also be written in the following recursive manner:
\[S_t\equiv \sum^{\infty}_{j=0}\beta^j x_{t+j}=x_t +\sum^{\infty}_{j=1}\beta^j
x_{t+j}=x_t+\beta\sum^{\infty}_{j=0}\beta^j x_{t+1+j} \equiv x_t + S_{t+1}\]

This formulation turns out to be useful in problems of the following
form:

\[\sum^{\infty}_{j=0}\beta^j x_{t+j}=p_t\sum^{\infty}_{j=0}\gamma^j y_{t+j}, \]
which can be written as a recursive system of the form:
\[S1_t=x_t+\beta S1_{t+1},\]
\[S2_t=y_t+\gamma S2_{t+1},\]
\[S1=p_t S2.\]

This is particularly helpful, for instance, in a \textbf{Calvo type setting}, as illustrated in the following brief example. The RBC model with monopolistic competition introduced in chapter \ref{ch:solbase} involved flexible prices. The extension with sticky prices, � la Calvo for instance, is instead typical of the new Keynesian monetary literature, exemplified by papers such as \citet{ClaridaGaliGertler1999}. \\

The optimal price for a firm resetting its price in period $t$, given that it will be able to reset its price only with probability $1-\theta$ each  period, is
\[
p_t^*(i) = \mu + (1-\beta \theta) \sum_{k=0}^\infty (\beta \theta)^k \mathbb{E}_t [mc_{t+k}^n (i)]
\]
where $\mu$ is the markup, $\beta$ is a discount factor, $i$ represents a firm of the continuum between 0 and 1, and $mc_t$ is marginal cost as described in the example in chapter \ref{ch:solbase}. The trouble, of course, is \textbf{how to input this infinite sum into Dynare}? \\

It turns out that the Calvo price setting implies that the aggregate price follows the equation of motion $p_t = \theta p_{t-1} + (1-\theta) p_t^*$, thus implying the following inflation relationship $\pi_t = (1-\theta) (p_t^* - p_{t-1})$. Finally, we can also rewrite the optimal price setting equation, after some algebraic manipulations, as
\[
p_t^* - p_{t-1} = (1-\beta \theta) \sum_{k=0}^\infty (\beta \theta)^k \mathbb{E}_t [\widehat{mc}_{t+k}] + \sum_{k=0}^\infty (\beta \theta)^k \mathbb{E}_t [\pi_{t+k}]
\]
where $\widehat{mc}_{t+k} = mc_{t+k} + \mu$ is the deviation of the marginal cost from its natural rate, defined as the marginal cost when prices are perfectly flexible. \\

The trick now is to note that the above can be written recursively, by writing the right hand side as the first term of the sum (with $k=0$) plus the remainder of the sum, which can be written as the left hand side term scrolled forward one period and appropriately discounted. Mathematically, this yields:
\[
p_t^* - p_{t-1} =�(1-\beta \theta) \widehat{mc}_{t+k} + \pi_t + \beta�\theta \mathbb{E}_t [p_{t+1}^* - p_t]
\]
which has gotten rid of our infinite sum! That would be enough for Dynare, but for convenience, we can go one step further and write the above as
\[
\pi_t = \beta \mathbb{E}_t [\pi_{t+1}] + \lambda \widehat{mc}_{t}
\]
where $\lambda \equiv \frac{(1-\theta)(1-\beta\theta)}{\theta}$, which is the recognizable inflation equation in the new Keynesian (or new Neoclassical) monetary literature. 

\subsection{Infinite sums with changing timing of expectations}

When you are not able to write an infinite sum recursively, as the index of the expectations changes with each element of the sum, as in the following example, a different approach than the one mentioned above is necessary. \\

Suppose your model included the following sum: 
\[
y_t=\sum_{j=0}^{\infty} \mathbb{E}_{t-j}x_t
\]
where $y_t$ and $x_t$ are endogenous variables. \\

In Dynare, the best way to handle this is to write out the first $k$ terms explicitly and enter each one in Dynare, such as: $\mathbb{E}_{t-1}x_t + \mathbb{E}_{t-2}x_t+\ldots + \mathbb{E}_{t-k}x_t$.
