\input texinfo
@c %**start of header
@setfilename dynare.info
@documentencoding UTF-8
@set txicodequoteundirected

@settitle Dynare Reference Manual
@afourwide
@dircategory Math
@direntry
* Dynare: (dynare).             A platform for handling a wide class
                                  of economic models.
@end direntry

@include version.texi

@c Define some macros

@macro descriptionhead
@ifnothtml
@sp 1
@end ifnothtml
@emph{Description}
@end macro

@macro optionshead
@iftex
@sp 1
@end iftex
@emph{Options}
@end macro

@macro flagshead
@iftex
@sp 1
@end iftex
@emph{Flags}
@end macro

@macro examplehead
@iftex
@sp 1
@end iftex
@emph{Example}
@end macro

@macro exampleshead
@iftex
@sp 1
@end iftex
@emph{Examples}
@end macro

@macro remarkhead
@iftex
@sp 1
@end iftex
@noindent @emph{Remark}
@end macro

@macro outputhead
@iftex
@sp 1
@end iftex
@emph{Output}
@end macro

@macro algorithmhead
@iftex
@sp 1
@end iftex
@emph{Algorithm}
@end macro

@macro algorithmshead
@iftex
@sp 1
@end iftex
@emph{Algorithms}
@end macro

@macro customhead{title}
@iftex
@sp 1
@end iftex
@emph{\title\}
@end macro

@macro dates
@code{dates }
@end macro

@macro dseries
@code{dseries }
@end macro

@c %**end of header

@copying
Copyright @copyright{} 1996-2017, Dynare Team.

@quotation
Permission is granted to copy, distribute and/or modify this document
under the terms of the GNU Free Documentation License, Version 1.3 or
any later version published by the Free Software Foundation; with no
Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.

A copy of the license can be found at @uref{http://www.gnu.org/licenses/fdl.txt}.
@end quotation
@end copying

@titlepage
@title Dynare
@subtitle Reference Manual, version @value{VERSION}
@author Stéphane Adjemian
@author Houtan Bastani
@author Frédéric Karamé
@author Michel Juillard
@author Junior Maih
@author Ferhat Mihoubi
@author George Perendia
@author Johannes Pfeifer
@author Marco Ratto
@author Sébastien Villemot
@page
@vskip 0pt plus 1filll
@insertcopying
@end titlepage

@contents

@ifnottex
@node Top
@top Dynare
This is Dynare Reference Manual, version @value{VERSION}.

@insertcopying
@end ifnottex

@menu
* Introduction::
* Installation and configuration::
* Running Dynare::
* The Model file::
* The Configuration File::
* Time Series::
* Reporting::
* Examples::
* Dynare misc commands::
* Bibliography::
* Command and Function Index::
* Variable Index::

@detailmenu
 --- The Detailed Node Listing ---

Introduction

* What is Dynare ?::
* Documentation sources::
* Citing Dynare in your research::

Installation and configuration

* Software requirements::
* Installation of Dynare::
* Compiler installation::
* Configuration::

Installation of Dynare

* On Windows::
* On Debian GNU/Linux and Ubuntu::
* On Mac OS X::
* For other systems::

Compiler installation

* Prerequisites on Windows::
* Prerequisites on Debian GNU/Linux and Ubuntu::
* Prerequisites on Mac OS X::

Configuration

* For MATLAB::
* For GNU Octave::
* Some words of warning::

Running Dynare

* Dynare invocation::
* Dynare hooks::
* Understanding Preprocessor Error Messages::

The Model file

* Conventions::
* Variable declarations::
* Expressions::
* Parameter initialization::
* Model declaration::
* Auxiliary variables::
* Initial and terminal conditions::
* Shocks on exogenous variables::
* Other general declarations::
* Steady state::
* Getting information about the model::
* Deterministic simulation::
* Stochastic solution and simulation::
* Estimation::
* Model Comparison::
* Shock Decomposition::
* Calibrated Smoother::
* Forecasting::
* Optimal policy::
* Sensitivity and identification analysis::
* Markov-switching SBVAR::
* Displaying and saving results::
* Macro-processing language::
* Verbatim inclusion::
* Misc commands::

Expressions

* Parameters and variables::
* Operators::
* Functions::
* A few words of warning in stochastic context::

Parameters and variables

* Inside the model::
* Outside the model::

Functions

* Built-in Functions::
* External Functions::

Steady state

* Finding the steady state with Dynare nonlinear solver::
* Using a steady state file::
* Replace some equations during steady state computations::

Stochastic solution and simulation

* Computing the stochastic solution::
* Typology and ordering of variables::
* First order approximation::
* Second order approximation::
* Third order approximation::

Sensitivity and identification analysis

* Performing sensitivity analysis::
* IRF/Moment calibration::
* Performing identification analysis::
* Types of analysis and output files::

Types of analysis and output files

* Sampling::
* Stability Mapping::
* IRF/Moment restrictions::
* Reduced Form Mapping::
* RMSE::
* Screening Analysis::
* Identification Analysis::

Macro-processing language

* Macro expressions::
* Macro directives::
* Typical usages::
* MATLAB/Octave loops versus macro-processor loops::

Typical usages

* Modularization::
* Indexed sums or products::
* Multi-country models::
* Endogeneizing parameters::

The Configuration File

* Dynare Configuration::
* Parallel Configuration::
* Windows Step-by-Step Guide::

Time Series

* Dates::
* dseries class::

Dates

* dates in a mod file::
* dates class::

@end detailmenu
@end menu

@node Introduction
@chapter Introduction

@menu
* What is Dynare ?::
* Documentation sources::
* Citing Dynare in your research::
@end menu

@node What is Dynare ?
@section What is Dynare ?

Dynare is a software platform for handling a wide class of economic
models, in particular dynamic stochastic general equilibrium (DSGE)
and overlapping generations (OLG) models. The models solved by Dynare
include those relying on the @i{rational expectations} hypothesis, wherein
agents form their expectations about the future in a way consistent
with the model. But Dynare is also able to handle models where
expectations are formed differently: on one extreme, models where
agents perfectly anticipate the future; on the other extreme, models
where agents have limited rationality or imperfect knowledge of the
state of the economy and, hence, form their expectations through a
learning process. In terms of types of agents, models solved by Dynare
can incorporate consumers, productive firms, governments, monetary
authorities, investors and financial intermediaries. Some degree of
heterogeneity can be achieved by including several distinct classes of
agents in each of the aforementioned agent categories.

Dynare offers a user-friendly and intuitive way of describing these
models. It is able to perform simulations of the model given a
calibration of the model parameters and is also able to estimate these
parameters given a dataset. In practice, the user will write a text
file containing the list of model variables, the dynamic equations
linking these variables together, the computing tasks to be performed
and the desired graphical or numerical outputs.

A large panel of applied mathematics and computer science techniques
are internally employed by Dynare: multivariate nonlinear solving and
optimization, matrix factorizations, local functional approximation,
Kalman filters and smoothers, MCMC techniques for Bayesian estimation,
graph algorithms, optimal control, @dots{}

Various public bodies (central banks, ministries of economy and
finance, international organisations) and some private financial
institutions use Dynare for performing policy analysis exercises and
as a support tool for forecasting exercises. In the academic world,
Dynare is used for research and teaching purposes in postgraduate
macroeconomics courses.

Dynare is a free software, which means that it can be downloaded free
of charge, that its source code is freely available, and that it can
be used for both non-profit and for-profit purposes. Most of the
source files are covered by the GNU General Public Licence (GPL)
version 3 or later (there are some exceptions to this, see the file
@file{license.txt} in Dynare distribution). It is available for the
Windows, Mac and Linux platforms and is fully documented through a
user guide and a reference manual. Part of Dynare is programmed in
C++, while the rest is written using the
@uref{http://www.mathworks.com/products/matlab/, MATLAB} programming
language.  The latter implies that commercially-available MATLAB
software is required in order to run Dynare. However, as an
alternative to MATLAB, Dynare is also able to run on top of
@uref{http://www.octave.org, GNU Octave} (basically a free clone of
MATLAB): this possibility is particularly interesting for students or
institutions who cannot afford, or do not want to pay for, MATLAB and
are willing to bear the concomitant performance loss.

The development of Dynare is mainly done at
@uref{http://www.cepremap.fr, Cepremap} by a core team of
researchers who devote part of their time to software development.
Currently the development team of Dynare is composed of Stéphane
Adjemian (Université du Maine, Gains and Cepremap), Houtan Bastani
(Cepremap), Michel Juillard (Banque de France), Frédéric Karamé
(Université du Maine, Gains and Cepremap), Junior Maih (Norges Bank),
Ferhat Mihoubi (Université Paris-Est Créteil, Epee and Cepremap), George
Perendia, Johannes Pfeifer (University of Cologne), Marco Ratto (European Commission, Joint Research Centre - JRC)
and Sébastien Villemot (OFCE – Sciences Po).
Increasingly, the developer base is expanding, as tools developed by
researchers outside of Cepremap are integrated into Dynare. Financial
support is provided by Cepremap, Banque de France and DSGE-net (an
international research network for DSGE modeling). The Dynare project
also received funding through the Seventh Framework Programme for
Research (FP7) of the European Commission's Socio-economic Sciences
and Humanities (SSH) Program from October 2008 to September 2011 under
grant agreement SSH-CT-2009-225149.

Interaction between developers and users of Dynare is central to the
project. A @uref{http://www.dynare.org/phpBB3, web forum} is available
for users who have questions about the usage of Dynare or who want to
report bugs. Training sessions are given through the Dynare Summer
School, which is organized every year and is attended by about 40
people. Finally, priorities in terms of future developments and
features to be added are decided in cooperation with the institutions
providing financial support.

@node Documentation sources
@section Documentation sources

The present document is the reference manual for Dynare. It documents
all commands and features in a systematic fashion.

New users should rather begin with Dynare User Guide (@cite{Mancini
(2007)}), distributed with Dynare and also available from the
@uref{http://www.dynare.org,official Dynare web site}.

Other useful sources of information include the
@uref{http://www.dynare.org,Dynare wiki} and the
@uref{http://www.dynare.org/phpBB3, Dynare forums}.

@node Citing Dynare in your research
@section Citing Dynare in your research

If you would like to refer to Dynare in a research article, the
recommended way is to cite the present manual, as follows:

@quotation
Stéphane Adjemian, Houtan Bastani, Michel Juillard, Frédéric Karamé,
Ferhat Mihoubi, George Perendia, Johannes Pfeifer, Marco Ratto and
Sébastien Villemot (2011), ``Dynare: Reference Manual, Version 4,''
@i{Dynare Working Papers}, 1, CEPREMAP
@end quotation

Note that citing the Dynare Reference Manual in your research is a
good way to help the Dynare project.

If you want to give a URL, use the address of the Dynare website:
@uref{http://www.dynare.org}.

@node Installation and configuration
@chapter Installation and configuration

@menu
* Software requirements::
* Installation of Dynare::
* Compiler installation::
* Configuration::
@end menu

@node Software requirements
@section Software requirements

Packaged versions of Dynare are available for Windows XP/Vista/7/8,
@uref{http://www.debian.org,Debian GNU/Linux},
@uref{http://www.ubuntu.com/,Ubuntu} and Mac OS X 10.8 or later.  Dynare should
work on other systems, but some compilation steps are necessary in that case.

In order to run Dynare, you need one of the following:

@itemize

@item
MATLAB version 7.5 (R2007b) or above (MATLAB R2009b 64-bit for Mac OS X);

@item
GNU Octave version 3.6 or above.
@end itemize

Packages of GNU Octave can be downloaded on the
@uref{http://www.dynare.org/download/octave,Dynare website}.

The following optional extensions are also useful to benefit from extra
features, but are in no way required:

@itemize

@item
If under MATLAB: the optimization toolbox, the statistics toolbox, the
control system toolbox;

@item
If under GNU Octave, the following
@uref{http://octave.sourceforge.net/,Octave-Forge} packages: optim,
io, statistics, control.

@item 
Mac OS X Octave users will also need to install
gnuplot if they want graphing capabilities.

@end itemize



@node Installation of Dynare
@section Installation of Dynare

After installation, Dynare can be used in any directory on your
computer. It is best practice to keep your model files in directories
different from the one containing the Dynare toolbox. That way you can
upgrade Dynare and discard the previous version without having to worry
about your own files.

@menu
* On Windows::
* On Debian GNU/Linux and Ubuntu::
* On Mac OS X::
* For other systems::
@end menu

@node On Windows
@subsection On Windows

Execute the automated installer called @file{dynare-4.@var{x}.@var{y}-win.exe}
(where 4.@var{x}.@var{y} is the version number), and follow the instructions. The
default installation directory is @file{c:\dynare\4.@var{x}.@var{y}}.

After installation, this directory will contain several sub-directories,
among which are @file{matlab}, @file{mex} and @file{doc}.

The installer will also add an entry in your Start Menu with a shortcut
to the documentation files and uninstaller.

Note that you can have several versions of Dynare coexisting (for
example in @file{c:\dynare}), as long as you correctly adjust your path
settings (@pxref{Some words of warning}).

@node On Debian GNU/Linux and Ubuntu
@subsection On Debian GNU/Linux and Ubuntu

Please refer to the
@uref{http://www.dynare.org/DynareWiki/InstallOnDebianOrUbuntu,Dynare
Wiki} for detailed instructions.

Dynare will be installed under @file{/usr/lib/dynare}. Documentation will be
under @file{/usr/share/doc/dynare-doc}.

@node On Mac OS X
@subsection On Mac OS X

Execute the automated installer called
@file{dynare-4.@var{x}.@var{y}.pkg} (where
4.@var{x}.@var{y} is the version number), and follow the
instructions. The default installation directory is
@file{/Applications/Dynare/4.@var{x}.@var{y}}.

Please refer to the
@uref{http://www.dynare.org/DynareWiki/InstallOnMacOSX,Dynare Wiki} for
detailed instructions.

After installation, this directory will contain several sub-directories,
among which are @file{matlab}, @file{mex} and @file{doc}.

Note that you can have several versions of Dynare coexisting (for
example in @file{/Applications/Dynare}), as long as you correctly
adjust your path settings (@pxref{Some words of warning}).

@node For other systems
@subsection For other systems

You need to download Dynare source code from the
@uref{http://www.dynare.org,Dynare website} and unpack it somewhere.

Then you will need to recompile the pre-processor and the dynamic
loadable libraries. Please refer to
@uref{https://github.com/DynareTeam/dynare/blob/master/README.md,README.md}.

@node Compiler installation
@section Compiler installation

If you plan to use the @code{use_dll} option of the @code{model}
command, you will need to install the necessary requirements for
compiling MEX files on your machine. 

If you are using MATLAB, please check
@uref{http://www.mathworks.com/support/compilers} for supported compilers for
your MATLAB version on your operating system. After installing your compiler,
select it using @code{mex -setup} in Matlab and clicking on the required compiler.

Octave comes with built-in functionality for compiling mex-files.

@menu
* Prerequisites on Windows::
* Prerequisites on Debian GNU/Linux and Ubuntu::
* Prerequisites on Mac OS X::
@end menu

@node Prerequisites on Windows
@subsection Prerequisites on Windows

If you are using MATLAB under Windows, install a C++ compiler on your machine and configure it with
MATLAB. There are at least two free compilers you can use. First, there is Microsoft's Visual Studio 
Community (@uref{https://www.visualstudio.com/}), which has the largest history of MATLAB support, but 
requires much space on the hard-disk. Second, since MATLAB R2015b, MATLAB supports the MinGW-w64 C/C++ 
Compiler from TDM-GCC. To install this compiler, use the Add-Ons menu of MATLAB. Search for MinGW or 
select it from Features. 

For older version of MATLAB, in particular before R2014a, it may sometimes make sense to use the gcc compiler 
provided by Cygwin. However, integrating it in MATLAB can be quite cumbersome and should be considered as a
legacy option. For details, see
@uref{http://www.dynare.org/DynareWiki/ConfigureMatlabWindowsForMexCompilation,instructions
on the Dynare wiki}. 

@node Prerequisites on Debian GNU/Linux and Ubuntu
@subsection Prerequisites on Debian GNU/Linux and Ubuntu

Users of MATLAB under Linux need to have a working compilation environment installed. If not already present,
it can be installed via @code{apt-get install build-essential}.

Users of Octave under Linux should install the package for MEX file compilation 
(under Debian or Ubuntu, it is called @file{liboctave-dev}).

@node Prerequisites on Mac OS X
@subsection Prerequisites on Mac OS X
If you are using MATLAB under Mac OS X, you should install the latest
version of XCode: see
@uref{http://www.dynare.org/DynareWiki/InstallOnMacOSX,instructions on
the Dynare wiki}.


@node Configuration
@section Configuration

@menu
* For MATLAB::
* For GNU Octave::
* Some words of warning::
@end menu

@node For MATLAB
@subsection For MATLAB

You need to add the @file{matlab} subdirectory of your Dynare
installation to MATLAB path. You have two options for doing that:

@itemize

@item
Using the @code{addpath} command in the MATLAB command window:

Under Windows, assuming that you have installed Dynare in the standard
location, and replacing @code{4.@var{x}.@var{y}} with the correct
version number, type:

@example
addpath c:\dynare\4.@var{x}.@var{y}\matlab
@end example

Under Debian GNU/Linux or Ubuntu, type:

@example
addpath /usr/lib/dynare/matlab
@end example

Under Mac OS X, assuming that you have installed Dynare in the standard
location, and replacing @code{4.@var{x}.@var{y}} with the correct version
number, type:

@example
addpath /Applications/Dynare/4.@var{x}.@var{y}/matlab
@end example

MATLAB will not remember this setting next time you run it, and you
will have to do it again.

@item
Via the menu entries:

Select the ``Set Path'' entry in the ``File'' menu, then click on
``Add Folder@dots{}'', and select the @file{matlab} subdirectory of your
Dynare installation. Note that you @emph{should not} use ``Add with
Subfolders@dots{}''. Apply the settings by clicking on ``Save''. Note that
MATLAB will remember this setting next time you run it.
@end itemize

@node For GNU Octave
@subsection For GNU Octave

You need to add the @file{matlab} subdirectory of your Dynare
installation to Octave path, using the @code{addpath} at the Octave
command prompt.

Under Windows, assuming that you have installed Dynare in the standard
location, and replacing ``4.@var{x}.@var{y}'' with the correct version
number, type:

@example
addpath c:\dynare\4.@var{x}.@var{y}\matlab
@end example

Under Debian GNU/Linux or Ubuntu, there is no need to use the
@code{addpath} command; the packaging does it for you.

Under Mac OS X, assuming that you have installed Dynare in the
standard location, and replacing ``4.@var{x}.@var{y}'' with the correct
version number, type:

@example
addpath /Applications/Dynare/4.@var{x}.@var{y}/matlab
@end example

If you don't want to type this command every time you run Octave, you
can put it in a file called @file{.octaverc} in your home directory
(under Windows this will generally be @file{c:\Documents and
Settings\USERNAME\} while under Mac OS X it is @file{/Users/USERNAME/}).
This file is run by Octave at every startup.

@node Some words of warning
@subsection Some words of warning

You should be very careful about the content of your MATLAB or Octave
path. You can display its content by simply typing @code{path} in the
command window.

The path should normally contain system directories of MATLAB or Octave,
and some subdirectories of your Dynare installation. You have to
manually add the @file{matlab} subdirectory, and Dynare will
automatically add a few other subdirectories at runtime (depending on
your configuration). You must verify that there is no directory coming
from another version of Dynare than the one you are planning to use.

You have to be aware that adding other directories to your path can
potentially create problems if any of your M-files have the same name
as a Dynare file. Your file would then override the Dynare file, making
Dynare unusable.

@node Running Dynare
@chapter Running Dynare

In order to give instructions to Dynare, the user has to write a
@emph{model file} whose filename extension must be @file{.mod}. This
file contains the description of the model and the computing tasks
required by the user. Its contents are described in @ref{The Model file}.

@menu
* Dynare invocation::
* Dynare hooks::
* Understanding Preprocessor Error Messages::
@end menu

@node Dynare invocation
@section Dynare invocation

Once the model file is written, Dynare is invoked using the
@code{dynare} command at the MATLAB or Octave prompt (with the filename
of the @file{.mod} given as argument).

In practice, the handling of the model file is done in two steps: in the
first one, the model and the processing instructions written by the user
in a @emph{model file} are interpreted and the proper MATLAB or GNU
Octave instructions are generated; in the second step, the program
actually runs the computations. Both steps are triggered automatically
by the @code{dynare} command.

@deffn {MATLAB/Octave command} dynare @var{FILENAME}[.mod] [@var{OPTIONS}@dots{}]

@descriptionhead

This command launches Dynare and executes the instructions included in
@file{@var{FILENAME}.mod}.  This user-supplied file contains the model
and the processing instructions, as described in @ref{The Model file}.

@code{dynare} begins by launching the preprocessor on the @file{.mod}
file.  By default (unless @code{use_dll} option has been given to
@code{model}), the preprocessor creates three intermediary files:

@table @file

@item @var{FILENAME}.m
Contains variable declarations, and computing tasks

@item @var{FILENAME}_dynamic.m
@vindex M_.lead_lag_incidence
Contains the dynamic model equations. Note that Dynare might introduce auxiliary equations and variables (@pxref{Auxiliary variables}). Outputs are the residuals of the dynamic model equations in the order the equations were declared and the Jacobian of the dynamic model equations. For higher order approximations also the Hessian and the third-order derivatives are provided. When computing the Jacobian of the dynamic model, the order of the endogenous variables in the columns is stored in @code{M_.lead_lag_incidence}. The rows of this matrix represent time periods: the first row denotes a lagged (time t-1) variable, the second row a contemporaneous (time t) variable, and the third row a leaded (time t+1) variable. The columns of the matrix represent the endogenous variables in their order of declaration. A zero in the matrix means that this endogenous does not appear in the model in this time period. The value in the @code{M_.lead_lag_incidence} matrix corresponds to the column of that variable in the Jacobian of the dynamic model. Example: Let the second declared variable be @code{c} and the @code{(3,2)} entry of @code{M_.lead_lag_incidence} be @code{15}. Then the @code{15}th column of the Jacobian is the derivative with respect to @code{c(+1)}.

@item @var{FILENAME}_static.m
Contains the long run static model equations. Note that Dynare might introduce auxiliary equations and variables (@pxref{Auxiliary variables}). Outputs are the residuals of the static model equations in the order the equations were declared and the Jacobian of the static equations. Entry @code{(i,j)} of the Jacobian represents the derivative of the @code{i}th static model equation with respect to the @code{j}th model variable in declaration order.
@end table

@noindent
These files may be looked at to understand errors reported at the simulation stage.

@code{dynare} will then run the computing tasks by executing @file{@var{FILENAME}.m}.

A few words of warning is warranted here: the filename of the
@file{.mod} file should be chosen in such a way that the generated
@file{.m} files described above do not conflict with @file{.m} files
provided by MATLAB/Octave or by Dynare. Not respecting this rule could
cause crashes or unexpected behaviour. In particular, it means that
the @file{.mod} file cannot be given the name of a MATLAB/Octave or
Dynare command. Under Octave, it also means that the @file{.mod} file
cannot be named @file{test.mod}.

@optionshead

@table @code

@item noclearall
By default, @code{dynare} will issue a @code{clear all} command to
MATLAB (<R2015b) or Octave, thereby deleting all workspace variables and
functions; this option instructs @code{dynare} not to clear the
workspace. Note that starting with Matlab 2015b @code{dynare} only
deletes the global variables and the functions using persistent
variables, in order to benefit from the JIT (Just In Time)
compilation. In this case the option instructs @code{dynare} not to
clear the globals and functions.

@item onlyclearglobals
By default, @code{dynare} will issue a @code{clear all} command to
MATLAB versions before 2015b and to Octave, thereby deleting all workspace variables; this
option instructs @code{dynare} to clear only the global variables
(@i{i.e.} @code{M_}, @code{options_}, @code{oo_},
@code{estim_params_}, @code{bayestopt_}, and @code{dataset_}), leaving
the other variables in the workspace.

@item debug
Instructs the preprocessor to write some debugging information about the
scanning and parsing of the @file{.mod} file

@item notmpterms
Instructs the preprocessor to omit temporary terms in the static and
dynamic files; this generally decreases performance, but is used for
debugging purposes since it makes the static and dynamic files more
readable

@item savemacro[=@var{FILENAME}]
Instructs @code{dynare} to save the intermediary file which is obtained
after macro-processing (@pxref{Macro-processing language}); the saved
output will go in the file specified, or if no file is specified in
@file{@var{FILENAME}-macroexp.mod}

@item onlymacro
Instructs the preprocessor to only perform the macro-processing step,
and stop just after. Mainly useful for debugging purposes or for using
the macro-processor independently of the rest of Dynare toolbox.

@item nolinemacro
Instructs the macro-preprocessor to omit line numbering information in
the intermediary @file{.mod} file created after the macro-processing
step. Useful in conjunction with @code{savemacro} when one wants that to
reuse the intermediary @file{.mod} file, without having it cluttered by
line numbering directives.

@item nolog
Instructs Dynare to no create a logfile of this run in
@file{@var{FILENAME}.log}. The default is to create the logfile.

@item params_derivs_order=0|1|2
When @ref{identification}, @ref{dynare_sensitivity} (with identification), or
@ref{estimation_cmd} are present, this option is used to limit the order of the
derivatives with respect to the parameters that are calculated by the
preprocessor. @code{0} means no derivatives, @code{1} means first derivatives,
and @code{2} means second derivatives. Default: @code{2}

@item nowarn
Suppresses all warnings.

@item warn_uninit
Display a warning for each variable or parameter which is not
initialized. @xref{Parameter initialization}, or
@ref{load_params_and_steady_state} for initialization of parameters.
@xref{Initial and terminal conditions}, or
@ref{load_params_and_steady_state} for initialization of endogenous
and exogenous variables.

@item console
Activate console mode. In addition to the behavior of
@code{nodisplay}, Dynare will not use graphical waitbars for long
computations.

@item nograph
Activate the @code{nograph} option (@pxref{nograph}), so that Dynare will not produce any
graph

@item nointeractive
@anchor{nointeractive}
Instructs Dynare to not request user input.

@item nopathchange
By default Dynare will change Matlab/Octave's path if
@file{dynare/matlab} directory is not on top and if Dynare's routines
are overriden by routines provided in other toolboxes. If one wishes to
override Dynare's routines, the @code{nopathchange} options can be
used. Alternatively, the path can be temporarly modified by the user at
the top of the @file{*.mod} file (using Matlab/Octave's @code{addpath}
command).

@item mingw
Tells Dynare that your MATLAB is configured for compiling MEX files with the
MinGW-compiler from TDM-GCC (@pxref{Compiler installation}). This option is
only available under Windows, and is used in conjunction with
@code{use_dll}.

@item msvc
Tells Dynare that your MATLAB is configured for compiling MEX files with
Microsoft Visual C++ (@pxref{Compiler installation}). This option is
only available under Windows, and is used in conjunction with
@code{use_dll}.

@item cygwin
Tells Dynare that your MATLAB is configured for compiling MEX files with
Cygwin (@pxref{Compiler installation}). This option is only available
under Windows, and is used in conjunction with @code{use_dll}.

@item parallel[=@var{CLUSTER_NAME}]
Tells Dynare to perform computations in parallel. If @var{CLUSTER_NAME}
is passed, Dynare will use the specified cluster to perform parallel
computations. Otherwise, Dynare will use the first cluster specified in
the configuration file. @xref{The Configuration File}, for more
information about the configuration file.

@item conffile=@var{FILENAME}
Specifies the location of the configuration file if it differs from the
default. @xref{The Configuration File}, for more information about the
configuration file and its default location.

@item parallel_slave_open_mode
Instructs Dynare to leave the connection to the slave node open after
computation is complete, closing this connection only when Dynare
finishes processing.

@item parallel_test
Tests the parallel setup specified in the configuration file without
executing the @file{.mod} file. @xref{The Configuration File}, for more
information about the configuration file.

@item -D@var{MACRO_VARIABLE}=@var{MACRO_EXPRESSION}
Defines a macro-variable from the command line (the same effect as using
the Macro directive @code{@@#define} in a model file, @pxref{Macro-processing language}).

@anchor{-I}
@item -I@var{<<path>>}
Defines a path to search for files to be included by the
macroprocessor (using the @ref{@@#include} command). Multiple
@code{-I} flags can be passed on the command line. The paths will be
searched in the order that the @code{-I} flags are passed and the
first matching file will be used. The flags passed here take priority
over those passed to @ref{@@#includepath}.

@item nostrict
Allows Dynare to issue a warning and continue processing when
@enumerate
@item there are more endogenous variables than equations
@item an undeclared symbol is assigned in @code{initval} or @code{endval}
@item exogenous variables were declared but not used in the @code{model} block
@end enumerate

@item fast
Only useful with model option @code{use_dll}. Don't recompile the MEX
files when running again the same model file and the lists of variables
and the equations haven't changed. We use a 32 bit checksum, stored in
@code{<model filename>/checksum}. There is a very small probability that
the preprocessor misses a change in the model. In case of doubt, re-run
without the @code{fast} option.

@item minimal_workspace
Instructs Dynare not to write parameter assignments to parameter names
in the @file{.m} file produced by the preprocessor. This is
potentially useful when running @code{dynare} on a large @file{.mod}
file that runs into workspace size limitations imposed by MATLAB.

@item compute_xrefs
Tells Dynare to compute the equation cross references, writing them to the
output @file{.m} file.
@end table

@outputhead

Depending on the computing tasks requested in the @file{.mod} file,
executing the @code{dynare} command will leave variables containing
results in the workspace available for further processing. More
details are given under the relevant computing tasks.

The @code{M_}, @code{oo_}, and @code{options_} structures are saved in
a file called @file{@var{FILENAME}_results.mat}. If they exist,
@code{estim_params_}, @code{bayestopt_}, @code{dataset_}, @code{oo_recursive_} and
@code{estimation_info} are saved in the same file.

@examplehead

@example
dynare ramst
dynare ramst.mod savemacro
@end example

@end deffn

The output of Dynare is left into three main variables in the
MATLAB/Octave workspace:

@defvr {MATLAB/Octave variable} M_
Structure containing various information about the model.
@end defvr

@defvr {MATLAB/Octave variable} options_
Structure contains the values of the various options used by Dynare
during the computation.
@end defvr

@defvr {MATLAB/Octave variable} oo_
Structure containing the various results of the computations.
@end defvr

@defvr {MATLAB/Octave variable} oo_recursive_
@anchor{oo_recursive_}
Cell array containing the @code{oo_} structures obtained when estimating the model 
for the different samples when performing recursive estimation and forecasting. 
The @code{oo_} structure obtained for the sample ranging to the @math{i}th observation 
is saved in the @math{i}th field. The fields for non-estimated endpoints are empty.
@end defvr


@node Dynare hooks
@section Dynare hooks

It is possible to call pre and post Dynare preprocessor hooks written as MATLAB scripts.
The script @file{@var{MODFILENAME}/hooks/priorprocessing.m} is executed before the
call to Dynare's preprocessor, and  can be used to programmatically transform the mod file
that will be read by the preprocessor. The script @file{@var{MODFILENAME}/hooks/postprocessing.m}
is executed just after the call to Dynare's preprocessor, and can be used to programmatically
transform the files generated by Dynare's preprocessor before actual computations start. The
pre and/or post dynare preprocessor hooks are executed if and only if the aforementioned scripts
are detected in the same folder as the the model file, @file{@var{FILENAME}.mod}.


@node Understanding Preprocessor Error Messages
@section Understanding Preprocessor Error Messages

If the preprocessor runs into an error while processing your
@file{.mod} file, it will issue an error. Due to the way that a parser
works, sometimes these errors can be misleading. Here, we aim to
demystify these error messages.

The preprocessor issues error messages of the form:
@enumerate
@item @code{ERROR: <<file.mod>>: line A, col B: <<error message>>}
@item @code{ERROR: <<file.mod>>: line A, cols B-C: <<error message>>}
@item @code{ERROR: <<file.mod>>: line A, col B - line C, col D: <<error message>>}
@end enumerate
@noindent The first two errors occur on a single line, with error
two spanning multiple columns. Error three spans multiple rows.

Often, the line and column numbers are precise, leading you directly
to the offending syntax. Infrequently however, because of the way the
parser works, this is not the case. The most common example of
misleading line and column numbers (and error message for that matter)
is the case of a missing semicolon, as seen in the following example:
@example
varexo a, b
parameters c, ...;
@end example
@noindent In this case, the parser doesn't know a semicolon is missing at the
end of the @code{varexo} command until it begins parsing the second
line and bumps into the @code{parameters} command. This is because we
allow commands to span multiple lines and, hence, the parser cannot
know that the second line will not have a semicolon on it until it
gets there. Once the parser begins parsing the second line, it
realizes that it has encountered a keyword, @code{parameters}, which
it did not expect. Hence, it throws an error of the form: @code{ERROR:
<<file.mod>>: line 2, cols 0-9: syntax error, unexpected
PARAMETERS}. In this case, you would simply place a semicolon at the
end of line one and the parser would continue processing.

@node The Model file
@chapter The Model file

@menu
* Conventions::
* Variable declarations::
* Expressions::
* Parameter initialization::
* Model declaration::
* Auxiliary variables::
* Initial and terminal conditions::
* Shocks on exogenous variables::
* Other general declarations::
* Steady state::
* Getting information about the model::
* Deterministic simulation::
* Stochastic solution and simulation::
* Estimation::
* Model Comparison::
* Shock Decomposition::
* Calibrated Smoother::
* Forecasting::
* Optimal policy::
* Sensitivity and identification analysis::
* Markov-switching SBVAR::
* Displaying and saving results::
* Macro-processing language::
* Verbatim inclusion::
* Misc commands::
@end menu

@node Conventions
@section Conventions

A model file contains a list of commands and of blocks.  Each command
and each element of a block is terminated by a semicolon
(@code{;}). Blocks are terminated by @code{end;}.

Most Dynare commands have arguments and several accept options,
indicated in parentheses after the command keyword. Several options
are separated by commas.

In the description of Dynare commands, the following conventions are
observed:

@itemize

@item
optional arguments or options are indicated between square brackets:
@samp{[]};

@item
repreated arguments are indicated by ellipses: ``@dots{}'';

@item
mutually exclusive arguments are separated by vertical bars: @samp{|};

@item
@var{INTEGER} indicates an integer number;

@item
@var{INTEGER_VECTOR} indicates a vector of integer numbers separated by spaces,
enclosed by square brackets;

@item
@var{DOUBLE} indicates a double precision number. The following syntaxes
are valid: @code{1.1e3}, @code{1.1E3}, @code{1.1d3}, @code{1.1D3}. In
some places, infinite values @code{Inf} and @code{-Inf} are also allowed;

@item
@var{NUMERICAL_VECTOR} indicates a vector of numbers separated by spaces,
enclosed by square brackets;

@item
@var{EXPRESSION} indicates a mathematical expression valid outside the
model description (@pxref{Expressions});

@item
@var{MODEL_EXPRESSION} indicates a mathematical expression valid in the
model description (@pxref{Expressions} and @ref{Model declaration});

@item
@var{MACRO_EXPRESSION} designates an expression of the macro-processor
(@pxref{Macro expressions});

@item
@var{VARIABLE_NAME} indicates a variable name starting with an
alphabetical character and can't contain: @samp{()+-*/^=!;:@@#.} or
accentuated characters;

@item
@var{PARAMETER_NAME} indicates a parameter name starting with an
alphabetical character and can't contain: @samp{()+-*/^=!;:@@#.} or
accentuated characters;

@item
@var{LATEX_NAME} indicates a valid @LaTeX{} expression in math mode
(not including the dollar signs);

@item
@var{FUNCTION_NAME} indicates a valid MATLAB function name;

@item
@var{FILENAME} indicates a filename valid in the underlying operating
system; it is necessary to put it between quotes when specifying the
extension or if the filename contains a non-alphanumeric character;

@end itemize

@node Variable declarations
@section Variable declarations

While Dynare allows the user to choose their own variable names, there are some restrictions 
to be kept in mind. First, variables and parameters must not have the same name as Dynare commands or
built-in functions. In this respect, Dynare is not case-sensitive. For example, do not use @var{Ln}
or @var{Sigma_e} to name your variable. Not conforming to this rule might yield hard-to-debug
error messages or crashes. Second, to minimize interference with MATLAB or Octave functions that
may be called by Dynare or user-defined steady state files, it is recommended to avoid using the name
of MATLAB functions. In particular when working with steady state files, do not use correctly-spelled greek 
names like @var{alpha}, because there are Matlab functions of the same name. Rather go for @var{alppha} or so.
Lastly, please do not name a variable or parameter @var{i}. This may interfere with the imaginary 
number @var{i} and the index in many loops. Rather, name investment @var{invest}.

Declarations of variables and parameters are made with the following commands:

@deffn Command var @var{VARIABLE_NAME} [$@var{LATEX_NAME}$] [(long_name=@var{QUOTED_STRING}|NAME=@var{QUOTED_STRING}@dots{})]@dots{};
@deffnx Command var (deflator = @var{MODEL_EXPRESSION}) @var{VARIABLE_NAME} [$@var{LATEX_NAME}$] [(long_name=@var{QUOTED_STRING}|NAME=@var{QUOTED_STRING}@dots{})]@dots{};
@deffnx Command var (log_deflator = @var{MODEL_EXPRESSION}) @var{VARIABLE_NAME} [$@var{LATEX_NAME}$] [(long_name=@var{QUOTED_STRING}|NAME=@var{QUOTED_STRING}@dots{})]@dots{};

@descriptionhead

This required command declares the endogenous variables in the
model. @xref{Conventions}, for the syntax of @var{VARIABLE_NAME} and
@var{MODEL_EXPRESSION}. Optionally it is possible to give a @LaTeX{}
name to the variable or, if it is nonstationary, provide information
regarding its deflator.

@code{var} commands can appear several times in the file and Dynare will
concatenate them.

@optionshead

If the model is nonstationary and is to be written as such in the
@code{model} block, Dynare will need the trend deflator for the
appropriate endogenous variables in order to stationarize the model. The
trend deflator must be provided alongside the variables that follow this
trend.

@table @code

@item deflator = @var{MODEL_EXPRESSION}
The expression used to detrend an endogenous variable. All trend
variables, endogenous variables and parameters referenced in
@var{MODEL_EXPRESSION} must already have been declared by the
@code{trend_var}, @code{log_trend_var}, @code{var} and
@code{parameters} commands. The deflator is assumed to be
multiplicative; for an additive deflator, use @code{log_deflator}.

@item log_deflator = @var{MODEL_EXPRESSION}
Same as @code{deflator}, except that the deflator is assumed to be
additive instead of multiplicative (or, to put it otherwise, the
declared variable is equal to the log of a variable with a
multiplicative trend).

@anchor{long_name}
@item long_name = @var{QUOTED_STRING}
This is the long version of the variable name. Its value is stored in
@code{M_.endo_names_long}. In case multiple @code{long_name} options are
provided, the last one will be used. Default: @var{VARIABLE_NAME}

@anchor{partitioning}
@item NAME = @var{QUOTED_STRING}
This is used to create a partitioning of variables. It results in the direct
output in the @file{.m} file analogous to:
@code{M_.endo_partitions.}@var{NAME}@code{ = }@var{QUOTED_STRING}@code{;}.
@end table

@examplehead

@example
var c gnp cva (country=`US', state=`VA')
          cca (country=`US', state=`CA', long_name=`Consumption CA');
var(deflator=A) i b;
var c $C$ (long_name=`Consumption');
@end example

@end deffn

@deffn Command varexo @var{VARIABLE_NAME} [$@var{LATEX_NAME}$] [(long_name=@var{QUOTED_STRING}|NAME=@var{QUOTED_STRING}@dots{})]@dots{};

@descriptionhead

This optional command declares the exogenous variables in the model.
@xref{Conventions}, for the syntax of @var{VARIABLE_NAME}. Optionally it
is possible to give a @LaTeX{} name to the variable.

Exogenous variables are required if the user wants to be able to apply
shocks to her model.

@code{varexo} commands can appear several times in the file and Dynare
will concatenate them.

@optionshead
@table @code
@item long_name = @var{QUOTED_STRING}
Like @ref{long_name} but value stored in @code{M_.exo_names_long}.

@item NAME = @var{QUOTED_STRING}
Like @ref{partitioning} but @var{QUOTED_STRING} stored in
@code{M_.exo_partitions.}@var{NAME}.
@end table

@examplehead

@example
varexo m gov;
@end example

@end deffn

@deffn Command varexo_det @var{VARIABLE_NAME} [$@var{LATEX_NAME}$] [(long_name=@var{QUOTED_STRING}|NAME=@var{QUOTED_STRING}@dots{})]@dots{};

@descriptionhead

This optional command declares exogenous deterministic variables in a
stochastic model. See @ref{Conventions}, for the syntax of
@var{VARIABLE_NAME}. Optionally it is possible to give a @LaTeX{} name
to the variable.

It is possible to mix deterministic and stochastic shocks to build
models where agents know from the start of the simulation about future
exogenous changes. In that case @code{stoch_simul} will compute the
rational expectation solution adding future information to the state
space (nothing is shown in the output of @code{stoch_simul}) and
@code{forecast} will compute a simulation conditional on initial
conditions and future information.

@code{varexo_det} commands can appear several times in the file and
Dynare will concatenate them.

@optionshead
@table @code
@item long_name = @var{QUOTED_STRING}
Like @ref{long_name} but value stored in @code{M_.exo_det_names_long}.

@item NAME = @var{QUOTED_STRING}
Like @ref{partitioning} but @var{QUOTED_STRING} stored in
@code{M_.exo_det_partitions.}@var{NAME}.
@end table

@examplehead

@example

varexo m gov;
varexo_det tau;

@end example

@end deffn

@deffn Command parameters @var{PARAMETER_NAME} [$@var{LATEX_NAME}$] [(long_name=@var{QUOTED_STRING}|NAME=@var{QUOTED_STRING}@dots{})]@dots{};

@descriptionhead

This command declares parameters used in the model, in variable
initialization or in shocks declarations. See @ref{Conventions}, for the
syntax of @var{PARAMETER_NAME}. Optionally it is possible to give a
@LaTeX{} name to the parameter.

The parameters must subsequently be assigned values (@pxref{Parameter
initialization}).

@code{parameters} commands can appear several times in the file and
Dynare will concatenate them.

@optionshead
@table @code
@item long_name = @var{QUOTED_STRING}
Like @ref{long_name} but value stored in @code{M_.param_names_long}.

@item NAME = @var{QUOTED_STRING}
Like @ref{partitioning} but @var{QUOTED_STRING} stored in
@code{M_.param_partitions.}@var{NAME}.
@end table

@examplehead

@example
parameters alpha, bet;
@end example

@end deffn

@deffn Command change_type (var | varexo | varexo_det | parameters) @var{VARIABLE_NAME} | @var{PARAMETER_NAME}@dots{};

@descriptionhead

Changes the types of the specified variables/parameters to another type:
endogenous, exogenous, exogenous deterministic or parameter.

It is important to understand that this command has a global effect on
the @file{.mod} file: the type change is effective after, but also
before, the @code{change_type} command. This command is typically used
when flipping some variables for steady state calibration: typically a
separate model file is used for calibration, which includes the list of
variable declarations with the macro-processor, and flips some variable.

@examplehead

@example
var y, w;
parameters alpha, bet;
@dots{}
change_type(var) alpha, bet;
change_type(parameters) y, w;
@end example

Here, in the whole model file, @code{alpha} and @code{beta} will be
endogenous and @code{y} and @code{w} will be parameters.

@end deffn

@anchor{predetermined_variables}
@deffn Command predetermined_variables @var{VARIABLE_NAME}@dots{};

@descriptionhead

In Dynare, the default convention is that the timing of a variable
reflects when this variable is decided. The typical example is for
capital stock: since the capital stock used at current period is
actually decided at the previous period, then the capital stock entering
the production function is @code{k(-1)}, and the law of motion of
capital must be written:

@example
k = i + (1-delta)*k(-1)
@end example

Put another way, for stock variables, the default in Dynare is to use a
``stock at the end of the period'' concept, instead of a ``stock at the
beginning of the period'' convention.

The @code{predetermined_variables} is used to change that
convention. The endogenous variables declared as predetermined variables
are supposed to be decided one period ahead of all other endogenous
variables. For stock variables, they are supposed to follow a ``stock at
the beginning of the period'' convention.

Note that Dynare internally always uses the ``stock at the end of the period''
concept, even when the model has been entered using the
@code{predetermined_variables}-command. Thus, when plotting,
computing or simulating variables, Dynare will follow the convention to
use variables that are decided in the current period. For example,
when generating impulse response functions for capital, Dynare
will plot @code{k}, which is the capital stock decided upon by
investment today (and which will be used in tomorrow's production function).
This is the reason that capital is shown to be moving on impact, because
it is @code{k} and not the predetermined @code{k(-1)} that is displayed.
It is important to remember that this also affects simulated time
series and output from smoother routines for predetermined variables.
Compared to non-predetermined variables they might otherwise appear
to be falsely shifted to the future by one period.
@examplehead

The following two program snippets are strictly equivalent.

@emph{Using default Dynare timing convention:}

@example
var y, k, i;
@dots{}
model;
y = k(-1)^alpha;
k = i + (1-delta)*k(-1);
@dots{}
end;
@end example

@emph{Using the alternative timing convention:}

@example
var y, k, i;
predetermined_variables k;
@dots{}
model;
y = k^alpha;
k(+1) = i + (1-delta)*k;
@dots{}
end;
@end example

@end deffn

@deffn Command trend_var (growth_factor = @var{MODEL_EXPRESSION}) @var{VARIABLE_NAME} [$@var{LATEX_NAME}$]@dots{};

@descriptionhead

This optional command declares the trend variables in the
model. @xref{Conventions}, for the syntax of @var{MODEL_EXPRESSION}
and @var{VARIABLE_NAME}. Optionally it is possible to give a @LaTeX{}
name to the variable.

The variable is assumed to have a multiplicative growth trend. For an
additive growth trend, use @code{log_trend_var} instead.

Trend variables are required if the user wants to be able to write a
nonstationary model in the @code{model} block. The @code{trend_var}
command must appear before the @code{var} command that references the
trend variable.

@code{trend_var} commands can appear several times in the file and
Dynare will concatenate them.

If the model is nonstationary and is to be written as such in the
@code{model} block, Dynare will need the growth factor of every trend
variable in order to stationarize the model. The growth factor must be
provided within the declaration of the trend variable, using the
@code{growth_factor} keyword. All endogenous variables and
parameters referenced in @var{MODEL_EXPRESSION} must already have been
declared by the @code{var} and @code{parameters} commands.

@examplehead

@example
trend_var (growth_factor=gA) A;
@end example

@end deffn

@deffn Command log_trend_var (log_growth_factor = @var{MODEL_EXPRESSION}) @var{VARIABLE_NAME} [$@var{LATEX_NAME}$]@dots{};

@descriptionhead

Same as @code{trend_var}, except that the variable is supposed to have
an additive trend (or, to put it otherwise, to be equal to the log of
a variable with a multiplicative trend).

@end deffn


@node Expressions
@section Expressions

Dynare distinguishes between two types of mathematical expressions:
those that are used to describe the model, and those that are used
outside the model block (@i{e.g.} for initializing parameters or
variables, or as command options). In this manual, those two types of
expressions are respectively denoted by @var{MODEL_EXPRESSION} and
@var{EXPRESSION}.

Unlike MATLAB or Octave expressions, Dynare expressions are necessarily
scalar ones: they cannot contain matrices or evaluate to
matrices@footnote{Note that arbitrary MATLAB or Octave expressions can
be put in a @file{.mod} file, but those expressions have to be on
separate lines, generally at the end of the file for post-processing
purposes. They are not interpreted by Dynare, and are simply passed on
unmodified to MATLAB or Octave. Those constructions are not addresses in
this section.}.

Expressions can be constructed using integers (@var{INTEGER}), floating
point numbers (@var{DOUBLE}), parameter names (@var{PARAMETER_NAME}),
variable names (@var{VARIABLE_NAME}), operators and functions.

The following special constants are also accepted in some contexts:

@deffn Constant inf
Represents infinity.
@end deffn

@deffn Constant nan
``Not a number'': represents an undefined or unrepresentable value.
@end deffn

@menu
* Parameters and variables::
* Operators::
* Functions::
* A few words of warning in stochastic context::
@end menu

@node Parameters and variables
@subsection Parameters and variables

Parameters and variables can be introduced in expressions by simply
typing their names. The semantics of parameters and variables is quite
different whether they are used inside or outside the model block.

@menu
* Inside the model::
* Outside the model::
@end menu

@node Inside the model
@subsubsection Inside the model

Parameters used inside the model refer to the value given through
parameter initialization (@pxref{Parameter initialization}) or
@code{homotopy_setup} when doing a simulation, or are the estimated
variables when doing an estimation.

Variables used in a @var{MODEL_EXPRESSION} denote @emph{current period}
values when neither a lead or a lag is given. A lead or a lag can be
given by enclosing an integer between parenthesis just after the
variable name: a positive integer means a lead, a negative one means a
lag. Leads or lags of more than one period are allowed. For example, if
@code{c} is an endogenous variable, then @code{c(+1)} is the variable
one period ahead, and @code{c(-2)} is the variable two periods before.

When specifying the leads and lags of endogenous variables, it is
important to respect the following convention: in Dynare, the timing of
a variable reflects when that variable is decided. A control variable ---
which by definition is decided in the current period --- must have no
lead. A predetermined variable --- which by definition has been decided in
a previous period --- must have a lag. A consequence of this is that all
stock variables must use the ``stock at the end of the period''
convention. Please refer to @cite{Mancini-Griffoli (2007)} for more
details and concrete examples.

Leads and lags are primarily used for endogenous variables, but can be
used for exogenous variables. They have no effect on parameters and are
forbidden for local model variables (@pxref{Model declaration}).

@node Outside the model
@subsubsection Outside the model

When used in an expression outside the model block, a parameter or a
variable simply refers to the last value given to that variable. More
precisely, for a parameter it refers to the value given in the
corresponding parameter initialization (@pxref{Parameter
initialization}); for an endogenous or exogenous variable, it refers to
the value given in the most recent @code{initval} or @code{endval} block.

@node Operators
@subsection Operators

The following operators are allowed in both @var{MODEL_EXPRESSION} and
@var{EXPRESSION}:

@itemize

@item
binary arithmetic operators: @code{+}, @code{-}, @code{*}, @code{/}, @code{^}

@item
unary arithmetic operators: @code{+}, @code{-}

@item
binary comparison operators (which evaluate to either @code{0} or
@code{1}): @code{<}, @code{>}, @code{<=}, @code{>=}, @code{==},
@code{!=}

Note that these operators are differentiable everywhere except on a
line of the 2-dimensional real plane. However for facilitating
convergence of Newton-type methods, Dynare assumes that, at the points
of non-differentiability, the partial derivatives of these operators
with respect to both arguments is equal to @math{0} (since this is the
value of the partial derivatives everywhere else).
@end itemize

The following special operators are accepted in @var{MODEL_EXPRESSION}
(but not in @var{EXPRESSION}):

@deffn Operator STEADY_STATE (@var{MODEL_EXPRESSION})
This operator is used to take the value of the enclosed expression at
the steady state. A typical usage is in the Taylor rule, where you may
want to use the value of GDP at steady state to compute the output gap.
@end deffn

@anchor{expectation}
@deffn Operator EXPECTATION (@var{INTEGER}) (@var{MODEL_EXPRESSION})
This operator is used to take the expectation of some expression using
a different information set than the information available at current
period. For example, @code{EXPECTATION(-1)(x(+1))} is equal to the
expected value of variable @code{x} at next period, using the
information set available at the previous period. @xref{Auxiliary
variables}, for an explanation of how this operator is handled
internally and how this affects the output.
@end deffn

@node Functions
@subsection Functions

@menu
* Built-in Functions::
* External Functions::
@end menu

@node Built-in Functions
@subsubsection Built-in Functions

The following standard functions are supported internally for both
@var{MODEL_EXPRESSION} and @var{EXPRESSION}:

@defun exp (@var{x})
Natural exponential.
@end defun

@defun log (@var{x})
@defunx ln (@var{x})
Natural logarithm.
@end defun

@defun log10 (@var{x})
Base 10 logarithm.
@end defun

@defun sqrt (@var{x})
Square root.
@end defun

@defun abs (@var{x})
Absolute value.

Note that this function is not differentiable at @math{x=0}. However,
for facilitating convergence of Newton-type methods, Dynare assumes
that the derivative at @math{x=0} is equal to @math{0} (this
assumption comes from the observation that the derivative of
@math{abs(x)} is equal to @math{sign(x)} for @math{x\neq 0} and from
the convention for the derivative of @math{sign(x)} at @math{x=0}).
@end defun

@defun sign (@var{x})
Signum function.

Note that this function is not differentiable at @math{x=0}. However,
for facilitating convergence of Newton-type methods, Dynare assumes
that the derivative at @math{x=0} is equal to @math{0} (this assumption
comes from the observation that both the right- and left-derivatives
at this point exist and are equal to @math{0}).
@end defun

@defun sin (@var{x})
@defunx cos (@var{x})
@defunx tan (@var{x})
@defunx asin (@var{x})
@defunx acos (@var{x})
@defunx atan (@var{x})
Trigonometric functions.
@end defun

@defun max (@var{a}, @var{b})
@defunx min (@var{a}, @var{b})
Maximum and minimum of two reals.

Note that these functions are differentiable everywhere except on a
line of the 2-dimensional real plane defined by @math{a=b}. However
for facilitating convergence of Newton-type methods, Dynare assumes
that, at the points of non-differentiability, the partial derivative
of these functions with respect to the first (resp. the second)
argument is equal to @math{1} (resp. to @math{0}) (@i{i.e.} the
derivatives at the kink are equal to the derivatives observed on the
half-plane where the function is equal to its first argument).
@end defun

@defun normcdf (@var{x})
@defunx normcdf (@var{x}, @var{mu}, @var{sigma})
Gaussian cumulative density function, with mean @var{mu} and standard
deviation @var{sigma}. Note that @code{normcdf(@var{x})} is equivalent
to @code{normcdf(@var{x},0,1)}.
@end defun

@defun normpdf (@var{x})
@defunx normpdf (@var{x}, @var{mu}, @var{sigma})
Gaussian probability density function, with mean @var{mu} and standard
deviation @var{sigma}. Note that @code{normpdf(@var{x})} is equivalent
to @code{normpdf(@var{x},0,1)}.
@end defun

@defun erf (@var{x})
Gauss error function.
@end defun

@node External Functions
@subsubsection External Functions

Any other user-defined (or built-in) MATLAB or Octave function may be
used in both a @var{MODEL_EXPRESSION} and an @var{EXPRESSION}, provided
that this function has a scalar argument as a return value.

To use an external function in a @var{MODEL_EXPRESSION}, one must
declare the function using the @code{external_function} statement. This
is not necessary for external functions used in an @var{EXPRESSION}.

@deffn Command external_function (@var{OPTIONS}@dots{});

@descriptionhead

This command declares the external functions used in the model block. It
is required for every unique function used in the model block.

@code{external_function} commands can appear several times in the file
and must come before the model block.

@optionshead

@table @code

@item name = @var{NAME}
The name of the function, which must also be the name of the M-/MEX file
implementing it. This option is mandatory.

@item nargs = @var{INTEGER}
The number of arguments of the function. If this option is not provided,
Dynare assumes @code{nargs = 1}.

@item first_deriv_provided [= @var{NAME}]
If @var{NAME} is provided, this tells Dynare that the Jacobian is
provided as the only output of the M-/MEX file given as the option
argument. If @var{NAME} is not provided, this tells Dynare that the
M-/MEX file specified by the argument passed to @code{name} returns the
Jacobian as its second output argument.

@item second_deriv_provided [= @var{NAME}]
If @var{NAME} is provided, this tells Dynare that the Hessian is
provided as the only output of the M-/MEX file given as the option
argument. If @var{NAME} is not provided, this tells Dynare that the
M-/MEX file specified by the argument passed to @code{name} returns the
Hessian as its third output argument. NB: This option can only be used
if the @code{first_deriv_provided} option is used in the same
@code{external_function} command.
@end table

@examplehead

@example
external_function(name = funcname);
external_function(name = otherfuncname, nargs = 2,
                  first_deriv_provided, second_deriv_provided);
external_function(name = yetotherfuncname, nargs = 3,
                  first_deriv_provided = funcname_deriv);
@end example

@end deffn

@node A few words of warning in stochastic context
@subsection A few words of warning in stochastic context

The use of the following functions and operators is strongly
discouraged in a stochastic context: @code{max}, @code{min},
@code{abs}, @code{sign}, @code{<}, @code{>}, @code{<=}, @code{>=},
@code{==}, @code{!=}.

The reason is that the local approximation used by @code{stoch_simul}
or @code{estimation} will by nature ignore the non-linearities
introduced by these functions if the steady state is away from the
kink. And, if the steady state is exactly at the kink, then the
approximation will be bogus because the derivative of these functions
at the kink is bogus (as explained in the respective documentations of
these functions and operators).

Note that @code{extended_path} is not affected by this problem,
because it does not rely on a local approximation of the model.

@node Parameter initialization
@section Parameter initialization

When using Dynare for computing simulations, it is necessary to
calibrate the parameters of the model. This is done through parameter
initialization.

The syntax is the following:

@example
@var{PARAMETER_NAME} = @var{EXPRESSION};
@end example

Here is an example of calibration:

@example
parameters alpha, bet;

beta = 0.99;
alpha = 0.36;
A = 1-alpha*beta;
@end example

Internally, the parameter values are stored in @code{M_.params}:

@defvr {MATLAB/Octave variable} M_.params

Contains the values of model parameters. The parameters are in the
order that was used in the @code{parameters} command.

@end defvr


@node Model declaration
@section Model declaration

The model is declared inside a @code{model} block:

@deffn Block model ;
@deffnx Block model (@var{OPTIONS}@dots{});

@descriptionhead

The equations of the model are written in a block delimited by
@code{model} and @code{end} keywords.

There must be as many equations as there are endogenous variables in the
model, except when computing the unconstrained optimal policy with
@code{ramsey_model}, @code{ramsey_policy} or @code{discretionary_policy}.

The syntax of equations must follow the conventions for
@var{MODEL_EXPRESSION} as described in @ref{Expressions}. Each equation
must be terminated by a semicolon (@samp{;}). A normal equation looks
like:
@example
@var{MODEL_EXPRESSION} = @var{MODEL_EXPRESSION};
@end example

When the equations are written in homogenous form, it is possible to
omit the @samp{=0} part and write only the left hand side of the
equation. A homogenous equation looks like:
@example
@var{MODEL_EXPRESSION};
@end example

Inside the model block, Dynare allows the creation of @emph{model-local
variables}, which constitute a simple way to share a common expression
between several equations. The syntax consists of a pound sign
(@code{#}) followed by the name of the new model local variable (which
must @strong{not} be declared as in @ref{Variable declarations}), an equal
sign, and the expression for which this new variable will stand. Later
on, every time this variable appears in the model, Dynare will
substitute it by the expression assigned to the variable. Note that the
scope of this variable is restricted to the model block; it cannot be
used outside. A model local variable declaration looks like:
@example
# @var{VARIABLE_NAME} = @var{MODEL_EXPRESSION};
@end example

It is possible to tag equations written in the model block. A tag can serve
different purposes by allowing the user to attach arbitrary informations to each
equation and to recover them at runtime. For instance, it is possible to name the
equations with a @code{name}-tag, using a syntax like:
@example
mode;
    ...
    [name = 'Budget constraint']
    c + k = k^theta*A;
    ...
end;
@end example
Here, @code{name} is the keyword indicating that the tag names the equation. If an equation 
of the model is tagged with a name, the @code{resid} command
will display the name of the equations (which may be more informative than the
equation numbers) in addition to the equation number. Several tags for one equation can be separated using a comma. 
@example
mode;
    ...
   [name='Taylor rule',mcp = 'r > -1.94478']
   r = rho*r(-1) + (1-rho)*(gpi*Infl+gy*YGap) + e;
    ...
end;
@end example

More information on tags is available on the @uref{http://www.dynare.org/DynareWiki/EquationsTags, DynareWiki
wiki}.


@optionshead

@table @code

@item linear
Declares the model as being linear. It spares oneself from having to
declare initial values for computing the steady state of a stationary
linear model. This option can't be used with non-linear models, it will
NOT trigger linearization of the model.

@item use_dll
@anchor{use_dll}
Instructs the preprocessor to create dynamic loadable libraries (DLL)
containing the model equations and derivatives, instead of writing those
in M-files. You need a working compilation environment, @i{i.e.}
a working @code{mex} command (see @ref{Compiler installation} for more
details). On MATLAB for Windows, you will need to also pass the compiler name at 
the command line. Using this option can result in faster simulations or
estimations, at the expense of some initial compilation
time.@footnote{In particular, for big models, the compilation step can
be very time-consuming, and use of this option may be counter-productive
in those cases.}

@item block
@anchor{block}
Perform the block decomposition of the model, and exploit it in
computations (steady-state, deterministic simulation,
stochastic simulation with first order approximation and estimation). See
@uref{http://www.dynare.org/DynareWiki/FastDeterministicSimulationAndSteadyStateComputation,Dynare
wiki} for details on the algorithms used in deterministic simulation and steady-state computation.

@item bytecode
@anchor{bytecode}
Instead of M-files, use a bytecode representation of the model, @i{i.e.}
a binary file containing a compact representation of all the equations.

@item cutoff = @var{DOUBLE}
Threshold under which a jacobian element is considered as null during
the model normalization. Only available with option
@code{block}. Default: @code{1e-15}

@item mfs = @var{INTEGER}
Controls the handling of minimum feedback set of endogenous
variables. Only available with option @code{block}. Possible values:

@table @code

@item 0
All the endogenous variables are considered as feedback variables (Default).

@item 1
The endogenous variables assigned to equation naturally normalized
(@i{i.e.} of the form @math{x=f(Y)} where @math{x} does not appear in
@math{Y}) are potentially recursive variables. All the other variables
are forced to belong to the set of feedback variables.

@item 2
In addition of variables with @code{mfs = 1} the endogenous variables
related to linear equations which could be normalized are potential
recursive variables. All the other variables are forced to belong to
the set of feedback variables.

@item 3
In addition of variables with @code{mfs = 2} the endogenous variables
related to non-linear equations which could be normalized are
potential recursive variables. All the other variables are forced to
belong to the set of feedback variables.
@end table

@item no_static
Don't create the static model file. This can be useful for models which
don't have a steady state.

@item differentiate_forward_vars
@itemx differentiate_forward_vars = ( @var{VARIABLE_NAME} [@var{VARIABLE_NAME} @dots{}] )
Tells Dynare to create a new auxiliary variable for each endogenous
variable that appears with a lead, such that the new variable is the
time differentiate of the original one. More precisely, if the model
contains @code{x(+1)}, then a variable @code{AUX_DIFF_VAR} will be
created such that @code{AUX_DIFF_VAR=x-x(-1)}, and @code{x(+1)} will
be replaced with @code{x+AUX_DIFF_VAR(+1)}.

The transformation is applied to all endogenous variables with a lead
if the option is given without a list of variables. If there is a
list, the transformation is restricted to endogenous with a lead that
also appear in the list.

This option can useful for some deterministic simulations where
convergence is hard to obtain. Bad values for terminal conditions in
the case of very persistent dynamics or permanent shocks can hinder
correct solutions or any convergence. The new differentiated variables
have obvious zero terminal conditions (if the terminal condition is a
steady state) and this in many cases helps convergence of simulations.

@item parallel_local_files = ( @var{FILENAME} [, @var{FILENAME}]@dots{} )
Declares a list of extra files that should be transferred to slave
nodes when doing a parallel computation (@pxref{Parallel Configuration}).

@end table

@customhead{Example 1: elementary RBC model}

@example
var c k;
varexo x;
parameters aa alph bet delt gam;

model;
c =  - k + aa*x*k(-1)^alph + (1-delt)*k(-1);
c^(-gam) = (aa*alph*x(+1)*k^(alph-1) + 1 - delt)*c(+1)^(-gam)/(1+bet);
end;
@end example

@customhead{Example 2: use of model local variables}

The following program:

@example
model;
# gamma = 1 - 1/sigma;
u1 = c1^gamma/gamma;
u2 = c2^gamma/gamma;
end;
@end example

@noindent
@dots{}is formally equivalent to:

@example
model;
u1 = c1^(1-1/sigma)/(1-1/sigma);
u2 = c2^(1-1/sigma)/(1-1/sigma);
end;
@end example

@customhead{Example 3: a linear model}

@example
model(linear);
x = a*x(-1)+b*y(+1)+e_x;
y = d*y(-1)+e_y;
end;
@end example

@end deffn

Dynare has the ability to output the original list of model equations
to a @LaTeX{} file, using the @code{write_latex_original_model}
command, the list of transformed model equations using the
@code{write_latex_dynamic_model} command, and the list of static model
equations using the @code{write_latex_static_model} command.

@anchor{write_latex_original_model}

@deffn Command write_latex_original_model ;

@descriptionhead

This command creates two @LaTeX{} files: one containing the model as
defined in the model block and one containing the @LaTeX{} document
header information.

If your @file{.mod} file is @file{@var{FILENAME}.mod}, then Dynare
will create a file called @file{@var{FILENAME}_original.tex}, which
includes a file called @file{@var{FILENAME}_original_content.tex}
(also created by Dynare) containing the list of all the original model
equations.

If @LaTeX{} names were given for variables and parameters
(@pxref{Variable declarations}), then those will be used; otherwise,
the plain text names will be used.

Time subscripts (@code{t}, @code{t+1}, @code{t-1}, @dots{}) will be
appended to the variable names, as @LaTeX{} subscripts.

Compiling the @TeX{} file requires the following @LaTeX{} packages:
@code{geometry}, @code{fullpage}, @code{breqn}.

@end deffn

@anchor{write_latex_dynamic_model}

@deffn Command write_latex_dynamic_model ;
@deffnx Command write_latex_dynamic_model (@var{OPTIONS}) ;

@descriptionhead

This command creates two @LaTeX{} files: one containing the dynamic
model and one containing the @LaTeX{} document header information.

If your @file{.mod} file is @file{@var{FILENAME}.mod}, then Dynare
will create a file called @file{@var{FILENAME}_dynamic.tex}, which
includes a file called @file{@var{FILENAME}_dynamic_content.tex}
(also created by Dynare) containing the list of all the dynamic model
equations.

If @LaTeX{} names were given for variables and parameters
(@pxref{Variable declarations}), then those will be used; otherwise,
the plain text names will be used.

Time subscripts (@code{t}, @code{t+1}, @code{t-1}, @dots{}) will be
appended to the variable names, as @LaTeX{} subscripts.

Note that the model written in the @TeX{} file will differ from the
model declared by the user in the following dimensions:

@itemize

@item
the timing convention of predetermined variables
(@pxref{predetermined_variables}) will have been changed to the
default Dynare timing convention; in other words, variables declared
as predetermined will be lagged on period back,

@item
the expectation operators (@pxref{expectation}) will have
been removed, replaced by auxiliary variables and new equations as
explained in the documentation of the operator,

@item
endogenous variables with leads or lags greater or equal than two will
have been removed, replaced by new auxiliary variables and equations,

@item
for a stochastic model, exogenous variables with leads or lags will
also have been replaced by new auxiliary variables and equations.
@end itemize

For the required @LaTeX{} packages, @pxref{write_latex_original_model}.

@optionshead

@table @code

@item write_equation_tags
Write the equation tags in the @LaTeX{} output. NB: the equation tags will be
interpreted with @LaTeX{} markups.

@end table

@end deffn

@deffn Command write_latex_static_model ;

@descriptionhead

This command creates two @LaTeX{} files: one containing the static
model and one containing the @LaTeX{} document header information.

If your @file{.mod} file is @file{@var{FILENAME}.mod}, then Dynare
will create a file called @file{@var{FILENAME}_static.tex}, which
includes a file called @file{@var{FILENAME}_static_content.tex} (also
created by Dynare) containing the list of all the steady state model
equations.

If @LaTeX{} names were given for variables and parameters
(@pxref{Variable declarations}), then those will be used; otherwise,
the plain text names will be used.

Note that the model written in the @TeX{} file will differ from the
model declared by the user in the some dimensions
(@pxref{write_latex_dynamic_model} for details).

Also note that this command will not output the contents of the
optional @code{steady_state_model} block (@pxref{steady_state_model});
it will rather output a static version (@i{i.e.} without leads and
lags) of the dynamic model declared in the @code{model} block.

For the required @LaTeX{} packages, @pxref{write_latex_original_model}.

@end deffn

@node Auxiliary variables
@section Auxiliary variables

The model which is solved internally by Dynare is not exactly the
model declared by the user. In some cases, Dynare will introduce
auxiliary endogenous variables---along with corresponding auxiliary
equations---which will appear in the final output.

The main transformation concerns leads and lags. Dynare will perform a
transformation of the model so that there is only one lead and one lag
on endogenous variables and, in the case of a stochastic model, no leads/lags on
exogenous variables.

This transformation is achieved by the creation of auxiliary
variables and corresponding equations. For example, if @code{x(+2)}
exists in the model, Dynare will create one auxiliary variable
@code{AUX_ENDO_LEAD = x(+1)}, and replace @code{x(+2)} by
@code{AUX_ENDO_LEAD(+1)}.

A similar transformation is done for lags greater than 2 on endogenous
(auxiliary variables will have a name beginning with
@code{AUX_ENDO_LAG}), and for exogenous with leads and lags (auxiliary
variables will have a name beginning with @code{AUX_EXO_LEAD} or
@code{AUX_EXO_LAG} respectively).

Another transformation is done for the @code{EXPECTATION}
operator. For each occurrence of this operator, Dynare creates an
auxiliary variable defined by a new equation, and replaces the
expectation operator by a reference to the new auxiliary variable. For
example, the expression @code{EXPECTATION(-1)(x(+1))} is replaced by
@code{AUX_EXPECT_LAG_1(-1)}, and the new auxiliary variable is
declared as @code{AUX_EXPECT_LAG_1 = x(+2)}.

Auxiliary variables are also introduced by the preprocessor for the
@code{ramsey_model} and @code{ramsey_policy} commands. In this case, they are used to represent the Lagrange
multipliers when first order conditions of the Ramsey problem are computed.
The new variables take the form @code{MULT_@var{i}}, where @var{i} represents
the constraint with which the multiplier is associated (counted from the
order of declaration in the model block).

The last type of auxiliary variables is introduced by the
@code{differentiate_forward_vars} option of the @code{model} block.
The new variables take the form @code{AUX_DIFF_FWRD_@var{i}}, and are
equal to @code{x-x(-1)} for some endogenous variable @code{x}.

Once created, all auxiliary variables are included in the set of
endogenous variables. The output of decision rules (see below) is such
that auxiliary variable names are replaced by the original variables
they refer to.

@vindex M_.orig_endo_nbr
@vindex M_.endo_nbr
The number of endogenous variables before the creation of auxiliary
variables is stored in @code{M_.orig_endo_nbr}, and the number of
endogenous variables after the creation of auxiliary variables is
stored in @code{M_.endo_nbr}.

See @uref{http://www.dynare.org/DynareWiki/AuxiliaryVariables,Dynare
Wiki} for more technical details on auxiliary variables.

@node Initial and terminal conditions
@section Initial and terminal conditions

For most simulation exercises, it is necessary to provide initial (and
possibly terminal) conditions. It is also necessary to provide initial
guess values for non-linear solvers. This section describes the
statements used for those purposes.

In many contexts (deterministic or stochastic), it is necessary to
compute the steady state of a non-linear model: @code{initval} then
specifies numerical initial values for the non-linear solver. The
command @code{resid} can be used to compute the equation residuals for
the given initial values.

Used in perfect foresight mode, the types of forward-looking models for
which Dynare was designed require both initial and terminal
conditions. Most often these initial and terminal conditions are
static equilibria, but not necessarily.

One typical application is to consider an economy at the equilibrium at time 0,
trigger a shock in first period, and study the trajectory of return to
the initial equilibrium. To do that, one needs @code{initval} and
@code{shocks} (@pxref{Shocks on exogenous variables}.

Another one is to study, how an economy, starting from arbitrary
initial conditions at time 0 converges toward equilibrium. 
In this case models, the command @code{histval} permits to specify different 
historical initial values for variables with lags for the 
periods before the beginning of the simulation. Due to the design of Dynare, 
in this case @code{initval} is used to specify the terminal conditions.


@deffn Block initval ;
@deffnx Block initval (@var{OPTIONS}@dots{});

@descriptionhead

The @code{initval} block has two main purposes: providing guess values 
for non-linear solvers in the context of perfect foresight simulations 
and providing guess values for steady state computations in both perfect 
foresight and stochastic simulations. Depending on the presence of @code{histval} 
and @code{endval}-blocks it is also used for declaring the initial and 
terminal conditions in a perfect foresight simulation exercise. 
Because of this interaction of the meaning of an @code{initval}-block 
with the presence of @code{histval} and @code{endval}-blocks in perfect foresight 
simulations, it is strongly recommended to check that the 
constructed @code{oo_.endo_simul} and @code{oo_.exo_simul} variables 
contain the desired values after running @code{perfect_foresight_setup} 
and before running @code{perfect_foresight_solver}. In the presence of leads 
and lags, these subfields of the results structure will store the historical 
values for the lags in the first 
column/row and the terminal values for the leads in the last column/row.

The @code{initval} block is terminated by @code{end;}, and contains lines of the
form:
@example
@var{VARIABLE_NAME} = @var{EXPRESSION};
@end example

@customhead{In a deterministic (@i{i.e.} perfect foresight) model}

First, it will fill both the @code{oo_.endo_simul} and @code{oo_.exo_simul} variables 
storing the endogenous and exogenous variables with the values provided by this block. 
If there are no other blocks present, it will therefore provide the initial and 
terminal conditions for all the endogenous and exogenous variables, because it 
will also fill the last column/row of these matrices. For the intermediate simulation periods 
it thereby provides the starting values for the solver.
In the presence of a @code{histval} block (and therefore absence of an @code{endval}-block), 
this @code{histval} block will provide/overwrite the historical values for the state variables (lags) by 
setting the first column/row of @code{oo_.endo_simul} and @code{oo_.exo_simul}. 
This implies that the @code{initval}-block in the presence of @code{histval} only sets the terminal values 
for the variables with leads and provides initial values for the perfect foresight solver.


Because of these various functions of @code{initval} it is often necessary to provide values for all the
endogenous variables in an @code{initval} block. Initial and terminal conditions are strictly 
necessary for lagged/leaded variables, while feasible starting values are required for the solver. 
It is important to be aware that if some variables, endogenous or exogenous, are not mentioned in the
@code{initval} block, a zero value is assumed. It is particularly important to keep 
this in mind when specifying exogenous variables using @code{varexo} that are not allowed 
to take on the value of zero, like @i{e.g.} TFP.

Note that if the @code{initval} block is immediately followed by a
@code{steady} command, its semantics are slightly changed. 
The @code{steady} command will compute the steady state of the model for all the 
endogenous variables, assuming that exogenous variables are kept constant at the value 
declared in the @code{initval} block. These steady state values conditional on 
the declared exogenous variables are then written into @code{oo_.endo_simul} and take up the 
potential roles as historical and terminal conditions as well 
as starting values for the solver. An @code{initval} block followed by @code{steady}
is therefore formally equivalent to an @code{initval} block with the specified values
for the exogenous variables, and the endogenous variables set to the associated steady state values
conditional on the exogenous variables.

@customhead{In a stochastic model}

The main purpose of @code{initval} is to provide initial guess values
for the non-linear solver in the steady state computation. Note that
if the @code{initval} block is not followed by @code{steady}, the
steady state computation will still be triggered by subsequent
commands (@code{stoch_simul}, @code{estimation}@dots{}).

It is not necessary to declare @code{0} as initial value for exogenous
stochastic variables, since it is the only possible value.

The subsequently computed steady state (not the initial values, use
@ref{histval} for this) will be used as the initial condition at all
the periods preceeding the first simulation period for the three
possible types of simulations in stochastic mode:

@itemize

@item
@ref{stoch_simul}, if the @code{periods} option is specified

@item
@ref{forecast} as the initial point at which the forecasts are computed

@item
@ref{conditional_forecast} as the initial point at which the conditional forecasts are computed
@end itemize

To start simulations at a particular set of starting values that are not a computed steady state, use @ref{histval}.

@optionshead

@table @code

@item all_values_required
@anchor{all_values_required}
Issues an error and stops processing the @file{.mod} file if there is at least
one endogenous or exogenous variable that has not been set in the @code{initval}
block.
@end table

@examplehead

@example
initval;
c = 1.2;
k = 12;
x = 1;
end;

steady;
@end example

@end deffn

@deffn Block endval ;
@deffnx Block endval (@var{OPTIONS}@dots{});

@descriptionhead

This block is terminated by @code{end;}, and contains lines of the
form:
@example
@var{VARIABLE_NAME} = @var{EXPRESSION};
@end example

The @code{endval} block makes only sense in a deterministic model and cannot 
be used together with @code{histval}. Similar to the @code{initval} command, 
it will fill both the @code{oo_.endo_simul} and @code{oo_.exo_simul} variables 
storing the endogenous and exogenous variables with the values provided by this block. 
If no @code{initval}-block is present, it will fill the whole matrices, therefore 
providing the initial and terminal conditions for all the endogenous and exogenous 
variables, because it will also fill the first and last column/row of these matrices. Due to
also filling the intermediate simulation periods it will provide the starting values for the solver as well.

If an @code{initval}-block is present, @code{initval} will provide the historical 
values for the variables (if there are states/lags), while @code{endval} will fill 
the remainder of the matrices, thereby still providing i) the terminal conditions 
for variables entering the model with a lead and ii) the initial guess values 
for all endogenous variables at all the simulation dates for the perfect foresight solver.

Note that if some variables, endogenous or exogenous, are NOT mentioned in the
@code{endval} block, the value assumed is that of the last
@code{initval} block or @code{steady} command (if present). Therefore, 
in contrast to @code{initval}, omitted variables are not automatically assumed to be 0 
in this case. Again, it is strongly recommended to check the 
constructed @code{oo_.endo_simul} and @code{oo_.exo_simul} variables 
after running @code{perfect_foresight_setup} and before running @code{perfect_foresight_solver}
to see whether the desired outcome has been achieved. 

Like @code{initval}, if the @code{endval} block is immediately followed by a
@code{steady} command, its semantics are slightly changed. 
The @code{steady} command will compute the steady state of the model for all 
the endogenous variables, assuming that exogenous variables are kept constant 
to the value declared in the @code{endval} block. These steady state values 
conditional on the declared exogenous variables are then written into @code{oo_.endo_simul} 
and therefore take up the potential roles as historical and terminal conditions 
as well as starting values for the solver. An @code{endval} block followed by @code{steady}
is therefore formally equivalent to an @code{endval} block with the specified values
for the exogenous variables, and the endogenous variables set to the associated steady state values.

@optionshead

@table @code

@item all_values_required
@xref{all_values_required}.
@end table

@examplehead

@example
var c k;
varexo x;
@dots{}
initval;
c = 1.2;
k = 12;
x = 1;
end;

steady;

endval;
c = 2;
k = 20;
x = 2;
end;

steady;
@end example

The initial equilibrium is computed by @code{steady} conditional on @code{x=1},
and the terminal one conditional on @code{x=2}. The @code{initval}-block sets 
the initial condition for @code{k}, while the @code{endval}-block sets the terminal
condition for @code{c}. The starting values for the perfect foresight solver are 
given by the @code{endval}-block. A detailed explanation follows below the next example.

@examplehead

@example
var c k;
varexo x;
@dots{}
model;
c + k - aa*x*k(-1)^alph - (1-delt)*k(-1);
c^(-gam) - (1+bet)^(-1)*(aa*alph*x(+1)*k^(alph-1) + 1 - delt)*c(+1)^(-gam);
end;

initval;
k = 12;
end;

endval;
c = 2;
x = 1.1;
end;
simul(periods=200);

@end example

In this example, the problem is finding the optimal path for consumption and
capital for the periods @math{t=1} to @math{T=200}, given the path of the exogenous
technology level @code{x}. @code{c} is a forward looking variable and the
exogenous variable @code{x} appears with a lead in the expected return of
physical capital, so we need terminal conditions for them, while @code{k} is a
purely backward-looking (state) variable, so we need an initial condition for
it.

Setting @code{x=1.1} in the @code{endval}-block without a @code{shocks}-block implies that technology
is at @math{1.1} in @math{t=1} and stays there forever, because @code{endval}
is filling all entries of @code{oo_.endo_simul} and @code{oo_.exo_simul} except 
for the very first one, which stores the initial conditions and was set to @math{0} by the @code{initval}-block when not 
explicitly specifying a value for it. 

Because the law of motion for capital is backward-looking, we need an initial
condition for @code{k} at time @math{0}. Due to the presence of @code{endval}, this cannot be 
done via a @code{histval}-block, but rather must be specified in the @code{initval}-block.
Similarly, because the Euler equation is forward-looking, we need a
terminal condition for @code{c} at @math{t=201}, which is specified in the
@code{endval}-block. 

As can be seen, it is not necessary to specify @code{c} and @code{x} in the @code{initval}-block and
@code{k} in the @code{endval}-block, because they have no impact on the results. Due to 
the optimization problem in the first period being to choose @code{c,k}
at @math{t=1} given the predetermined capital stock @code{k} inherited from @math{t=0} as
well as the current and future values for technology @code{x}, the values for
@code{c} and @code{x} at time @math{t=0} play no role. The same applies to the choice of
@code{c,k} at time @math{t=200}, which does not depend on @code{k} at @math{t=201}. As
the Euler equation shows, that choice only depends on current capital as
well as future consumption @code{c} and technology @code{x}, but not on
future capital @code{k}. The intuitive reason is that those variables are
the consequence of optimization problems taking place in at periods @math{t=0}
and @math{t=201}, respectively, which are not modeled here.

@examplehead

@example
initval;
c = 1.2;
k = 12;
x = 1;
end;

endval;
c = 2;
k = 20;
x = 1.1;
end;
@end example

In this example, initial conditions for the forward-looking variables @code{x}
and @code{c} are provided, together with a terminal condition for the backward-looking
variable @code{k}. As shown in the previous example, these values will not affect the simulation 
results. Dynare simply takes them as given and basically assumes that there were realizations
of exogenous variables and states that make those choices
equilibrium values (basically initial/terminal conditions
at the unspecified time periods @math{t<0} and @math{t>201}).
 
The above example suggests another way of looking at the use of @code{steady}
after @code{initval} and @code{endval}. Instead of saying that the
implicit unspecified conditions before and after the simulation range
have to fit the initial/terminal conditions of the endogenous variables
in those blocks, @code{steady} specifies that those conditions at @math{t<0} and
@math{t>201} are equal to being at the steady state given the exogenous
variables in the @code{initval} and @code{endval}-blocks. The
endogenous variables at @math{t=0} and @math{t=201} are then set to the corresponding steady state
equilibrium values.
 
The fact that @code{c} at @math{t=0} and @code{k} at @math{t=201} specified in
@code{initval} and @code{endval} are taken as given has an important
implication for plotting the simulated vector for the endogenous
variables, @i{i.e.} the rows of @code{oo_.endo_simul}: this vector will
also contain the initial and terminal
conditions and thus is 202 periods long in the example. When you specify
arbitrary values for the initial and terminal conditions for forward- and
backward-looking variables, respectively, these values can be very far
away from the endogenously determined values at @math{t=1} and @math{t=200}. While the
values at @math{t=0} and @math{t=201} are unrelated to the dynamics for @math{0<t<201}, they
may result in strange-looking large jumps. In the example above,
consumption will display a large jump from @math{t=0} to @math{t=1} and capital will
jump from @math{t=200} to @math{t=201} when using @ref{rplot} or manually plotting @code{oo_.endo_val}.

@end deffn

@deffn Block histval ;
@deffnx Block histval (@var{OPTIONS}@dots{});
@anchor{histval}
@descriptionhead

@customhead{In a deterministic perfect foresight context}

In models with lags on more than one period, the @code{histval} block
permits to specify different historical initial values for different
periods of the state variables. In this case, the @code{initval}-block takes over the role of specifying 
terminal conditions and starting values for the solver. Note that the @code{histval} block does not 
take non-state variables.   

This block is terminated by @code{end;}, and contains lines of the
form:
@example
@var{VARIABLE_NAME}(@var{INTEGER}) = @var{EXPRESSION};
@end example

@var{EXPRESSION} is any valid expression returning a numerical value
and can contain already initialized variable names.

By convention in Dynare, period 1 is the first period of the
simulation. Going backward in time, the first period before the start
of the simulation is period @code{0}, then period @code{-1}, and so on.

State variables not initialized in the @code{histval} block are assumed to
have a value of zero at period 0 and before. Note that @code{histval}
cannot be followed by @code{steady}.

@examplehead
@example
model;
x=1.5*x(-1)-0.6*x(-2)+epsilon;
log(c)=0.5*x+0.5*log(c(+1));
end;

histval;
x(0)=-1;
x(-1)=0.2;
end;

initval;
c=1;
x=1;
end;
@end example

In this example, @code{histval} is used to set the historical conditions for the two lags
of the endogenous variable @code{x}, stored in the first column of @code{oo_.endo_simul}. 
The @code{initval} block is used to set the terminal condition for the forward looking variable @code{c},
stored in the last column of @code{oo_.endo_simul}. Moreover, the @code{initval} block defines
the starting values for the perfect foresight solver for both endogenous variables @code{c} and @code{x}.

@customhead{In a stochastic simulation context}

In the context of stochastic simulations, @code{histval} allows setting
the starting point of those simulations in the state space. As for the case of
perfect foresight simulations, all not explicitly specified variables are set to 0.
Moreover, as only states enter the recursive policy functions, all values specified for control variables will be ignored. This can be used

@itemize

@item
in @ref{stoch_simul}, if the @code{periods} option is specified. Note that this
only affects the starting point for the simulation, but not for the impulse
response functions. When using the @ref{loglinear} option, the
@code{histval}-block nevertheless takes the unlogged starting values.

@item
in @ref{forecast} as the initial point at which the forecasts are computed. When using the @ref{loglinear} option, 
the @code{histval}-block nevertheless takes the unlogged starting values.

@item
in @ref{conditional_forecast} for a calibrated model as the initial point at which the conditional forecasts are computed.
When using the @ref{loglinear} option, the @code{histval}-block nevertheless takes the unlogged starting values.

@item 
in @ref{Ramsey} policy, where it also specifies the values of the endogenous states at 
which the objective function of the planner is computed. Note that the initial values 
of the Lagrange multipliers associated with the planner's problem cannot be set
(@pxref{planner_objective_value}).

@end itemize

@optionshead

@table @code

@item all_values_required
@xref{all_values_required}.
@end table


@examplehead

@example
var x y;
varexo e;

model;
x = y(-1)^alpha*y(-2)^(1-alpha)+e;
@dots{}
end;

initval;
x = 1;
y = 1;
e = 0.5;
end;

steady;

histval;
y(0) = 1.1;
y(-1) = 0.9;
end;

stoch_simul(periods=100);
@end example

@end deffn

@deffn Command resid ;

This command will display the residuals of the static equations of the
model, using the values given for the endogenous in the last
@code{initval} or @code{endval} block (or the steady state file if you
provided one, @pxref{Steady state}).

@end deffn


@deffn Command initval_file (filename = @var{FILENAME});

@descriptionhead

In a deterministic setup, this command is used to specify a path for
all endogenous and exogenous variables. The length of these paths must
be equal to the number of simulation periods, plus the number of leads
and the number of lags of the model (for example, with 50 simulation
periods, in a model with 2 lags and 1 lead, the paths must have a
length of 53). Note that these paths cover two different things:

@itemize

@item
the constraints of the problem, which are given by the path for
exogenous and the initial and terminal values for endogenous

@item
the initial guess for the non-linear solver, which is given by the
path for endogenous variables for the simulation periods (excluding
initial and terminal conditions)
@end itemize

The command accepts three file formats:

@itemize

@item
M-file (extension @file{.m}): for each endogenous and exogenous
variable, the file must contain a row or column vector of the same name. Their length must be @code{periods+M_.maximum_lag+M_.maximum_lead} 

@item
MAT-file (extension @file{.mat}): same as for M-files.

@item
Excel file (extension @file{.xls} or @file{.xlsx}): for each endogenous and
exogenous, the file must contain a column of the same name. NB: Octave only
supports the @file{.xlsx} file extension and must have the
@uref{http://octave.sourceforge.net/io/,io} package installed (easily done via octave by typing `@code{pkg install -forge io}').
@end itemize

@customhead{Warning}

The extension must be omitted in the command argument. Dynare will
automatically figure out the extension and select the appropriate file
type.

@end deffn

@deffn Command histval_file (filename = @var{FILENAME});

This command is equivalent to @code{histval}, except that it reads its input
from a file.

This command is typically used in conjunction with @code{smoother2histval}.

@end deffn

@node Shocks on exogenous variables
@section Shocks on exogenous variables

In a deterministic context, when one wants to study the transition of
one equilibrium position to another, it is equivalent to analyze the
consequences of a permanent shock and this in done in Dynare through
the proper use of @code{initval} and @code{endval}.

Another typical experiment is to study the effects of a temporary
shock after which the system goes back to the original equilibrium (if
the model is stable@dots{}). A temporary shock is a temporary change of
value of one or several exogenous variables in the model. Temporary
shocks are specified with the command @code{shocks}.

In a stochastic framework, the exogenous variables take random values
in each period. In Dynare, these random values follow a normal
distribution with zero mean, but it belongs to the user to specify the
variability of these shocks. The non-zero elements of the matrix of
variance-covariance of the shocks can be entered with the @code{shocks}
command. Or, the entire matrix can be directly entered with
@code{Sigma_e} (this use is however deprecated).

If the variance of an exogenous variable is set to zero, this variable
will appear in the report on policy and transition functions, but
isn't used in the computation of moments and of Impulse Response
Functions. Setting a variance to zero is an easy way of removing an
exogenous shock.

Note that, by default, if there are several @code{shocks} or @code{mshocks}
blocks in the same @file{.mod} file, then they are cumulative: all the shocks
declared in all the blocks are considered; however, if a @code{shocks} or
@code{mshocks} block is declared with the @code{overwrite} option, then it
replaces all the previous @code{shocks} and @code{mshocks} blocks.

@deffn Block shocks ;
@deffnx Block shocks (overwrite) ;

See above for the meaning of the @code{overwrite} option.

@customhead{In deterministic context}

For deterministic simulations, the @code{shocks} block specifies
temporary changes in the value of exogenous variables. For
permanent shocks, use an @code{endval} block.

The block should contain one or more occurrences of the following
group of three lines:

@example
var @var{VARIABLE_NAME};
periods @var{INTEGER}[:@var{INTEGER}] [[,] @var{INTEGER}[:@var{INTEGER}]]@dots{};
values @var{DOUBLE} | (@var{EXPRESSION})  [[,] @var{DOUBLE} | (@var{EXPRESSION}) ]@dots{};
@end example

It is possible to specify shocks which last several periods and which can
vary over time. The @code{periods} keyword accepts a list of
several dates or date ranges, which must be matched by as many shock values
in the @code{values} keyword. Note that a range in the
@code{periods} keyword can be matched by only one value in the
@code{values} keyword. If @code{values} represents a scalar, the same
value applies to the whole range. If @code{values} represents a vector,
it must have as many elements as there are periods in the range.

Note that shock values are not restricted to numerical constants:
arbitrary expressions are also allowed, but you have to enclose them
inside parentheses.

Here is an example:

@example
shocks;
var e;
periods 1;
values 0.5;
var u;
periods 4:5;
values 0;
var v;
periods 4:5 6 7:9;
values 1 1.1 0.9;
var w;
periods 1 2;
values (1+p) (exp(z));
end;
@end example

A second example with a vector of values:

@example
xx = [1.2; 1.3; 1];

shocks;
var e;
periods 1:3;
values (xx);
end;
@end example


@customhead{In stochastic context}

For stochastic simulations, the @code{shocks} block specifies the non
zero elements of the covariance matrix of the shocks of exogenous
variables.

You can use the following types of entries in the block:

@table @code

@item var @var{VARIABLE_NAME}; stderr @var{EXPRESSION};
Specifies the standard error of a variable.

@item var @var{VARIABLE_NAME} = @var{EXPRESSION};
Specifies the variance of a variable.

@item var @var{VARIABLE_NAME}, @var{VARIABLE_NAME} = @var{EXPRESSION};
Specifies the covariance of two variables.

@item corr @var{VARIABLE_NAME}, @var{VARIABLE_NAME} = @var{EXPRESSION};
Specifies the correlation of two variables.

@end table

In an estimation context, it is also possible to specify variances and
covariances on endogenous variables: in that case, these values are interpreted
as the calibration of the measurement errors on these variables. This requires
the @code{varobs} command to be specified before the @code{shocks} block.

Here is an example:

@example
shocks;
var e = 0.000081;
var u; stderr 0.009;
corr e, u = 0.8;
var v, w = 2;
end;
@end example

@customhead{Mixing deterministic and stochastic shocks}

It is possible to mix deterministic and stochastic shocks to build
models where agents know from the start of the simulation about future
exogenous changes. In that case @code{stoch_simul} will compute the
rational expectation solution adding future information to the state
space (nothing is shown in the output of @code{stoch_simul}) and
@code{forecast} will compute a simulation conditional on initial
conditions and future information.

Here is an example:

@example
varexo_det tau;
varexo e;

@dots{}

shocks;
var e; stderr 0.01;
var tau;
periods 1:9;
values -0.15;
end;

stoch_simul(irf=0);

forecast;
@end example

@end deffn


@deffn Block mshocks ;
@deffnx Block mshocks (overwrite) ;

The purpose of this block is similar to that of the @code{shocks}
block for deterministic shocks, except that the numeric values given
will be interpreted in a multiplicative way. For example, if a value
of @code{1.05} is given as shock value for some exogenous at some
date, it means 5% above its steady state value (as given by the last
@code{initval} or @code{endval} block).

The syntax is the same than @code{shocks} in a deterministic context.

This command is only meaningful in two situations:

@itemize

@item
on exogenous variables with a non-zero steady state, in a deterministic setup,

@item
on deterministic exogenous variables with a non-zero steady state, in
a stochastic setup.
@end itemize

See above for the meaning of the @code{overwrite} option.

@end deffn

@defvr {Special variable} Sigma_e

@customhead{Warning}

@strong{The use of this special variable is deprecated and is strongly
discouraged.} You should use a @code{shocks} block instead.

@descriptionhead

This special variable specifies directly the covariance matrix of the
stochastic shocks, as an upper (or lower) triangular matrix. Dynare
builds the corresponding symmetric matrix. Each row of the triangular
matrix, except the last one, must be terminated by a semi-colon
@code{;}. For a given element, an arbitrary @var{EXPRESSION} is
allowed (instead of a simple constant), but in that case you need to
enclose the expression in parentheses. @emph{The order of the
covariances in the matrix is the same as the one used in the
@code{varexo} declaration.}

@examplehead

@example

varexo u, e;
@dots{}
Sigma_e = [ 0.81 (phi*0.9*0.009);
            0.000081];
@end example

This sets the variance of @code{u} to 0.81, the variance of @code{e}
to 0.000081, and the correlation between @code{e} and @code{u} to
@code{phi}.

@end defvr

@node Other general declarations
@section Other general declarations

@deffn {Command} dsample @var{INTEGER} [@var{INTEGER}];
Reduces the number of periods considered in subsequent output commands.
@end deffn

@deffn {Command} periods @var{INTEGER};

@descriptionhead

This command is now deprecated (but will still work for older model files). It
is not necessary when no simulation is performed and is replaced by an option
@code{periods} in @code{perfect_foresight_setup}, @code{simul} and
@code{stoch_simul}.

This command sets the number of periods in the simulation. The periods
are numbered from @code{1} to @var{INTEGER}. In perfect foresight
simulations, it is assumed that all future events are perfectly known
at the beginning of period @code{1}.

@examplehead

@example
periods 100;
@end example

@end deffn

@node Steady state
@section Steady state

There are two ways of computing the steady state (@i{i.e.} the static
equilibrium) of a model. The first way is to let Dynare compute the
steady state using a nonlinear Newton-type solver; this should work
for most models, and is relatively simple to use. The second way is to
give more guidance to Dynare, using your knowledge of the model, by
providing it with a ``steady state file''.

@menu
* Finding the steady state with Dynare nonlinear solver::
* Using a steady state file::
* Replace some equations during steady state computations::
@end menu

@node Finding the steady state with Dynare nonlinear solver
@subsection Finding the steady state with Dynare nonlinear solver

@deffn Command steady ;
@deffnx Command steady (@var{OPTIONS}@dots{});

@descriptionhead

This command computes the steady state of a model using a nonlinear
Newton-type solver and displays it. When a steady state file is used @code{steady} displays the steady state and checks that it is a solution of the static model.

More precisely, it computes the equilibrium value of the endogenous
variables for the value of the exogenous variables specified in the
previous @code{initval} or @code{endval} block.

@code{steady} uses an iterative procedure and takes as initial guess
the value of the endogenous variables set in the previous
@code{initval} or @code{endval} block.

For complicated models, finding good numerical initial values for the
endogenous variables is the trickiest part of finding the equilibrium
of that model. Often, it is better to start with a smaller model and
add new variables one by one.

@optionshead

@table @code

@item maxit = @var{INTEGER}
Determines the maximum number of iterations used in the non-linear solver. The
default value of @code{maxit} is 50. 

@item tolf = @var{DOUBLE} 
Convergence criterion for termination based on the function value. Iteration will cease when the residuals are smaller
than @code{tolf}. Default: @code{eps^(1/3)}

@item solve_algo = @var{INTEGER}
@anchor{solve_algo}
Determines the non-linear solver to use. Possible values for the option are:

@table @code

@item 0
Use @code{fsolve} (under MATLAB, only available if you have the
Optimization Toolbox; always available under Octave)

@item 1
Use Dynare's own nonlinear equation solver (a Newton-like algorithm with
line-search)

@item 2
Splits the model into recursive blocks and solves each block in turn
using the same solver as value @code{1}

@item 3
Use Chris Sims' solver

@item 4
Splits the model into recursive blocks and solves each block in turn
using a trust-region solver with autoscaling.

@item 5
Newton algorithm with a sparse Gaussian elimination (SPE) (requires
@code{bytecode} option, @pxref{Model declaration})

@item 6
Newton algorithm with a sparse LU solver at each iteration (requires
@code{bytecode} and/or @code{block} option, @pxref{Model declaration})

@item 7
Newton algorithm with a Generalized Minimal Residual (GMRES) solver at
each iteration (requires @code{bytecode} and/or @code{block} option,
@pxref{Model declaration}; not available under Octave)

@item 8
Newton algorithm with a Stabilized Bi-Conjugate Gradient (BICGSTAB)
solver at each iteration (requires @code{bytecode} and/or @code{block}
option, @pxref{Model declaration})

@item 9
Trust-region algorithm on the entire model.

@item 10
Levenberg-Marquardt mixed compleproblem (LMMCP) solver
(@cite{Kanzow and Petra 2004})

@item 11
PATH mixed complementarity problem solver of @cite{Ferris and Munson (1999)}. The complementarity 
conditions are specified with an @code{mcp} equation tag, @pxref{lmmcp}. Dynare only provides the interface
for using the solver. Due to licence restrictions, you have to download the solver's most current version yourself
from @url{http://pages.cs.wisc.edu/~ferris/path.html} and place it in Matlab's search path.

@end table

@noindent
Default value is @code{4}.

@item homotopy_mode = @var{INTEGER}
Use a homotopy (or divide-and-conquer) technique to solve for the
steady state. If you use this option, you must specify a
@code{homotopy_setup} block. This option can take three possible
values:


@table @code

@item 1
In this mode, all the parameters are changed simultaneously, and the
distance between the boundaries for each parameter is divided in as
many intervals as there are steps (as defined by @code{homotopy_steps}
option); the problem is solves as many times as there are steps.

@item 2
Same as mode @code{1}, except that only one parameter is changed at a
time; the problem is solved as many times as steps times number of
parameters.

@item 3
Dynare tries first the most extreme values. If it fails to compute the
steady state, the interval between initial and desired values is
divided by two for all parameters. Every time that it is impossible to
find a steady state, the previous interval is divided by two. When it
succeeds to find a steady state, the previous interval is multiplied
by two. In that last case @code{homotopy_steps} contains the maximum
number of computations attempted before giving up.
@end table

@item homotopy_steps = @var{INTEGER}
Defines the number of steps when performing a homotopy. See
@code{homotopy_mode} option for more details.


@item homotopy_force_continue = @var{INTEGER}
This option controls what happens when homotopy fails.

@table @code

@item 0
@code{steady} fails with an error message

@item 1
@code{steady} keeps the values of the last homotopy step that was
successful and continues. BE CAREFUL: parameters and/or exogenous
variables are NOT at the value expected by the user
@end table

@noindent
Default is @code{0}.

@item nocheck
Don't check the steady state values when they are provided explicitly either by a steady state file or a @code{steady_state_model} block. This is useful for models with unit roots as, in this case, the steady state is not unique or doesn't exist.

@item markowitz = @var{DOUBLE}
Value of the Markowitz criterion, used to select the pivot. Only used
when @code{solve_algo = 5}. Default: @code{0.5}.

@end table

@examplehead

@xref{Initial and terminal conditions}.

@end deffn

After computation, the steady state is available in the following
variable:

@defvr {MATLAB/Octave variable} oo_.steady_state

Contains the computed steady state.

Endogenous variables are ordered in order of declaration used in
@code{var} command (which is also the order used in @code{M_.endo_names}).

@end defvr

@deffn Block homotopy_setup ;

@descriptionhead

This block is used to declare initial and final values when using
a homotopy method. It is used in conjunction with the option
@code{homotopy_mode} of the @code{steady} command.

The idea of homotopy (also called divide-and-conquer by some authors)
is to subdivide the problem of finding the steady state into smaller
problems. It assumes that you know how to compute the steady state for
a given set of parameters, and it helps you finding the steady state
for another set of parameters, by incrementally moving from one to
another set of parameters.

The purpose of the @code{homotopy_setup} block is to declare the final
(and possibly also the initial) values for the parameters or exogenous
that will be changed during the homotopy. It should contain lines of
the form:

@example
@var{VARIABLE_NAME}, @var{EXPRESSION}, @var{EXPRESSION};
@end example

This syntax specifies the initial and final values of a given
parameter/exogenous.

There is an alternative syntax:
@example
@var{VARIABLE_NAME}, @var{EXPRESSION};
@end example

Here only the final value is specified for a given
parameter/exogenous; the initial value is taken from the preceeding
@code{initval} block.

A necessary condition for a successful homotopy is that Dynare must be
able to solve the steady state for the initial parameters/exogenous
without additional help (using the guess values given in the
@code{initval} block).

If the homotopy fails, a possible solution is to increase the number
of steps (given in @code{homotopy_steps} option of @code{steady}).

@examplehead

In the following example, Dynare will first compute the steady state
for the initial values (@code{gam=0.5} and @code{x=1}), and then
subdivide the problem into 50 smaller problems to find the steady
state for the final values (@code{gam=2} and @code{x=2}).

@example
var c k;
varexo x;

parameters alph gam delt bet aa;
alph=0.5;
delt=0.02;
aa=0.5;
bet=0.05;

model;
c + k - aa*x*k(-1)^alph - (1-delt)*k(-1);
c^(-gam) - (1+bet)^(-1)*(aa*alph*x(+1)*k^(alph-1) + 1 - delt)*c(+1)^(-gam);
end;

initval;
x = 1;
k = ((delt+bet)/(aa*x*alph))^(1/(alph-1));
c = aa*x*k^alph-delt*k;
end;

homotopy_setup;
gam, 0.5, 2;
x, 2;
end;

steady(homotopy_mode = 1, homotopy_steps = 50);
@end example

@end deffn

@node Using a steady state file
@subsection Using a steady state file

If you know how to compute the steady state for your model, you can
provide a MATLAB/Octave function doing the computation instead of
using @code{steady}. Again, there are two options for doing that:

@itemize

@item
The easiest way is to write a @code{steady_state_model} block, which
is described below in more details. See also @file{fs2000.mod} in the
@file{examples} directory for an example.

The steady state file generated by Dynare will be called
@file{@var{FILENAME}_steadystate2.m}.

@item
You can write the corresponding MATLAB function by hand. If your
MOD-file is called @file{@var{FILENAME}.mod}, the steady state file
must be called @file{@var{FILENAME}_steadystate.m}. See
@file{NK_baseline_steadystate.m} in the @file{examples} directory for
an example. This option gives a bit more flexibility, at the expense
of a heavier programming burden and a lesser efficiency.

@end itemize

Note that both files allow to update parameters in each call of
the function. This allows for example to calibrate a model to a labor
supply of 0.2 in steady state by setting the labor disutility parameter
to a corresponding value (see @file{NK_baseline_steadystate.m} in the
@file{examples} directory). They can also be used in estimation
where some parameter may be a function of an estimated parameter
and needs to be updated for every parameter draw. For example, one might
 want to set the capital utilization cost parameter as a function
of the discount rate to ensure that capacity utilization is 1 in steady
state. Treating both parameters as independent or not updating one as
a function of the other would lead to wrong results. But this also means
that care is required. Do not accidentally overwrite your parameters
with new values as it will lead to wrong results.

@anchor{steady_state_model}
@deffn Block steady_state_model ;

@descriptionhead

When the analytical solution of the model is known, this command can
be used to help Dynare find the steady state in a more efficient and
reliable way, especially during estimation where the steady state has
to be recomputed for every point in the parameter space.

Each line of this block consists of a variable (either an endogenous,
a temporary variable or a parameter) which is assigned an expression
(which can contain parameters, exogenous at the steady state, or any
endogenous or temporary variable already declared above). Each line
therefore looks like:

@example
@var{VARIABLE_NAME} = @var{EXPRESSION};
@end example

Note that it is also possible to assign several variables at the same
time, if the main function in the right hand side is a MATLAB/Octave
function returning several arguments:

@example
[ @var{VARIABLE_NAME}, @var{VARIABLE_NAME}@dots{} ] = @var{EXPRESSION};
@end example

Dynare will automatically generate a steady state file (of the form
@file{@var{FILENAME}_steadystate2.m}) using the information provided in
this block.

@customhead{Steady state file for deterministic models}

@code{steady_state_model} block works also with deterministic
models. An @code{initval} block and, when necessary, an @code{endval}
block, is used to set the value of the exogenous variables. Each
@code{initval} or @code{endval} block must be followed by @code{steady}
to execute the function created by @code{steady_state_model} and set the
initial, respectively terminal, steady state.

@examplehead

@example
var m P c e W R k d n l gy_obs gp_obs y dA;
varexo e_a e_m;

parameters alp bet gam mst rho psi del;

@dots{}
// parameter calibration, (dynamic) model declaration, shock calibration@dots{}
@dots{}

steady_state_model;
  dA = exp(gam);
  gst = 1/dA; // A temporary variable
  m = mst;

  // Three other temporary variables
  khst = ( (1-gst*bet*(1-del)) / (alp*gst^alp*bet) )^(1/(alp-1));
  xist = ( ((khst*gst)^alp - (1-gst*(1-del))*khst)/mst )^(-1);
  nust = psi*mst^2/( (1-alp)*(1-psi)*bet*gst^alp*khst^alp );

  n  = xist/(nust+xist);
  P  = xist + nust;
  k  = khst*n;

  l  = psi*mst*n/( (1-psi)*(1-n) );
  c  = mst/P;
  d  = l - mst + 1;
  y  = k^alp*n^(1-alp)*gst^alp;
  R  = mst/bet;

  // You can use MATLAB functions which return several arguments
  [W, e] = my_function(l, n);

  gp_obs = m/dA;
  gy_obs = dA;
end;

steady;
@end example

@end deffn

@anchor{equation_tag_for_conditional_steady_state}
@node Replace some equations during steady state computations
@subsection Replace some equations during steady state computations

When there is no steady state file, Dynare computes the steady state
by solving the static model, @i{i.e.} the model from the @file{.mod}
file from which leads and lags have been removed.

In some specific cases, one may want to have more control over the way
this static model is created. Dynare therefore offers the possibility
to explicitly give the form of equations that should be in the static
model.

More precisely, if an equation is prepended by a @code{[static]} tag,
then it will appear in the static model used for steady state
computation, but that equation will not be used for other
computations. For every equation tagged in this way, you must tag
another equation with @code{[dynamic]}: that equation will not be used
for steady state computation, but will be used for other computations.

This functionality can be useful on models with a unit root, where
there is an infinity of steady states. An equation (tagged
@code{[dynamic]}) would give the law of motion of the nonstationary
variable (like a random walk). To pin down one specific steady state,
an equation tagged @code{[static]} would affect a constant value to
the nonstationary variable.

@examplehead

This is a trivial example with two endogenous variables. The second equation
takes a different form in the static model.

@example
var c k;
varexo x;

@dots{}

model;
c + k - aa*x*k(-1)^alph - (1-delt)*k(-1);
[dynamic] c^(-gam) - (1+bet)^(-1)*(aa*alph*x(+1)*k^(alph-1) + 1 - delt)*c(+1)^(-gam);
[static] k = ((delt+bet)/(x*aa*alph))^(1/(alph-1));
end;
@end example


@node Getting information about the model
@section Getting information about the model

@deffn Command check ;
@deffnx Command check (solve_algo = @var{INTEGER}) ;
@anchor{check}

@descriptionhead

Computes the eigenvalues of the model linearized around the values
specified by the last @code{initval}, @code{endval} or @code{steady}
statement. Generally, the eigenvalues are only meaningful if the
linearization is done around a steady state of the model. It is a
device for local analysis in the neighborhood of this steady state.

A necessary condition for the uniqueness of a stable equilibrium in
the neighborhood of the steady state is that there are as many
eigenvalues larger than one in modulus as there are forward looking
variables in the system. An additional rank condition requires that
the square submatrix of the right Schur vectors corresponding to the
forward looking variables (jumpers) and to the explosive eigenvalues
must have full rank.

@optionshead

@table @code

@item solve_algo = @var{INTEGER}
@xref{solve_algo}, for the possible values and their meaning.

@item qz_zero_threshold = @var{DOUBLE}
@anchor{qz_zero_threshold}
Value used to test if a generalized eigenvalue is 0/0 in the generalized
Schur decomposition  (in which case  the model  does not admit  a unique
solution). Default: @code{1e-6}.

@end table

@outputhead

@code{check} returns the eigenvalues in the global variable
@code{oo_.dr.eigval}.

@end deffn

@defvr {MATLAB/Octave variable} oo_.dr.eigval
Contains the eigenvalues of the model, as computed by the @code{check}
command.
@end defvr


@deffn Command model_diagnostics ;

This command performs various sanity checks on the model, and prints a
message if a problem is detected (missing variables at current period,
invalid steady state, singular Jacobian of static model).

@end deffn


@deffn Command model_info ;
@deffnx Command model_info (@var{OPTIONS}@dots{});

@descriptionhead

This command provides information about:

@itemize

@item
the normalization of the model: an endogenous variable is attributed
to each equation of the model;

@item
the block structure of the model: for each block model_info indicates
its type, the equations number and endogenous variables belonging to
this block.

@end itemize

This command can only be used in conjunction with the @code{block}
option of the @code{model} block.

There are five different types of blocks depending on the simulation
method used:

@table @samp

@item EVALUATE FORWARD
In this case the block contains only equations where endogenous
variable attributed to the equation appears currently on the left hand
side and where no forward looking endogenous variables appear. The
block has the form: @math{y_{j,t} = f_j(y_t, y_{t-1}, \ldots, y_{t-k})}.

@item EVALUATE BACKWARD
The block contains only equations where endogenous variable attributed
to the equation appears currently on the left hand side and where no
backward looking endogenous variables appear. The block has the form:
@math{y_{j,t} = f_j(y_t, y_{t+1}, \ldots, y_{t+k})}.

@item SOLVE FORWARD @var{x}
The block contains only equations where endogenous variable attributed
to the equation does not appear currently on the left hand side and
where no forward looking endogenous variables appear. The block has
the form: @math{g_j(y_{j,t}, y_t, y_{t-1}, \ldots, y_{t-k})=0}.
@var{x} is equal to @samp{SIMPLE} if the block has only one
equation. If several equation appears in the block, @var{x} is equal
to @samp{COMPLETE}.

@item SOLVE FORWARD @var{x}
The block contains only equations where endogenous variable attributed
to the equation does not appear currently on the left hand side and
where no backward looking endogenous variables appear. The block has
the form: @math{g_j(y_{j,t}, y_t, y_{t+1}, \ldots,
y_{t+k})=0}. @var{x} is equal to @samp{SIMPLE} if the block has only
one equation. If several equation appears in the block, @var{x} is
equal to @samp{COMPLETE}.

@item SOLVE TWO BOUNDARIES @var{x}
The block contains equations depending on both forward and backward
variables. The block looks like: @math{g_j(y_{j,t}, y_t, y_{t-1},
\ldots, y_{t-k} ,y_t, y_{t+1}, \ldots, y_{t+k})=0}. @var{x} is equal
to @samp{SIMPLE} if the block has only one equation. If several
equation appears in the block, @var{x} is equal to @samp{COMPLETE}.
@end table

@optionshead

@table @code

@item 'static'
Prints out the block decomposition of the static model.
Without 'static' option model_info displays the block decomposition
of the dynamic model.

@item 'incidence'
Displays the gross incidence matrix and the reordered incidence matrix
of the block decomposed model.

@end table


@end deffn

@deffn Command print_bytecode_dynamic_model ;
Prints the equations and the Jacobian matrix of the dynamic model
stored in the bytecode binary format file. Can only be used in
conjunction with the @code{bytecode} option of the @code{model} block.
@end deffn

@deffn Command print_bytecode_static_model ;
Prints the equations and the Jacobian matrix of the static model
stored in the bytecode binary format file. Can only be used in
conjunction with the @code{bytecode} option of the @code{model} block.
@end deffn

@node Deterministic simulation
@section Deterministic simulation

When the framework is deterministic, Dynare can be used for models
with the assumption of perfect foresight. Typically, the system is
supposed to be in a state of equilibrium before a period @samp{1} when
the news of a contemporaneous or of a future shock is learned by the
agents in the model. The purpose of the simulation is to describe the
reaction in anticipation of, then in reaction to the shock, until the
system returns to the old or to a new state of equilibrium. In most
models, this return to equilibrium is only an asymptotic phenomenon,
which one must approximate by an horizon of simulation far enough in
the future.  Another exercise for which Dynare is well suited is to
study the transition path to a new equilibrium following a permanent
shock.  For deterministic simulations, the numerical problem consists of solving
 a nonlinar system of simultaneous equations in @code{n} endogenous
 variables in @code{T} periods. Dynare offers several algorithms for
 solving this problem, which can be chosen via the
 @code{stack_solve_algo}-option. By default (@code{stack_solve_algo=0}),
Dynare uses a Newton-type method to solve the simultaneous equation
system. Because the resulting Jacobian is in the order of @code{n} by
@code{T} and hence will be very large for long simulations with many
variables, Dynare makes use of the sparse matrix capacities of
MATLAB/Octave. A slower but potentially less memory consuming alternative
(@code{stack_solve_algo=6}) is based on a Newton-type algorithm first
proposed by @cite{Laffargue (1990)} and @cite{Boucekkine (1995)}, which
uses relaxation techniques. Thereby, the algorithm avoids ever storing
the full Jacobian. The details of the algorithm can be found in
@cite{Juillard (1996)}. The third type of algorithms makes use of block
decomposition techniques (divide-and-conquer methods) that exploit the
structure of the model. The principle is to identify recursive and
simultaneous blocks in the model structure and use this information to
aid the solution process.  These solution algorithms can provide a
significant speed-up on large models.


@deffn Command perfect_foresight_setup ;
@deffnx Command perfect_foresight_setup (@var{OPTIONS}@dots{});

@descriptionhead

Prepares a perfect foresight simulation, by extracting the information in the
@code{initval}, @code{endval} and @code{shocks} blocks and converting them into
simulation paths for exogenous and endogenous variables.

This command must always be called before running the simulation with
@code{perfect_foresight_solver}.

@optionshead

@table @code

@item periods = @var{INTEGER}
Number of periods of the simulation

@item datafile = @var{FILENAME}
If the variables of the model are not constant over time, their
initial values, stored in a text file, could be loaded, using that
option, as initial values before a deterministic simulation.
@end table

@outputhead

The paths for the exogenous variables are stored into @code{oo_.exo_simul}.

The initial and terminal conditions for the endogenous variables and the
initial guess for the path of endogenous variables are stored into
@code{oo_.endo_simul}.

@end deffn


@deffn Command perfect_foresight_solver ;
@deffnx Command perfect_foresight_solver (@var{OPTIONS}@dots{});

@descriptionhead

Computes the perfect foresight (or deterministic) simulation of the model.

Note that @code{perfect_foresight_setup} must be called before this command, in
order to setup the environment for the simulation.

@optionshead

@table @code

@item maxit = @var{INTEGER}
Determines the maximum number of iterations used in the non-linear solver. The
default value of @code{maxit} is 50. 

@item tolf = @var{DOUBLE} 
Convergence criterion for termination based on the function value. Iteration will cease when it proves impossible to
improve the function value by more than @code{tolf}. Default: @code{1e-5}

@item tolx = @var{DOUBLE} 
Convergence criterion for termination based on the change in the function argument. Iteration will cease when the solver 
attempts to take a step that is smaller than @code{tolx}. Default: @code{1e-5}

@item stack_solve_algo = @var{INTEGER}
Algorithm used for computing the solution. Possible values are:

@table @code

@item 0
Newton method to solve simultaneously all the equations for every
period, using sparse matrices (Default).

@item 1
Use a Newton algorithm with a sparse LU solver at each iteration
(requires @code{bytecode} and/or @code{block} option, @pxref{Model
declaration}).

@item 2
Use a Newton algorithm with a Generalized Minimal Residual (GMRES)
solver at each iteration (requires @code{bytecode} and/or @code{block}
option, @pxref{Model declaration}; not available under Octave)

@item 3
Use a Newton algorithm with a Stabilized Bi-Conjugate Gradient
(BICGSTAB) solver at each iteration (requires @code{bytecode} and/or
@code{block} option, @pxref{Model declaration}).

@item 4
Use a Newton algorithm with a optimal path length at each iteration
(requires @code{bytecode} and/or @code{block} option, @pxref{Model
declaration}).

@item 5
Use a Newton algorithm with a sparse Gaussian elimination (SPE) solver
at each iteration (requires @code{bytecode} option, @pxref{Model
declaration}).

@item 6
Use the historical algorithm proposed in @cite{Juillard (1996)}: it is
slower than @code{stack_solve_algo=0}, but may be less memory consuming
on big models (not available with @code{bytecode} and/or @code{block}
options).

@item 7
Allows the user to solve the perfect foresight model with the solvers available
through option @code{solve_algo} (@xref{solve_algo} for a list of possible
values, note that values 5, 6, 7 and 8, which require @code{bytecode} and/or
@code{block} options, are not allowed). For instance, the following commands:
@example
perfect_foresight_setup(periods=400);
perfect_foresight_solver(stack_solve_algo=7, solve_algo=9)
@end example
trigger the computation of the solution with a trust region algorithm.

@end table

@item robust_lin_solve
Triggers the use of a robust linear solver for the default @code{stack_solve_algo=0}. 

@item solve_algo
@xref{solve_algo}. Allows selecting the solver used with @code{stack_solve_algo=7}.

@item no_homotopy
By default, the perfect foresight solver uses a homotopy technique if it cannot
solve the problem. Concretely, it divides the problem into smaller steps by
diminishing the size of shocks and increasing them progressively until the
problem converges. This option tells Dynare to disable that behavior. Note that
the homotopy is not implemented for purely forward or backward models.

@item markowitz = @var{DOUBLE}
Value of the Markowitz criterion, used to select the pivot. Only used
when @code{stack_solve_algo = 5}. Default: @code{0.5}.

@item minimal_solving_periods = @var{INTEGER}
Specify the minimal number of periods where the model has to be
solved, before using a constant set of operations for the remaining
periods. Only used when @code{stack_solve_algo = 5}. Default: @code{1}.

@item lmmcp
@anchor{lmmcp}
Solves the perfect foresight model with a Levenberg-Marquardt mixed complementarity problem (LMMCP) solver
(@cite{Kanzow and Petra 2004}), which allows to consider inequality constraints on the endogenous variables
(such as a ZLB on the nominal interest rate or a model with irreversible
investment). This option is equivalent to @code{stack_solve_algo=7} @strong{and}
@code{solve_algo=10}. Using the LMMCP solver requires a particular model setup as the goal is to get rid of 
any @code{min/max} operators and complementary slackness conditions that might introduce 
a singularity into the Jacobian. This is done by attaching an equation tag (@pxref{Model declaration})
with the @code{mcp} keyword to affected equations. This tag states that the equation 
to which the tag is attached has to hold unless the expression within the tag is binding.
For instance, a ZLB on the nominal interest rate would be specified as follows in the model block:
@example
model;
   ...
   [mcp = 'r > -1.94478']
   r = rho*r(-1) + (1-rho)*(gpi*Infl+gy*YGap) + e;
   ...
end;
@end example
where 1.94478 is the steady state level of the nominal interest rate and
@code{r} is the nominal interest rate in deviation from the steady state. This construct implies that
the Taylor rule is operative, unless the implied interest rate @code{r<=-1.94478}, in which case the 
@code{r} is fixed at @code{-1.94478} (thereby being equivalent to a complementary slackness
condition). By restricting the value of @code{r} coming out of this equation, the
@code{mcp}-tag also avoids using @code{max(r,-1.94478)} for other occurrences of @code{r} in the 
rest of the model. It is important to keep in mind that, because the @code{mcp}-tag effectively 
replaces a complementary slackness condition, it cannot be simply attached to any 
equation. Rather, it must be attached to the correct affected equation as otherwise the 
solver will solve a different problem than originally intended.

Note that in the current implementation, the content of the @code{mcp} equation tag is not parsed by the
preprocessor. The inequalities must therefore be as simple as possible: an endogenous
variable, followed by a relational operator, followed by a number (not a
variable, parameter or expression). 

@item endogenous_terminal_period
The  number of  periods is  not constant  across Newton  iterations when
solving the perfect foresight model. The size of the nonlinear system of
equations  is  reduced  by  removing  the  portion  of  the  paths  (and
associated equations) for which the solution has already been identified
(up to the  tolerance parameter). This strategy can be  interpreted as a
mix  of the  shooting and  relaxation  approaches. Note  that round  off
errors are  more important with  this mixed strategy (user  should check
the reported value  of the maximum absolute error).  Only available with
option @code{stack_solve_algo==0}.

@item linear_approximation
Solves the linearized version of the perfect foresight model. The model must be
stationary. Only available with option @code{stack_solve_algo==0}.

@end table

@outputhead

The simulated endogenous variables are available in global matrix
@code{oo_.endo_simul}.

@end deffn

@deffn Command simul ;
@deffnx Command simul (@var{OPTIONS}@dots{});

@descriptionhead

Short-form command for triggering the computation of a deterministic simulation
of the model. It is strictly equivalent to a call to
@code{perfect_foresight_setup} followed by a call to
@code{perfect_foresight_solver}.

@optionshead

Accepts all the options of @code{perfect_foresight_setup} and
@code{perfect_foresight_solver}.

@end deffn
@anchor{oo_.endo_simul}
@defvr {MATLAB/Octave variable} oo_.endo_simul
This variable stores the result of a deterministic simulation (computed by
@code{perfect_foresight_solver} or @code{simul}) or of a stochastic simulation
(computed by @code{stoch_simul} with the @code{periods} option or by
@code{extended_path}).

The variables are arranged row by row, in order of declaration (as in
@code{M_.endo_names}). Note that this variable also contains initial
and terminal conditions, so it has more columns than the value of
@code{periods} option.
@end defvr

@anchor{oo_.exo_simul}
@defvr {MATLAB/Octave variable} oo_.exo_simul
This variable stores the path of exogenous variables during a simulation
(computed by @code{perfect_foresight_solver}, @code{simul}, @code{stoch_simul}
or @code{extended_path}).

The variables are arranged in columns, in order of declaration (as in
@code{M_.exo_names}). Periods are in rows. Note that this convention
regarding columns and rows is the opposite of the convention for
@code{oo_.endo_simul}!

@end defvr

@node Stochastic solution and simulation
@section Stochastic solution and simulation

In a stochastic context, Dynare computes one or several simulations
corresponding to a random draw of the shocks.

The main algorithm for solving stochastic models relies on a Taylor
approximation, up to third order, of the expectation functions (see
@cite{Judd (1996)}, @cite{Collard and Juillard (2001a)}, @cite{Collard
and Juillard (2001b)}, and @cite{Schmitt-Grohé and Uríbe (2004)}). The
details of the Dynare implementation of the first order solution are
given in @cite{Villemot (2011)}. Such a solution is computed using
the @code{stoch_simul} command.

As an alternative, it is possible to compute a simulation to a
stochastic model using the @emph{extended path} method presented by
@cite{Fair and Taylor (1983)}. This method is especially useful when
there are strong nonlinearities or binding constraints. Such a
solution is computed using the @code{extended_path} command.

@menu
* Computing the stochastic solution::
* Typology and ordering of variables::
* First order approximation::
* Second order approximation::
* Third order approximation::
@end menu

@node Computing the stochastic solution
@subsection Computing the stochastic solution

@deffn Command stoch_simul [@var{VARIABLE_NAME}@dots{}];
@deffnx Command stoch_simul (@var{OPTIONS}@dots{}) [@var{VARIABLE_NAME}@dots{}];
@anchor{stoch_simul}
@descriptionhead

@code{stoch_simul} solves a stochastic (@i{i.e.} rational
expectations) model, using perturbation techniques.

More precisely, @code{stoch_simul} computes a Taylor approximation of
the decision and transition functions for the model. Using this, it
computes impulse response functions and various descriptive statistics
(moments, variance decomposition, correlation and autocorrelation
coefficients). For correlated shocks, the variance decomposition is
computed as in the VAR literature through a Cholesky decomposition of
the covariance matrix of the exogenous variables. When the shocks are
correlated, the variance decomposition depends upon the order of the
variables in the @code{varexo} command.

The Taylor approximation is computed around the steady state
(@pxref{Steady state}).

The IRFs are computed as the difference between the trajectory of a
variable following a shock at the beginning of period 1 and its steady
state value. More details on the computation of IRFs can be found on the
@uref{http://www.dynare.org/DynareWiki/IrFs,DynareWiki}.

Variance decomposition, correlation, autocorrelation are only
displayed for variables with strictly positive variance. Impulse response
functions are only plotted for variables with response larger than
@math{10^{-10}}.

Variance decomposition is computed relative to the sum of the
contribution of each shock. Normally, this is of course equal to
aggregate variance, but if a model generates very large variances, it
may happen that, due to numerical error, the two differ by a
significant amount. Dynare issues a warning if the maximum relative
difference between the sum of the contribution of each shock and
aggregate variance is larger than 0.01%.

The covariance matrix of the shocks is specified with the
@code{shocks} command (@pxref{Shocks on exogenous variables}).

When a list of @var{VARIABLE_NAME} is specified, results are displayed
only for these variables.

The @code{stoch_simul} command with a first order approximation can benefit from the block decomposition of the model (@pxref{block}).

@optionshead

@table @code

@item ar = @var{INTEGER}
@anchor{ar}
Order of autocorrelation coefficients to compute and to print. Default: @code{5}.

@item drop = @var{INTEGER}
Number of points (burnin) dropped at the beginning of simulation before computing the summary statistics. Note that this option does not affect the simulated series stored in @var{oo_.endo_simul} and the workspace. Here, no periods are dropped. Default: @code{100}.

@item hp_filter = @var{DOUBLE}
Uses HP filter with @math{\lambda} = @var{DOUBLE} before computing
moments. If theoretical moments are requested, the spectrum of the model solution is filtered 
following the approach outlined in @cite{Uhlig (2001)}.
Default: no filter.

@item one_sided_hp_filter = @var{DOUBLE}
Uses the one-sided HP filter with @math{\lambda} = @var{DOUBLE} described in @cite{Stock and Watson (1999)}
before computing moments. This option is only available with simulated moments.
Default: no filter.


@item hp_ngrid = @var{INTEGER}
Number of points in the grid for the discrete Inverse Fast Fourier
Transform used in the HP filter computation. It may be necessary to
increase it for highly autocorrelated processes. Default: @code{512}.

@item bandpass_filter
Uses a bandpass filter with the default passband before computing moments. If theoretical moments are
requested, the spectrum of the model solution is filtered using an ideal bandpass
filter. If empirical moments are requested, the @cite{Baxter and King (1999)}-filter
is used.
Default: no filter.

@item bandpass_filter = @var{[HIGHEST_PERIODICITY LOWEST_PERIODICITY]}
Uses a bandpass filter before computing moments. The passband is set to a periodicity of @code{HIGHEST_PERIODICITY} 
to @code{LOWEST_PERIODICITY}, @i{e.g.} @math{6} to @math{32} quarters if the model frequency is quarterly.
Default: @code{[6,32]}.

@item irf = @var{INTEGER}
@anchor{irf}
Number of periods on which to compute the IRFs. Setting @code{irf=0},
suppresses the plotting of IRFs. Default: @code{40}.

@item irf_shocks = ( @var{VARIABLE_NAME} [[,] @var{VARIABLE_NAME} @dots{}] )
@anchor{irf_shocks}
The exogenous variables for which to compute IRFs. Default: all.

@item relative_irf
@anchor{relative_irf}

Requests the computation of normalized IRFs. At first order, the normal shock vector of size one standard deviation is divided by the standard deviation of the current shock and multiplied by 100. The impulse responses are hence the responses to a unit shock of size 1 (as opposed to the regular shock size of one standard deviation), multiplied by 100. Thus, for a loglinearized model where the variables are measured in percent, the IRFs have the interpretation of the percent responses to a 100 percent shock. For example, a response of 400 of output to a TFP shock shows that output increases by 400 percent after a 100 percent TFP shock (you will see that TFP increases by 100 on impact). Given linearity at @code{ordeR=1}, it is straightforward to rescale the IRFs stored in @code{oo_.irfs} to any desired size.
At higher order, the interpretation is different. The @code{relative_irf} option then triggers the generation of IRFs as the response to a 0.01 unit shock (corresponding to 1 percent for shocks measured in percent) and no multiplication with 100 is performed. That is, the normal shock vector of size one standard deviation is divided by the standard deviation of the current shock and divided by 100.
For example, a response of 0.04 of log output (thus measured in percent of the steady state output level) to a TFP shock also measured in percent then shows that output increases by 4 percent after a 1 percent TFP shock (you will see that TFP increases by 0.01 on impact).


@item irf_plot_threshold = @var{DOUBLE}
@anchor{irf_plot_threshold}
Threshold size for plotting IRFs. All IRFs for a particular variable with a maximum absolute deviation from the steady state smaller than this value are not displayed. Default: @code{1e-10}.

@item nocorr
Don't print the correlation matrix (printing them is the default).

@item nodecomposition
Don't compute (and don't print) unconditional variance decomposition.

@item nofunctions
Don't print the coefficients of the approximated solution (printing
them is the default).

@item nomoments
Don't print moments of the endogenous variables (printing them is the
default).

@item nograph
@anchor{nograph} Do not create graphs (which implies that they are not
saved to the disk nor displayed). If this option is not used, graphs
will be saved to disk (to the format specified by @code{graph_format}
option, except if @code{graph_format=none}) and displayed to screen
(unless @code{nodisplay} option is used).

@item graph
@anchor{graph}
Re-enables the generation of graphs previously shut off with @ref{nograph}.

@item nodisplay
@anchor{nodisplay} Do not display the graphs, but still save them to disk
(unless @code{nograph} is used).

@item graph_format = @var{FORMAT}
@itemx graph_format = ( @var{FORMAT}, @var{FORMAT}@dots{} )
@anchor{graph_format}
Specify the file format(s) for graphs saved to disk. Possible values are
@code{eps} (the default), @code{pdf}, @code{fig} and @code{none} (under Octave,
only @code{eps} and @code{none} are available). If the file format is set equal to
@code{none}, the graphs are displayed but not saved to the disk.

@item noprint
Don't print anything. Useful for loops.

@item print
Print results (opposite of @code{noprint}).

@item order = @var{INTEGER}
@anchor{order}
Order of Taylor approximation. Acceptable values are @code{1},
@code{2} and @code{3}. Note that for third order,
@code{k_order_solver} option is implied and only empirical moments are
available (you must provide a value for @code{periods}
option). Default: @code{2} (except after an @code{estimation} command,
in which case the default is the value used for the estimation).

@item k_order_solver
@anchor{k_order_solver}
Use a k-order solver (implemented in C++) instead of the default
Dynare solver. This option is not yet compatible with the
@code{bytecode} option (@pxref{Model declaration}. Default: disabled
for order 1 and 2, enabled otherwise

@item periods = @var{INTEGER}
@vindex oo_.endo_simul
If different from zero, empirical moments will be computed instead of
theoretical moments. The value of the option specifies the number of
periods to use in the simulations. Values of the @code{initval} block,
possibly recomputed by @code{steady}, will be used as starting point
for the simulation. The simulated endogenous variables are made
available to the user in a vector for each variable and in the global
matrix @code{oo_.endo_simul} (@pxref{oo_.endo_simul}). The simulated
exogenous variables are made available in @code{oo_.exo_simul}
(@pxref{oo_.exo_simul}). Default: @code{0}.

@item qz_criterium = @var{DOUBLE}
Value used to split stable from unstable eigenvalues in reordering the
Generalized Schur decomposition used for solving 1^st order
problems. Default: @code{1.000001} (except when estimating with
@code{lik_init} option equal to @code{1}: the default is
@code{0.999999} in that case; @pxref{Estimation}).

@item qz_zero_threshold = @var{DOUBLE}
@xref{qz_zero_threshold}.

@item replic = @var{INTEGER}
Number of simulated series used to compute the IRFs. Default: @code{1}
if @code{order}=@code{1}, and @code{50} otherwise.

@item simul_replic = @var{INTEGER}
Number of series to simulate when empirical moments are requested
(@i{i.e.} @code{periods} > 0). Note that if this option is greater
than @code{1}, the additional series will not be used for computing
the empirical moments but will simply be saved in binary form to the
file @file{@var{FILENAME}_simul}. Default: @code{1}.

@item solve_algo = @var{INTEGER}
@xref{solve_algo}, for the possible values and their meaning.

@item aim_solver
@anchor{aim_solver}
Use the Anderson-Moore Algorithm (AIM) to compute the decision rules,
instead of using Dynare's default method based on a generalized Schur
decomposition. This option is only valid for first order
approximation. See
@uref{http://www.federalreserve.gov/Pubs/oss/oss4/aimindex.html,AIM
website} for more details on the algorithm.

@item conditional_variance_decomposition = @var{INTEGER}
@anchor{conditional_variance_decomposition = INTEGER}
See below.

@item conditional_variance_decomposition = [@var{INTEGER1}:@var{INTEGER2}]
See below.

@item conditional_variance_decomposition = [@var{INTEGER1} @var{INTEGER2} @dots{}]
Computes a conditional variance decomposition for the specified
period(s). The periods must be strictly positive. Conditional variances are given by
@math{var(y_{t+k}|t)}. For period 1, the conditional variance
decomposition provides the decomposition of the effects of shocks upon
impact. The results are stored in
@code{oo_.conditional_variance_decomposition}
(@pxref{oo_.conditional_variance_decomposition}). The variance decomposition is only conducted, if theoretical moments are requested, @i{i.e.} using the @code{periods=0}-option. In case of @code{order=2}, Dynare provides a second-order accurate approximation to the true second moments based on the linear terms of the second-order solution (see @cite{Kim, Kim, Schaumburg and Sims (2008)}). Note that the unconditional variance decomposition (@i{i.e.} at horizon infinity) is automatically conducted if theoretical moments are requested and if @code{nodecomposition} is not set (@pxref{oo_.variance_decomposition})

@item pruning
Discard higher order terms when iteratively computing simulations of
the solution. At second order, Dynare uses the algorithm of @cite{Kim, Kim, Schaumburg and Sims (2008)}, while at third order its generalization by @cite{Andreasen, Fernández-Villaverde and Rubio-Ramírez (2013)} is used.

@item partial_information
@anchor{partial_information}

Computes the solution of the model under partial information, along
the lines of @cite{Pearlman, Currie and Levine (1986)}. Agents are
supposed to observe only some variables of the economy. The set of
observed variables is declared using the @code{varobs} command. Note
that if @code{varobs} is not present or contains all endogenous
variables, then this is the full information case and this option has
no effect. More references can be found at
@uref{http://www.dynare.org/DynareWiki/PartialInformation}.

@item sylvester = @var{OPTION}
@anchor{sylvester}
Determines the algorithm used to solve the Sylvester equation for block decomposed model. Possible values for @code{@var{OPTION}} are:

@table @code

@item default
Uses the default solver for Sylvester equations (@code{gensylv}) based
on Ondra Kamenik's algorithm (see
@uref{http://www.dynare.org/documentation-and-support/dynarepp/sylvester.pdf/at_download/file,the
Dynare Website} for more information).

@item fixed_point
Uses a fixed point algorithm to solve the Sylvester equation (@code{gensylv_fp}). This method is faster than the @code{default} one for large scale models.

@end table

@noindent
Default value is @code{default}

@item sylvester_fixed_point_tol = @var{DOUBLE}
@anchor{sylvester_fixed_point_tol}
It is the convergence criterion used in the fixed point Sylvester solver. Its default value is 1e-12.

@item dr = @var{OPTION}
@anchor{dr}
Determines the method used to compute the decision rule. Possible values for @code{@var{OPTION}} are:

@table @code

@item default
Uses the default method to compute the decision rule based on the generalized Schur decomposition
(see @cite{Villemot (2011)} for more information).

@item cycle_reduction
Uses the cycle reduction algorithm to solve the polynomial equation for retrieving the coefficients
associated to the endogenous variables in the decision rule. This method is faster than the @code{default} one for large scale models.

@item logarithmic_reduction
Uses the logarithmic reduction algorithm to solve the polynomial equation for retrieving the coefficients
associated to the endogenous variables in the decision rule. This method is in general slower than the @code{cycle_reduction}.

@end table

@noindent
Default value is @code{default}

@item dr_cycle_reduction_tol = @var{DOUBLE}
@anchor{dr_cycle_reduction_tol}
The convergence criterion used in the cycle reduction algorithm. Its default value is 1e-7.

@item dr_logarithmic_reduction_tol = @var{DOUBLE}
@anchor{dr_logarithmic_reduction_tol}
The convergence criterion used in the logarithmic reduction algorithm. Its default value is 1e-12.

@item dr_logarithmic_reduction_maxiter = @var{INTEGER}
@anchor{dr_logarithmic_reduction_maxiter}
The maximum number of iterations used in the logarithmic reduction algorithm. Its default value is 100.

@item loglinear
@xref{loglinear}. Note that ALL variables are log-transformed by using the Jacobian transformation,
not only selected ones. Thus, you have to make sure that your variables have strictly positive
steady states. @code{stoch_simul} will display the moments, decision rules,
and impulse responses for the log-linearized variables. The decision rules saved
in @code{oo_.dr} and the simulated variables will also be the ones for the log-linear variables.

@item tex
@anchor{tex} Requests the printing of results and graphs in @TeX{}
tables and graphics that can be later directly included in @LaTeX{}
files.

@item dr_display_tol = @var{DOUBLE}
Tolerance for the suppression of small terms in the display of decision rules. Rows where all terms are 
smaller than @code{dr_display_tol} are not displayed. 
Default value: @code{1e-6}.

@item contemporaneous_correlation
@anchor{contemporaneous_correlation} 
Saves the contemporaneous correlation between the endogenous variables in @code{oo_.contemporaneous_correlation}.
Requires the @code{nocorr}-option not to be set.

@item spectral_density 
@anchor{spectral_density} 
Triggers the computation and display of the theoretical spectral density of the (filtered) model variables. 
Results are stored in @code{oo_.SpectralDensity}, defined below.
Default: do not request spectral density estimates

@end table

@outputhead

This command sets @code{oo_.dr}, @code{oo_.mean}, @code{oo_.var} and
@code{oo_.autocorr}, which are described below.

If option @code{periods} is present, sets @code{oo_.skewness}, 
@code{oo_.kurtosis}, and @code{oo_.endo_simul}
(@pxref{oo_.endo_simul}), and also saves the simulated variables in
MATLAB/Octave vectors of the global workspace with the same name as
the endogenous variables.

If options @code{irf} is different from zero, sets @code{oo_.irfs}
(see below) and also saves the IRFs in MATLAB/Octave vectors of
the global workspace (this latter way of accessing the IRFs is
deprecated and will disappear in a future version).

If the option @code{contemporaneous_correlation} is different from 0, sets 
@code{oo_.contemporaneous_correlation}, which is described below.

@customhead{Example 1}

@example
shocks;
var e;
stderr 0.0348;
end;

stoch_simul;
@end example

Performs the simulation of the 2nd order approximation of a model
with a single stochastic shock @code{e}, with a standard error of
0.0348.

@customhead{Example 2}

@example
stoch_simul(irf=60) y k;
@end example

Performs the simulation of a model and displays impulse
response functions on 60 periods for variables @code{y} and @code{k}.
@end deffn

@defvr {MATLAB/Octave variable} oo_.mean
After a run of @code{stoch_simul}, contains the mean of the endogenous
variables. Contains theoretical mean if the @code{periods} option is
not present, and simulated mean otherwise. The variables are arranged
in declaration order.
@end defvr

@defvr {MATLAB/Octave variable} oo_.var
After a run of @code{stoch_simul}, contains the variance-covariance of
the endogenous variables. Contains theoretical variance if the
@code{periods} option is not present (or an approximation thereof for @code{order=2}), 
and simulated variance
otherwise. The variables are arranged in declaration order.
@end defvr

@defvr {MATLAB/Octave variable} oo_.skewness
After a run of @code{stoch_simul} contains the skewness (standardized third moment)
of the simulated variables if the @code{periods} option is present. 
The variables are arranged in declaration order.
@end defvr

@defvr {MATLAB/Octave variable} oo_.kurtosis
After a run of @code{stoch_simul} contains the kurtosis (standardized fourth moment)
of the simulated variables if the @code{periods} option is present. 
The variables are arranged in declaration order.
@end defvr

@anchor{oo_.autocorr}
@defvr {MATLAB/Octave variable} oo_.autocorr
After a run of @code{stoch_simul}, contains a cell array of the
autocorrelation matrices of the endogenous variables. The element
number of the matrix in the cell array corresponds to the order of
autocorrelation. The option @code{ar} specifies the number of
autocorrelation matrices available. Contains theoretical
autocorrelations if the @code{periods} option is not present (or an approximation thereof for @code{order=2}), and
simulated autocorrelations otherwise. The field is only created if stationary variables are present.

The element @code{oo_.autocorr@{i@}(k,l)} is equal to the correlation
between @math{y^k_t} and @math{y^l_{t-i}}, where @math{y^k}
(resp. @math{y^l}) is the @math{k}-th (resp. @math{l}-th) endogenous
variable in the declaration order.

Note that if theoretical moments have been requested,
@code{oo_.autocorr@{i@}} is the same than @code{oo_.gamma_y@{i+1@}}.
@end defvr

@defvr {MATLAB/Octave variable} oo_.gamma_y
After a run of @code{stoch_simul}, if theoretical moments have been
requested (@i{i.e.} if the @code{periods} option is not present), this
variable contains a cell array with the following values (where
@code{ar} is the value of the option of the same name):

@table @code
@item oo_.gamma@{1@}
Variance/co-variance matrix.

@item oo_.gamma@{i+1@} (for i=1:ar)
Autocorrelation function. @pxref{oo_.autocorr} for more
details. Beware, this is the @i{autocorrelation} function, not the
@i{autocovariance} function.

@item oo_.gamma@{nar+2@}
Unconditional variance decomposition @pxref{oo_.variance_decomposition}

@item oo_.gamma@{nar+3@}
If a second order approximation has been requested, contains the
vector of the mean correction terms.
@end table

In case of @code{order=2}, the theoretical second moments are a second order 
accurate approximation of the true second moments, see @code{conditional_variance_decomposition}.

@end defvr

@anchor{oo_.variance_decomposition}
@defvr {MATLAB/Octave variable} oo_.variance_decomposition
After a run of @code{stoch_simul} when requesting theoretical moments (@code{periods=0}), 
contains a matrix with the result of the unconditional variance decomposition (@i{i.e.} at horizon infinity).
The first dimension corresponds to the endogenous variables (in the order of declaration) and 
the second dimension corresponds to exogenous variables (in the order of declaration). 
Numbers are in percent and sum up to 100 across columns.
@end defvr

@anchor{oo_.conditional_variance_decomposition}
@defvr {MATLAB/Octave variable} oo_.conditional_variance_decomposition
After a run of @code{stoch_simul} with the
@code{conditional_variance_decomposition} option, contains a
three-dimensional array with the result of the decomposition. The
first dimension corresponds to forecast horizons (as declared with the
option), the second dimension corresponds to endogenous variables (in
the order of declaration), the third dimension corresponds to
exogenous variables (in the order of declaration).
@end defvr

@anchor{oo_.contemporaneous_correlation}
@defvr {MATLAB/Octave variable} oo_.contemporaneous_correlation
After a run of @code{stoch_simul} with the
@code{contemporaneous_correlation} option, contains theoretical contemporaneous correlations if the
@code{periods} option is not present (or an approximation thereof for @code{order=2}), 
and simulated contemporaneous correlations otherwise. The variables are arranged in declaration order.
@end defvr

@anchor{oo_.SpectralDensity}
@defvr {MATLAB/Octave variable} oo_.SpectralDensity
After a run of @code{stoch_simul} with option @code{spectral_density} contains the spectral density
of the model variables. There will be a @code{nvars} by @code{nfrequencies} subfield
@code{freqs} storing the respective frequency grid points ranging from 0 to 2*pi and a 
same sized subfield @code{density} storing the corresponding density.
@end defvr

@defvr {MATLAB/Octave variable} oo_.irfs
After a run of @code{stoch_simul} with option @code{irf} different
from zero, contains the impulse responses, with the following naming
convention: @code{@var{VARIABLE_NAME}_@var{SHOCK_NAME}}.

For example, @code{oo_.irfs.gnp_ea} contains the effect on @code{gnp}
of a one standard deviation shock on @code{ea}.
@end defvr

The approximated solution of a model takes the form of a set of decision
rules or transition equations expressing the current value of the endogenous
variables of the model as function of the previous state of the model and
shocks observed at the beginning of the period. The decision rules are stored
in the structure @code{oo_.dr} which is described below.

@deffn Command extended_path ;
@deffnx Command extended_path (@var{OPTIONS}@dots{}) ;

@descriptionhead

@code{extended_path}   solves    a   stochastic    (@i{i.e.}    rational
expectations) model, using the  @emph{extended path} method presented by
@cite{Fair and Taylor (1983)}. Time  series for the endogenous variables
are generated  by assuming that the agents  believe that there  will no
more shocks in the following periods.

This function first  computes a random path for  the exogenous variables
(stored   in  @code{oo_.exo_simul},   @pxref{oo_.exo_simul})  and   then
computes  the corresponding  path for  endogenous variables,  taking the
steady state as  starting point. The result of the  simulation is stored
in  @code{oo_.endo_simul}   (@pxref{oo_.endo_simul}).  Note   that  this
simulation  approach  does  not  solve for  the  policy  and  transition
equations but for paths for the endogenous variables.

@optionshead

@table @code

@item periods = @var{INTEGER}
The number of periods for which the simulation is to be computed. No
default value, mandatory option.

@item solver_periods = @var{INTEGER}
The  number of  periods  used to  compute the  solution  of the  perfect
foresight at every iteration of the algorithm. Default: @code{200}.

@item order = @var{INTEGER}
If @code{order} is greater than 0 Dynare uses a gaussian quadrature to take into account the effects of future uncertainty. If @code{order}=@var{S} then the time  series for the endogenous variables
are generated  by assuming that the agents  believe that there  will no more shocks after period @var{t+S}. This is an experimental feature and can be quite slow. Default: @code{0}.

@item hybrid
Use the constant of the second order perturbation reduced form to correct the paths generated by the (stochastic) extended path algorithm.

@end table

@end deffn

@node Typology and ordering of variables
@subsection Typology and ordering of variables

Dynare distinguishes four types of endogenous variables:

@table @emph

@item Purely backward (or purely predetermined) variables
@vindex M_.npred
Those that appear only at current and past period in the model, but
not at future period (@i{i.e.} at @math{t} and @math{t-1} but not
@math{t+1}). The number of such variables is equal to
@code{M_.npred}.

@item Purely forward variables
@vindex M_.nfwrd
Those that appear only at current and future period in the model, but
not at past period (@i{i.e.} at @math{t} and @math{t+1} but not
@math{t-1}). The number of such variables is stored in
@code{M_.nfwrd}.

@item Mixed variables
@vindex M_.nboth
Those that appear at current, past and future period in the model
(@i{i.e.} at @math{t}, @math{t+1} and @math{t-1}). The number of such
variables is stored in @code{M_.nboth}.

@item Static variables
@vindex M_.nstatic
Those that appear only at current, not past and future period in the
model (@i{i.e.} only at @math{t}, not at @math{t+1} or
@math{t-1}). The number of such variables is stored in
@code{M_.nstatic}.
@end table

Note that all endogenous variables fall into one of these four
categories, since after the creation of auxiliary variables
(@pxref{Auxiliary variables}), all endogenous have at most one lead
and one lag. We therefore have the following identity:

@example
M_.npred + M_.both + M_.nfwrd + M_.nstatic = M_.endo_nbr
@end example

Internally, Dynare uses two orderings of the endogenous variables: the
order of declaration (which is reflected in @code{M_.endo_names}), and
an order based on the four types described above, which we will call
the DR-order (``DR'' stands for decision rules). Most of the time, the
declaration order is used, but for elements of the decision rules, the
DR-order is used.

The DR-order is the following: static variables appear first, then purely
backward variables, then mixed variables, and finally purely forward
variables. Inside each category, variables are arranged according to the
declaration order.

@vindex oo_.dr.order_var
@vindex oo_.dr.inv_order_var
Variable @code{oo_.dr.order_var} maps DR-order to declaration
order, and variable @code{oo_.dr.inv_order_var} contains the
inverse map. In other words, the k-th variable in the DR-order corresponds
to the endogenous variable numbered @code{oo_.dr_order_var(k)} in
declaration order. Conversely, k-th declared variable is numbered
@code{oo_.dr.inv_order_var(k)} in DR-order.

@vindex M_.nspred
@vindex M_.nsfwrd
@vindex M_.ndynamic
Finally, the state variables of the model are the purely backward variables
and the mixed variables. They are ordered in DR-order when they appear in
decision rules elements. There are @code{M_.nspred = M_.npred + M_.nboth} such
variables. Similarly, one has @code{M_.nsfwrd = M_.nfwrd + M_.nboth},
and @code{M_.ndynamic = M_.nfwrd+M_.nboth+M_.npred}.

@node First order approximation
@subsection First order approximation

The approximation has the stylized form:

@math{y_t = y^s + A y^h_{t-1} + B u_t}

where @math{y^s} is the steady state value of @math{y} and
@math{y^h_t=y_t-y^s}.

The coefficients of the decision rules are stored as follows:

@itemize

@item
@vindex oo_.dr.ys
@math{y^s} is stored in @code{oo_.dr.ys}. The vector rows
correspond to all endogenous in the declaration order.

@item
@vindex oo_.dr.ghx
A is stored in @code{oo_.dr.ghx}. The matrix rows correspond to all
endogenous in DR-order. The matrix columns correspond to state
variables in DR-order.

@item
@vindex oo_.dr.ghu
B is stored @code{oo_.dr.ghu}. The matrix rows correspond to all
endogenous in DR-order. The matrix columns correspond to exogenous
variables in declaration order.
@end itemize

Of course, the shown form of the approximation is only stylized, because it neglects the required different ordering in @math{y^s} and @math{y^h_t}. The precise form of the approximation that shows the way Dynare deals with differences between declaration and DR-order, is

@math{y_t(oo\_.dr.order\_var) = y^s(oo\_.dr.order\_var) + A \cdot y_{t-1}(oo\_.dr.order\_var(k2))-y^s(oo\_.dr.order\_var(k2)) + B\cdot u_t}

where @math{k2} selects the state variables, @math{y_t} and @math{y^s} are in declaration order and the coefficient matrices are in DR-order. Effectively, all variables on the right hand side are brought into DR order for computations and then assigned to @math{y_t} in declaration order.

@node Second order approximation
@subsection Second order approximation

The approximation has the form:

@math{y_t = y^s + 0.5 \Delta^2 +
A y^h_{t-1} + B u_t + 0.5 C
(y^h_{t-1}\otimes y^h_{t-1}) + 0.5 D
(u_t \otimes u_t) + E
(y^h_{t-1} \otimes u_t)}

where @math{y^s} is the steady state value of @math{y},
@math{y^h_t=y_t-y^s}, and @math{\Delta^2} is the shift effect of the
variance of future shocks. For the reordering required due to differences in declaration and DR order, see the first order approximation.

The coefficients of the decision rules are stored in the variables
described for first order approximation, plus the following variables:

@itemize

@item
@vindex oo_.dr.ghs2
@math{\Delta^2} is stored in @code{oo_.dr.ghs2}. The vector rows
correspond to all endogenous in DR-order.

@item
@vindex oo_.dr.ghxx
@math{C} is stored in @code{oo_.dr.ghxx}. The matrix rows
correspond to all endogenous in DR-order. The matrix columns correspond
to the Kronecker product of the vector of state variables in DR-order.

@item
@vindex oo_.dr.ghuu
@math{D} is stored in @code{oo_.dr.ghuu}. The matrix rows correspond
to all endogenous in DR-order. The matrix columns correspond to the
Kronecker product of exogenous variables in declaration order.

@item
@vindex oo_.dr.ghxu
@math{E} is stored in @code{oo_.dr.ghxu}. The matrix rows correspond
to all endogenous in DR-order. The matrix columns correspond to the
Kronecker product of the vector of state variables (in DR-order) by
the vector of exogenous variables (in declaration order).
@end itemize

@node Third order approximation
@subsection Third order approximation

The approximation has the form:

@math{y_t = y^s + G_0 +
G_1 z_t +
G_2 (z_t \otimes z_t) +
G_3 (z_t \otimes z_t \otimes z_t)}

where @math{y^s} is the steady state value of @math{y}, and @math{z_t} is a
vector consisting of the deviation from the steady state of the state
variables (in DR-order) at date @math{t-1} followed by the exogenous variables at
date @math{t} (in declaration order). The vector @math{z_t} is
therefore of size @math{n_z} = @code{M_.nspred +
M_.exo_nbr}.

The coefficients of the decision rules are stored as follows:

@itemize

@item
@vindex oo_.dr.ys
@math{y^s} is stored in @code{oo_.dr.ys}. The vector rows
correspond to all endogenous in the declaration order.

@item
@vindex oo_.dr.g_0
@math{G_0} is stored in @code{oo_.dr.g_0}. The
vector rows correspond to all endogenous in DR-order.

@item
@vindex oo_.dr.g_1
@math{G_1} is stored in @code{oo_.dr.g_1}. The matrix rows correspond
to all endogenous in DR-order. The matrix columns correspond to state
variables in DR-order, followed by exogenous in declaration order.

@item
@vindex oo_.dr.g_2
@math{G_2} is stored in @code{oo_.dr.g_2}. The matrix rows correspond
to all endogenous in DR-order. The matrix columns correspond to the
Kronecker product of state variables (in DR-order), followed by
exogenous (in declaration order). Note that the Kronecker product is
stored in a folded way, @i{i.e.} symmetric elements are stored only
once, which implies that the matrix has @math{n_z(n_z+1)/2} columns.  More
precisely, each column of this matrix corresponds to a pair @math{(i_1, i_2)}
where each index represents an element of @math{z_t} and is therefore between
@math{1} and @math{n_z}. Only non-decreasing pairs are stored, @i{i.e.} those for
which @math{i_1 \leq i_2}. The columns are arranged in the lexicographical order
of non-decreasing pairs. Also note that for those pairs where @math{i_1 \neq
i_2}, since the element is stored only once but appears two times in
the unfolded @math{G_2} matrix, it must be multiplied by 2 when computing the
decision rules.

@item
@vindex oo_.dr.g_3
@math{G_3} is stored in @code{oo_.dr.g_3}. The matrix rows correspond
to all endogenous in DR-order. The matrix columns correspond to the
third Kronecker power of state variables (in DR-order), followed by
exogenous (in declaration order). Note that the third Kronecker power
is stored in a folded way, @i{i.e.} symmetric elements are stored only
once, which implies that the matrix has @math{n_z(n_z+1)(n_z+2)/6}
columns.  More precisely, each column of this matrix corresponds to a
tuple @math{(i_1, i_2, i_3)} where each index represents an element of
@math{z_t} and is therefore between @math{1} and @math{n_z}. Only
non-decreasing tuples are stored, @i{i.e.} those for which @math{i_1
\leq i_2 \leq i_3}. The columns are arranged in the lexicographical
order of non-decreasing tuples. Also note that for tuples that have
three distinct indices (@i{i.e.} @math{i_1 \neq i_2} and @math{i_1
\neq i_3} and @math{i_2 \neq i_3}, since these elements are stored
only once but appears six times in the unfolded @math{G_3} matrix,
they must be multiplied by 6 when computing the decision
rules. Similarly, for those tuples that have two equal indices
(@i{i.e.} of the form @math{(a,a,b)} or @math{(a,b,a)} or
@math{(b,a,a)}), since these elements are stored only once but appears
three times in the unfolded @math{G_3} matrix, they must be multiplied
by 3 when computing the decision rules.
@end itemize


@node Estimation
@section Estimation

Provided that you have observations on some endogenous variables, it
is possible to use Dynare to estimate some or all parameters. Both
maximum likelihood (as in @cite{Ireland (2004)}) and Bayesian
techniques (as in @cite{Rabanal and Rubio-Ramirez (2003)},
@cite{Schorfheide (2000)} or @cite{Smets and Wouters (2003)}) are
available. Using Bayesian methods, it is possible to estimate DSGE
models, VAR models, or a combination of the two techniques called
DSGE-VAR.

Note that in order to avoid stochastic singularity, you must have at
least as many shocks or measurement errors in your model as you have
observed variables.

The estimation using a first order approximation can benefit from the block
decomposition of the model (@pxref{block}).


@deffn Command varobs @var{VARIABLE_NAME}@dots{};

@descriptionhead

This command lists the name of observed endogenous variables for the
estimation procedure. These variables must be available in the data
file (@pxref{estimation_cmd}).

Alternatively, this command is also used in conjunction with the
@code{partial_information} option of @code{stoch_simul}, for declaring
the set of observed variables when solving the model under partial
information.

Only one instance of @code{varobs} is allowed in a model file. If one
needs to declare observed variables in a loop, the macro-processor can
be used as shown in the second example below.

@customhead{Simple example}

@example
varobs C y rr;
@end example

@customhead{Example with a loop}

@example
varobs
@@#for co in countries
  GDP_@@@{co@}
@@#endfor
;
@end example

@end deffn

@deffn Block observation_trends ;

@descriptionhead

This block specifies @emph{linear} trends for observed variables as
functions of model parameters. In case the @code{loglinear}-option is used,
this corresponds to a linear trend in the logged observables, @i{i.e.} an exponential
trend in the level of the observables.

Each line inside of the block should be of the form:

@example
@var{VARIABLE_NAME}(@var{EXPRESSION});
@end example

In most cases, variables shouldn't be centered when
@code{observation_trends} is used. 

@examplehead

@example
observation_trends;
Y (eta);
P (mu/eta);
end;
@end example

@end deffn


@anchor{estimated_params}
@deffn Block estimated_params ;

@descriptionhead

This block lists all parameters to be estimated and specifies bounds
and priors as necessary.

Each line corresponds to an estimated parameter.

In a maximum likelihood estimation, each line follows this syntax:

@example
stderr VARIABLE_NAME | corr VARIABLE_NAME_1, VARIABLE_NAME_2 | PARAMETER_NAME
, INITIAL_VALUE [, LOWER_BOUND, UPPER_BOUND ];
@end example

In a Bayesian estimation, each line follows this syntax:

@example
stderr VARIABLE_NAME | corr VARIABLE_NAME_1, VARIABLE_NAME_2 |
PARAMETER_NAME | DSGE_PRIOR_WEIGHT
[, INITIAL_VALUE [, LOWER_BOUND, UPPER_BOUND]], PRIOR_SHAPE,
PRIOR_MEAN, PRIOR_STANDARD_ERROR [, PRIOR_3RD_PARAMETER [,
PRIOR_4TH_PARAMETER [, SCALE_PARAMETER ] ] ];
@end example

The first part of the line consists of one of the three following
alternatives:

@table @code

@item stderr @var{VARIABLE_NAME}
Indicates that the standard error of the exogenous variable
@var{VARIABLE_NAME}, or of the observation error/measurement errors associated with
endogenous observed variable @var{VARIABLE_NAME}, is to be estimated

@item corr @var{VARIABLE_NAME1}, @var{VARIABLE_NAME2}
Indicates that the correlation between the exogenous variables
@var{VARIABLE_NAME1} and @var{VARIABLE_NAME2}, or the correlation of
the observation errors/measurement errors associated with endogenous observed variables
@var{VARIABLE_NAME1} and @var{VARIABLE_NAME2}, is to be estimated. Note that correlations set by previous @code{shocks}-blocks or @code{estimation}-commands are kept at their value set prior to estimation if they are not estimated again subsequently. Thus, the treatment is the same as in the case of deep parameters set during model calibration and not estimated.

@item @var{PARAMETER_NAME}
The name of a model parameter to be estimated

@item DSGE_PRIOR_WEIGHT
@dots{}

@end table

The rest of the line consists of the following fields, some of them
being optional:

@table @code

@item @var{INITIAL_VALUE}
Specifies a starting value for the posterior mode optimizer or the
maximum likelihood estimation. If unset, defaults to the prior mean.

@item @var{LOWER_BOUND}
@anchor{lower_bound} Specifies a lower bound for the parameter value in maximum
likelihood estimation. In a Bayesian estimation context, sets a lower bound
only effective while maximizing the posterior kernel. This lower bound does not
modify the shape of the prior density, and is only aimed at helping the
optimizer in identifying the posterior mode (no consequences for the MCMC). For
some prior densities (namely inverse gamma, gamma, uniform, beta or weibull) it is
possible to shift the support of the prior distributions to the left or the right using
@ref{prior_3rd_parameter}. In this case the prior density is effectively
modified (note that the truncated Gaussian density is not implemented in
Dynare). If unset, defaults to minus infinity (ML) or the natural lower bound
of the prior (Bayesian estimation).

@item @var{UPPER_BOUND}
Same as @ref{lower_bound}, but specifying an upper bound instead.

@item @var{PRIOR_SHAPE}
A keyword specifying the shape of the prior density.
The possible values are: @code{beta_pdf},
@code{gamma_pdf}, @code{normal_pdf},
@code{uniform_pdf}, @code{inv_gamma_pdf},
@code{inv_gamma1_pdf}, @code{inv_gamma2_pdf} and @code{weibull_pdf}. Note
that @code{inv_gamma_pdf} is equivalent to
@code{inv_gamma1_pdf}

@item @var{PRIOR_MEAN}
@anchor{prior_mean} The mean of the prior distribution

@item @var{PRIOR_STANDARD_ERROR}
@anchor{prior_standard_error} The standard error of the prior distribution

@item @var{PRIOR_3RD_PARAMETER}
@anchor{prior_3rd_parameter}
A third parameter of the prior used for generalized beta distribution,
generalized gamma, generalized weibull and for the uniform distribution. Default: @code{0}

@item @var{PRIOR_4TH_PARAMETER}
@anchor{prior_4th_parameter}
A fourth parameter of the prior used for generalized beta distribution
and for the uniform distribution. Default: @code{1}

@item @var{SCALE_PARAMETER}
A parameter specific scale parameter for the jumping distribution's covariance matrix of the
Metropolis-Hasting algorithm
@end table

Note that @var{INITIAL_VALUE}, @var{LOWER_BOUND}, @var{UPPER_BOUND},
@var{PRIOR_MEAN}, @var{PRIOR_STANDARD_ERROR},
@var{PRIOR_3RD_PARAMETER}, @var{PRIOR_4TH_PARAMETER} and
@var{SCALE_PARAMETER} can be any valid @var{EXPRESSION}. Some of them
can be empty, in which Dynare will select a default value depending on
the context and the prior shape.

As one uses options more towards the end of the list, all previous
options must be filled: for example, if you want to specify
@var{SCALE_PARAMETER}, you must specify @var{PRIOR_3RD_PARAMETER} and
@var{PRIOR_4TH_PARAMETER}. Use empty values, if these parameters don't
apply.

@examplehead

The following line:
@example
corr eps_1, eps_2, 0.5,  ,  , beta_pdf, 0, 0.3, -1, 1;
@end example
sets a generalized beta prior for the correlation between @code{eps_1} and
@code{eps_2} with mean 0 and variance 0.3. By setting
@var{PRIOR_3RD_PARAMETER} to -1 and @var{PRIOR_4TH_PARAMETER} to 1 the
standard beta distribution with support [0,1] is changed to a
generalized beta with support [-1,1]. Note that @var{LOWER_BOUND} and
@var{UPPER_BOUND} are left empty and thus default to -1 and 1,
respectively. The initial value is set to 0.5.

Similarly, the following line:
@example
corr eps_1, eps_2, 0.5,  -0.5,  1, beta_pdf, 0, 0.3, -1, 1;
@end example
sets the same generalized beta distribution as before, but now truncates
this distribution to [-0.5,1] through the use of @var{LOWER_BOUND} and
@var{UPPER_BOUND}. Hence, the prior does not integrate to 1 anymore.

@customhead{Parameter transformation}

Sometimes, it is desirable to estimate a transformation of a parameter
appearing in the model, rather than the parameter itself. It is of
course possible to replace the original parameter by a function of the
estimated parameter everywhere is the model, but it is often
unpractical.

In such a case, it is possible to declare the parameter to be estimated
in the @code{parameters} statement and to define the transformation,
using a pound sign (#) expression (@pxref{Model declaration}).

@examplehead

@example
parameters bet;

model;
# sig = 1/bet;
c = sig*c(+1)*mpk;
end;

estimated_params;
bet, normal_pdf, 1, 0.05;
end;
@end example

@end deffn

@deffn Block estimated_params_init ;
@deffnx Block estimated_params_init (@var{OPTIONS}@dots{});

This block declares numerical initial values for the optimizer when
these ones are different from the prior mean. It should be specified after the @code{estimated_params}-block as otherwise the specified starting values are overwritten by the latter.

Each line has the following syntax:

@example
stderr VARIABLE_NAME | corr VARIABLE_NAME_1, VARIABLE_NAME_2 | PARAMETER_NAME
, INITIAL_VALUE;
@end example

@optionshead

@table @code

@item use_calibration
For not specifically initialized parameters, use the deep parameters and the elements of the covariance matrix specified in the @code{shocks} block from calibration as starting values for estimation. For components of the @code{shocks} block that were not explicitly specified during calibration or which violate the prior, the prior mean is used.
@end table

@xref{estimated_params}, for the meaning and syntax of the various components.

@end deffn

@deffn Block estimated_params_bounds ;

This block declares lower and upper bounds for parameters in maximum
likelihood estimation.

Each line has the following syntax:

@example
stderr VARIABLE_NAME | corr VARIABLE_NAME_1, VARIABLE_NAME_2 | PARAMETER_NAME
, LOWER_BOUND, UPPER_BOUND;
@end example

@xref{estimated_params}, for the meaning and syntax of the various components.

@end deffn

@anchor{estimation_cmd}
@deffn Command estimation [@var{VARIABLE_NAME}@dots{}];
@deffnx Command estimation (@var{OPTIONS}@dots{}) [@var{VARIABLE_NAME}@dots{}];

@descriptionhead

This command runs Bayesian or maximum likelihood estimation.

The following information will be displayed by the command:
@itemize

@item
results from posterior optimization (also for maximum likelihood)

@item
marginal log data density

@item
posterior mean and highest posterior density interval (shortest credible set) from posterior simulation

@item
convergence diagnostic table when only one MCM chain is used or Metropolis-Hastings convergence graphs documented in @cite{Pfeifer (2014)} 
in case of multiple MCM chains

@item
table with numerical inefficiency factors of the MCMC

@item
graphs with prior, posterior, and mode

@item
graphs of smoothed shocks, smoothed observation errors, smoothed and historical variables
@end itemize

Note that the posterior moments, smoothed variables, k-step ahead
filtered variables and forecasts (when requested) will only be
computed on the variables listed after the @code{estimation} command.
Alternatively, one can choose to compute these quantities on all
endogenous or on all observed variables (see
@code{consider_all_endogenous} and @code{consider_only_observed}
options below). If no variable is listed after the @code{estimation}
command, then Dynare will interactively ask which variable set to use.

Also, during  the MCMC  (Bayesian estimation with  @code{mh_replic}>0) a
(graphical or text) waiting bar is displayed showing the progress of the
Monte-Carlo and the @i{current} value of the acceptance ratio. Note that
if  the @code{load_mh_file}  option  is used  (see  below) the  reported
acceptance ratio does not take into  account the draws from the previous
MCMC. In the literature there is a general agreement for saying that the
acceptance ratio  should be close to  one third or one  quarter. If this
not the case, you can stop the MCMC (@code{Ctrl-C}) and change the value
of option @code{mh_jscale} (see below).

Note that by default Dynare generates random numbers using the algorithm
@code{mt199937ar} (@i{ie} Mersenne Twister method) with a seed set equal
to @code{0}.   Consequently the MCMCs  in Dynare are  deterministic: one
will  get  exactly  the  same   results  across  different  Dynare  runs
(@i{ceteris paribus}).  For instance, the posterior moments or posterior
densities  will be  exactly the  same. This  behaviour allows  to easily
identify the  consequences of a change  on the model, the  priors or the
estimation options. But one may also  want to check that across multiple
runs, with  different sequences of  proposals, the returned  results are
almost  identical. This  should  be  true if  the  number of  iterations
(@i{ie} the value of @code{mh_replic}) is important enough to ensure the
convergence of  the MCMC to its  ergodic distribution. In this  case the
default behaviour of the random number generators in not wanted, and the
user  should set  the  seed according  to the  system  clock before  the
estimation command using the following command:

@example
set_dynare_seed('clock');
@end example

@noindent so that the sequence of proposals will be different across different runs.

@algorithmshead

The Monte  Carlo Markov  Chain (MCMC) diagnostics are generated  by the
estimation command if @ref{mh_replic} is  larger than 2000 and if option
@ref{nodiagnostic} is not used. If @ref{mh_nblocks} is equal to one, the
convergence diagnostics  of @cite{Geweke  (1992,1999)} is  computed.  It
uses a chi square test to compare  the means of the first and last draws
specified  by  @ref{geweke_interval}  after  discarding  the  burnin  of
@ref{mh_drop}. The test  is computed using variance  estimates under the
assumption of  no serial correlation  as well as using  tapering windows
specified in  @ref{taper_steps}.  If @ref{mh_nblocks} is  larger than 1,
the convergence diagnostics of @cite{Brooks  and Gelman (1998)} are used
instead.  As described  in section 3 of @cite{Brooks  and Gelman (1998)}
the univariate convergence diagnostics are based on comparing pooled and
within MCMC moments (Dynare displays the second and third order moments,
and the length of the  Highest Probability Density interval covering 80%
of  the  posterior distribution).   Due  to  computational reasons,  the
multivariate  convergence diagnostic  does not  follow @cite{Brooks  and
Gelman (1998)}  strictly, but rather  applies their idea  for univariate
convergence  diagnostics  to  the  range  of  the  posterior  likelihood
function instead of the individual  parameters.  The posterior kernel is
used  to  aggregate  the  parameters   into  a  scalar  statistic  whose
convergence is  then checked using  the @cite{Brooks and  Gelman (1998)}
univariate convergence diagnostic.

The inefficiency factors are computed as in @cite{Giordano et al. (2011)} based on 
Parzen windows as in @i{e.g.} @cite{Andrews (1991)}.

@optionshead

@table @code

@item datafile = @var{FILENAME}
@anchor{datafile} The datafile: a @file{.m} file, a @file{.mat} file, a
@file{.csv} file, or a @file{.xls}/@file{.xlsx} file (under Octave, the
@uref{http://octave.sourceforge.net/io/,io} package from Octave-Forge is
required for the @file{.csv} and @file{.xlsx} formats and the @file{.xls} file
extension is not supported). Note that the base name (@i{i.e.} without
extension) of the datafile has to be different from the base name of the model
file.
If there are several files named @code{FILENAME}, but with different file endings,
the file name must be included in quoted strings and provide the file ending like
@example
@code{estimation(datafile='../fsdat_simul.mat',...)}
@end example

@item dirname = @var{FILENAME}
Directory in which to store @code{estimation} output. To pass a
subdirectory of a directory, you must quote the argument. Default:
@code{<mod_file>}

@item xls_sheet = @var{NAME}
@anchor{xls_sheet}
The name of the sheet with the data in an Excel file

@item xls_range = @var{RANGE}
@anchor{xls_range}
The range with the data in an Excel file. For example, @code{xls_range=B2:D200}

@item nobs = @var{INTEGER}
@anchor{nobs}
The number of observations following @ref{first_obs} to be used. Default: all observations in
the file after @code{first_obs}

@item nobs = [@var{INTEGER1}:@var{INTEGER2}]
@anchor{nobs1}
Runs a recursive estimation and forecast for samples of size ranging
of @var{INTEGER1} to @var{INTEGER2}. Option @code{forecast} must
also be specified. The forecasts are stored in the
@code{RecursiveForecast} field of the results structure (@pxref{RecursiveForecast}). 
The respective results structures @code{oo_} are saved in @code{oo_recursive_} (@pxref{oo_recursive_})
and are indexed with the respective sample length.

@item first_obs = @var{INTEGER}
@anchor{first_obs}
The number of the first observation to be used. In case of estimating a DSGE-VAR, 
@code{first_obs} needs to be larger than the number of lags.  Default: @code{1}

@item first_obs = [@var{INTEGER1}:@var{INTEGER2}]
@anchor{first_obs1}
Runs a rolling window estimation and forecast for samples of fixed size @code{nobs} starting with the 
first observation ranging from @var{INTEGER1} to @var{INTEGER2}. Option @code{forecast} 
must also be specified. This option is incompatible with requesting recursive forecasts using an 
expanding window (@pxref{nobs1,,nobs}). The respective results structures @code{oo_} 
are saved in @code{oo_recursive_} (@pxref{oo_recursive_}) and are indexed with the respective
first observation of the rolling window.


@item prefilter = @var{INTEGER}
@anchor{prefilter} A value of @code{1} means that the estimation procedure will
demean each data series by its empirical mean. If the @ref{loglinear} option
without the @ref{logdata} option is requested, the data will first be logged
and then demeaned. Default: @code{0}, @i{i.e.} no prefiltering

@item presample = @var{INTEGER}
@anchor{presample}
The number of observations after @ref{first_obs} to be skipped before evaluating the
likelihood. These presample observations do not enter the likelihood, but are used as a 
training sample for starting the Kalman filter iterations. This option is incompatible with 
estimating a DSGE-VAR. Default: @code{0}

@item loglinear
@anchor{loglinear}
Computes a log-linear approximation of the model instead of a linear
approximation. As always in the context of estimation, the data must correspond to the definition of the
variables used in the model (see @cite{Pfeifer (2013)} for more details on how to correctly specify observation equations linking model variables and the data). If you specify the loglinear option, Dynare will take the logarithm of both your model variables and of your data as it assumes the data to correspond to the original non-logged model variables. The displayed posterior results like impulse responses, smoothed variables, and moments will be for the logged variables, not the original un-logged ones. Default: computes a linear approximation

@item logdata
@anchor{logdata}
Dynare applies the @math{log} transformation to the provided data if a log-linearization of the model is requested (@ref{loglinear}) unless @code{logdata} option is used. This option is necessary if the user provides data already in logs, otherwise the @math{log} transformation will be applied twice (this may result in complex data).

@item plot_priors = @var{INTEGER}
Control the plotting of priors:
1
@table @code

@item 0
No prior plot

@item 1
Prior density for each estimated parameter is plotted. It is important
to check that the actual shape of prior densities matches what you
have in mind. Ill-chosen values for the prior standard density can
result in absurd prior densities.
@end table

@noindent
Default value is @code{1}.

@item nograph
@xref{nograph}.

@item posterior_nograph
@anchor{posterior_nograph}
Suppresses the generation of graphs associated with Bayesian IRFs (@ref{bayesian_irf}), 
posterior smoothed objects (@ref{smoother}), and posterior forecasts (@ref{forecast}).

@item posterior_graph
@anchor{posterior_graph}
Re-enables the generation of graphs previously shut off with @ref{posterior_nograph}.

@item nodisplay
@xref{nodisplay}.

@item graph_format = @var{FORMAT}
@itemx graph_format = ( @var{FORMAT}, @var{FORMAT}@dots{} )
@xref{graph_format}.

@item lik_init = @var{INTEGER}
@anchor{lik_init}
Type of initialization of Kalman filter:

@table @code

@item 1
For stationary models, the initial matrix of variance of the error of
forecast is set equal to the unconditional variance of the state
variables

@item 2
For nonstationary models: a wide prior is used with an initial matrix
of variance of the error of forecast diagonal with 10 on the diagonal 
(follows the suggestion of @cite{Harvey and Phillips(1979)})

@item 3
For nonstationary models: use a diffuse filter (use rather the @code{diffuse_filter} option)

@item 4
The filter is initialized with the fixed point of the Riccati equation

@item 5
Use i) option 2 for the non-stationary elements by setting their initial variance in the 
forecast error matrix to 10 on the diagonal and all covariances to 0 and ii) option 1 for the stationary elements.

@end table

@noindent
Default value is @code{1}. For advanced use only.

@item lik_algo = @var{INTEGER}
For internal use and testing only.

@item conf_sig = @var{DOUBLE}
Confidence interval used for classical forecasting after estimation. @xref{conf_sig}.

@item mh_conf_sig = @var{DOUBLE}
@anchor{mh_conf_sig} 
Confidence/HPD interval used for the computation of prior and  posterior statistics like: parameter distributions, prior/posterior moments, conditional variance decomposition, impulse response functions, Bayesian forecasting. Default: @code{0.9} 

@item mh_replic = @var{INTEGER}
@anchor{mh_replic} Number of replications for Metropolis-Hastings
algorithm. For the time being, @code{mh_replic} should be larger than
@code{1200}. Default: @code{20000}

@item sub_draws = @var{INTEGER}
@anchor{sub_draws}  number of  draws  from  the MCMC  that  are used  to
compute posterior  distribution of  various objects  (smoothed variable,
smoothed shocks,  forecast, moments,  IRF).  The  draws used  to compute
these posterior moments are sampled uniformly in the estimated empirical
posterior  distribution (@i{ie}  draws of  the MCMC).   @code{sub_draws}
should  be  smaller than  the  total  number  of MCMC  draws  available.
Default:  @code{min(posterior_max_subsample_draws,(Total  number  of
draws)*(number of chains))}

@item posterior_max_subsample_draws = @var{INTEGER}
@anchor{posterior_max_subsample_draws} maximum number  of draws from the
MCMC used to compute posterior distribution of various objects (smoothed
variable, smoothed shocks, forecast, moments,  IRF), if not overriden by
option @ref{sub_draws}. Default: @code{1200}

@item mh_nblocks = @var{INTEGER}
@anchor{mh_nblocks} Number of parallel chains for Metropolis-Hastings algorithm. Default:
@code{2}

@item mh_drop = @var{DOUBLE}
@anchor{mh_drop}
The fraction of initially generated parameter vectors to be dropped as a burnin before using posterior simulations. Default: @code{0.5}

@item mh_jscale = @var{DOUBLE}
@anchor{mh_jscale}  The scale  parameter of  the jumping  distribution's
covariance matrix (Metropolis-Hastings or TaRB-algorithm).  The default value is
rarely satisfactory. This option must be tuned to obtain, ideally, an
acceptance ratio of 25%-33%.
Basically,  the  idea  is  to  increase  the  variance  of  the  jumping
distribution if the acceptance ratio is too high, and decrease the same
variance if the acceptance ratio is too low. In some situations it may
help to consider parameter-specific values for this scale parameter. 
This  can  be  done  in  the  @ref{estimated_params}- block.  

Note that @code{mode_compute=6} will tune the scale parameter to achieve an acceptance rate of 
@ref{AcceptanceRateTarget}. The resulting scale parameter will be saved into a file
named @file{@var{MODEL_FILENAME}_mh_scale.mat}. This file can be loaded in subsequent runs
via the @code{posterior_sampler_options}-option @ref{scale_file}. Both @code{mode_compute=6}
and @code{scale_file} will overwrite any value specified in @code{estimated_params} with the tuned value.  
Default: @code{0.2}

@item mh_init_scale = @var{DOUBLE}
The scale to be used for drawing the initial value of the
Metropolis-Hastings chain. Generally, the starting points should be overdispersed
for the @cite{Brooks and Gelman (1998)}-convergence diagnostics to be meaningful. Default: 2*@code{mh_jscale}. 
It is important to keep in mind that @code{mh_init_scale} is set at the beginning of 
Dynare execution, @i{i.e.} the default will not take into account potential changes in
@ref{mh_jscale} introduced by either @code{mode_compute=6} or the 
@code{posterior_sampler_options}-option @ref{scale_file}. 
If @code{mh_init_scale} is too wide during initalization of the posterior sampler so that 100 tested draws 
are inadmissible (@i{e.g.} Blanchard-Kahn conditions are always violated), Dynare will request user input 
of a new @code{mh_init_scale} value with which the next 100 draws will be drawn and tested. 
If the @ref{nointeractive}-option has been invoked, the program will instead automatically decrease 
@code{mh_init_scale} by 10 percent after 100 futile draws and try another 100 draws. This iterative 
procedure will take place at most 10 times, at which point Dynare will abort with an error message.

@item mh_recover
@anchor{mh_recover} Attempts to recover a Metropolis-Hastings
simulation that crashed prematurely, starting with the last available saved 
@code{mh}-file. Shouldn't be used together with
@code{load_mh_file} or a different @code{mh_replic} than in the crashed run. Since Dynare 4.5
the proposal density from the previous run will automatically be loaded. In older versions,
to assure a neat continuation of the chain with the same proposal density, you should 
provide the @code{mode_file} used in the previous 
run or the same user-defined @code{mcmc_jumping_covariance} when using this option. Note that 
under Octave, a neat continuation of the crashed chain with the respective last random number 
generator state is currently not supported.

@item mh_mode = @var{INTEGER}
@dots{}

@item mode_file = @var{FILENAME}
@anchor{mode_file}
Name of the file containing previous value for the mode. When
computing the mode, Dynare stores the mode (@code{xparam1}) and the
hessian (@code{hh}, only if @code{cova_compute=1}) in a file called
@file{@var{MODEL_FILENAME}_mode.mat}. After a successful run of the estimation
command, the @code{mode_file} will be disabled to prevent other function calls
from implicitly using an updated mode-file. Thus, if the mod-file contains subsequent
@code{estimation} commands, the @code{mode_file} option, if desired, needs to be 
specified again.

@item mode_compute = @var{INTEGER} | @var{FUNCTION_NAME}
@anchor{mode_compute}
Specifies the optimizer for the mode computation:

@table @code

@item 0
The mode isn't computed. When @code{mode_file} option is specified, the
mode is simply read from that file.

When @code{mode_file} option is not
specified, Dynare reports the value of the log posterior (log likelihood)
evaluated at the initial value of the parameters.

When @code{mode_file}
option is not specified and there is no @code{estimated_params} block,
but the @code{smoother} option is used, it is a roundabout way to
compute the smoothed value of the variables of a model with calibrated parameters.

@item 1
Uses @code{fmincon} optimization routine (available under MATLAB if
the Optimization Toolbox is installed; not available under Octave)

@item 2
Uses the continuous simulated annealing global optimization algorithm 
described in @cite{Corana et al. (1987)} and @cite{Goffe et al. (1994)}.

@item 3
Uses @code{fminunc} optimization routine (available under MATLAB if
the optimization toolbox is installed; available under Octave if the
@uref{http://octave.sourceforge.net/optim/,optim} package from
Octave-Forge is installed)

@item 4
Uses Chris Sims's @code{csminwel}

@item 5
Uses Marco Ratto's @code{newrat}. This value is not compatible with non
linear filters or DSGE-VAR models.
This is a slice optimizer: most iterations are a sequence of univariate optimization step, one for each estimated parameter or shock.
Uses @code{csminwel} for line search in each step.

@item 6
Uses a Monte-Carlo based optimization routine (see
@uref{http://www.dynare.org/DynareWiki/MonteCarloOptimization,Dynare
wiki} for more details)

@item 7
Uses @code{fminsearch}, a simplex based optimization routine (available
under MATLAB if the optimization toolbox is installed; available under
Octave if the @uref{http://octave.sourceforge.net/optim/,optim}
package from Octave-Forge is installed)

@item 8
Uses Dynare implementation of the Nelder-Mead simplex based optimization
routine (generally more efficient than the MATLAB or Octave implementation
available with @code{mode_compute=7})

@item 9
Uses the CMA-ES (Covariance Matrix Adaptation Evolution Strategy) algorithm of 
@cite{Hansen and Kern (2004)}, an evolutionary algorithm for difficult non-linear non-convex optimization

@item 10
Uses the simpsa algorithm, based on the combination of the non-linear simplex and simulated annealing algorithms and proposed by
@cite{Cardoso, Salcedo and Feyo de Azevedo (1996)}.

@item 11
This is not strictly speaking an optimization algorithm. The (estimated) parameters are treated as state variables and estimated jointly with the original state variables of the model using a nonlinear filter. The algorithm implemented in Dynare is described in @cite{Liu and West (2001)}.

@item 12
Uses @code{particleswarm} optimization routine (available under MATLAB if
the Global Optimization Toolbox is installed; not available under Octave).

@item 101
Uses the SolveOpt algorithm for local nonlinear optimization problems proposed by
@cite{Kuntsevich and Kappel (1997)}.

@item 102
Uses @code{simulannealbnd} optimization routine (available under MATLAB if
the Global Optimization Toolbox is installed; not available under Octave)

@item @var{FUNCTION_NAME}
It is also possible to give a @var{FUNCTION_NAME} to this option,
instead of an @var{INTEGER}. In that case, Dynare takes the return
value of that function as the posterior mode.
@end table

@noindent
Default value is @code{4}.

@item silent_optimizer
@anchor{silent_optimizer}
Instructs Dynare to run mode computing/optimization silently without displaying results or 
saving files in between. Useful when running loops.

@item mcmc_jumping_covariance = hessian|prior_variance|identity_matrix|@var{FILENAME}
@anchor{MCMC_jumping_covariance}
Tells Dynare which covariance to use for the proposal density of the MCMC sampler. @code{mcmc_jumping_covariance} can be one of the following:

@table @code
@item hessian
Uses the Hessian matrix computed at the mode.

@item prior_variance
Uses the prior variances. No infinite prior variances are allowed in this case.

@item identity_matrix
Uses an identity matrix.

@item @var{FILENAME}
Loads an arbitrary user-specified covariance matrix from @code{@var{FILENAME}.mat}. The covariance matrix must be saved in a variable named @code{jumping_covariance}, must be square, positive definite, and have the same dimension as the number of estimated parameters.

@end table
@noindent
Note that the covariance matrices are still scaled with @ref{mh_jscale}. Default value is @code{hessian}.

@item mode_check
Tells Dynare to plot the posterior density for values around the
computed mode for each estimated parameter in turn. This is helpful to
diagnose problems with the optimizer. Note that for @code{order}>1, the 
likelihood function resulting from the particle filter is not differentiable
anymore due to random chatter introduced by selecting different particles for 
different parameter values. For this reason, the @code{mode_check}-plot may look wiggly.

@item mode_check_neighbourhood_size = @var{DOUBLE}
Used in conjunction with option @code{mode_check}, gives the width of
the window around the posterior mode to be displayed on the diagnostic
plots. This width is expressed in percentage deviation. The @code{Inf}
value is allowed, and will trigger a plot over the entire domain
(see also @code{mode_check_symmetric_plots}).
Default: @code{0.5}.

@item mode_check_symmetric_plots = @var{INTEGER}
Used in conjunction with option @code{mode_check}, if set to @code{1},
tells Dynare to ensure that the check plots are symmetric around the
posterior mode. A value of @code{0} allows to have asymmetric plots,
which can be useful if the posterior mode is close to a domain
boundary, or in conjunction with @code{mode_check_neighbourhood_size =
Inf} when the domain in not the entire real line. Default: @code{1}.

@item mode_check_number_of_points = @var{INTEGER}
Number of points around the posterior mode where the posterior kernel is evaluated (for each parameter). Default is @code{20}

@item prior_trunc = @var{DOUBLE}
@anchor{prior_trunc} Probability of extreme values of the prior
density that is ignored when computing bounds for the
parameters. Default: @code{1e-32}

@item huge_number  = @var{DOUBLE}
@anchor{huge_number} Value for replacing infinite values in the definition of (prior) bounds 
when finite values are required for computational reasons. Default: @code{1e7}

@item load_mh_file
@anchor{load_mh_file} Tells Dynare to add to previous
Metropolis-Hastings simulations instead of starting from
scratch. Since Dynare 4.5
the proposal density from the previous run will automatically be loaded. In older versions,
to assure a neat continuation of the chain with the same proposal density, you should 
provide the @code{mode_file} used in the previous 
run or the same user-defined @code{mcmc_jumping_covariance} when using this option.
Shouldn't be used together with @code{mh_recover}. Note that under Octave, a neat 
continuation of the chain with the last random number 
generator state of the already present draws is currently not supported.

@item load_results_after_load_mh
@anchor{load_results_after_load_mh} This option is available when loading a previous MCMC run without
adding additional draws, @i{i.e.} when @code{load_mh_file} is specified with @code{mh_replic=0}. It tells Dynare 
to load the previously computed convergence diagnostics, marginal data density, and posterior statistics from an
existing @code{_results}-file instead of recomputing them.

@item optim = (@var{NAME}, @var{VALUE}, ...)
@anchor{optim}
A list of @var{NAME} and @var{VALUE} pairs. Can be used to set options for the optimization routines. The set of available options depends on the selected optimization routine (ie on the value of option @ref{mode_compute}):

@table @code

@item 1, 3, 7, 12
Available options are given in the documentation of the MATLAB Optimization Toolbox or in Octave's documentation.

@item 2
Available options are:

@table @code

@item 'initial_step_length'
Initial step length. Default: @code{1}

@item 'initial_temperature'
Initial temperature. Default: @code{15}

@item 'MaxIter'
Maximum number of function evaluations. Default: @code{100000}

@item 'neps'
Number of final function values used to decide upon termination. Default: @code{10}

@item 'ns'
Number of cycles. Default: @code{10}

@item 'nt'
Number of iterations before temperature reduction. Default: @code{10}

@item 'step_length_c'
Step length adjustment. Default: @code{0.1}

@item 'TolFun'
Stopping criteria. Default: @code{1e-8}

@item 'rt'
Temperature reduction factor. Default: @code{0.1}

@item 'verbosity'
Controls verbosity of display during optimization, ranging from 0 (silent) to 3 
(each function evaluation). Default: @code{1}

@end table

@item 4
Available options are:

@table @code

@item 'InitialInverseHessian'
Initial approximation for the inverse of the Hessian matrix of the posterior kernel (or likelihood). Obviously this approximation has to be a square, positive definite and symmetric matrix. Default: @code{'1e-4*eye(nx)'}, where @code{nx} is the number of parameters to be estimated.

@item 'MaxIter'
Maximum number of iterations. Default: @code{1000}

@item 'NumgradAlgorithm'
Possible values are @code{2}, @code{3} and @code{5} respectively corresponding to the two, three and five points formula used to compute the gradient of the objective function (see @cite{Abramowitz and Stegun (1964)}). Values @code{13} and @code{15} are more experimental. If perturbations on the right and the left increase the value of the objective function (we minimize this function) then we force the corresponding element of the gradient to be zero. The idea is to temporarily reduce the size of the optimization problem. Default: @code{2}.

@item 'NumgradEpsilon'
Size of the perturbation used to compute numerically the gradient of the objective function. Default: @code{1e-6}

@item 'TolFun'
Stopping criteria. Default: @code{1e-7}

@item 'verbosity'
Controls verbosity of display during optimization. Set to 0 to set to silent. Default: @code{1}

@item 'SaveFiles'
Controls saving of intermediate results during optimization. Set to 0 to shut off saving. Default: @code{1}

@end table

@item 5
Available options are:

@table @code

@item 'Hessian'
Triggers three types of Hessian computations. @code{0}: outer product gradient; @code{1} default DYNARE Hessian routine; @code{2} 'mixed' outer product gradient, where diagonal elements are obtained using second order derivation formula and outer product is used for correlation structure. 
Both @{0@} and @{2@} options require univariate filters, to ensure using maximum number of individual densities and a positive definite Hessian.
Both @{0@} and @{2@} are quicker than default DYNARE numeric Hessian, but provide decent starting values for Metropolis for large models (option @{2@} being more accurate than @{0@}).
Default: @code{1}.

@item 'MaxIter'
Maximum number of iterations. Default: @code{1000}

@item 'TolFun'
Stopping criteria. Default: @code{1e-5} for numerical derivatives @code{1e-7} for analytic derivatives.

@item 'verbosity'
Controls verbosity of display during optimization. Set to 0 to set to silent. Default: @code{1}

@item 'SaveFiles'
Controls saving of intermediate results during optimization. Set to 0 to shut off saving. Default: @code{1}

@end table

@item 6
Available options are:

@table @code

@item 'AcceptanceRateTarget'
@anchor{AcceptanceRateTarget}
A real number between zero and one. The scale parameter of the jumping distribution is adjusted so that the effective acceptance rate matches the value of option @code{'AcceptanceRateTarget'}. Default: @code{1.0/3.0}

@item 'InitialCovarianceMatrix'
Initial covariance matrix of the jumping distribution. Default is @code{'previous'} if option @code{mode_file} is used, @code{'prior'} otherwise.

@item 'nclimb'
Number of iterations in the last MCMC (climbing mode).

@item 'ncov-mh'
Number of iterations used for updating the covariance matrix of the jumping distribution. Default: @code{20000}

@item 'nscale-mh'
Maximum number of iterations used for adjusting the scale parameter of the jumping distribution.  @code{200000}

@item 'NumberOfMh'
Number of MCMC run sequentially. Default: @code{3}

@end table

@item 8
Available options are:

@table @code

@item 'InitialSimplexSize'
Initial size of the simplex, expressed as percentage deviation from the provided initial guess in each direction. Default: @code{.05}

@item 'MaxIter'
Maximum number of iterations. Default: @code{5000}

@item 'MaxFunEvals'
Maximum number of objective function evaluations. No default.

@item 'MaxFunvEvalFactor'
Set @code{MaxFunvEvals} equal to @code{MaxFunvEvalFactor} times the number of estimated parameters. Default: @code{500}.

@item 'TolFun'
Tolerance parameter (w.r.t the objective function). Default: @code{1e-4}

@item 'TolX'
Tolerance parameter (w.r.t the instruments). Default: @code{1e-4}

@item 'verbosity'
Controls verbosity of display during optimization. Set to 0 to set to silent. Default: @code{1}

@end table

@item 9
Available options are:

@table @code

@item 'CMAESResume'
Resume previous run. Requires the @code{variablescmaes.mat} from the last run. 
Set to 1 to enable. Default: @code{0}

@item 'MaxIter'
Maximum number of iterations.

@item 'MaxFunEvals'
Maximum number of objective function evaluations. Default: @code{Inf}.

@item 'TolFun'
Tolerance parameter (w.r.t the objective function). Default: @code{1e-7}

@item 'TolX'
Tolerance parameter (w.r.t the instruments). Default: @code{1e-7}

@item 'verbosity'
Controls verbosity of display during optimization. Set to 0 to set to silent. Default: @code{1}

@item 'SaveFiles'
Controls saving of intermediate results during optimization. Set to 0 to shut off saving. Default: @code{1}

@end table

@item 10
Available options are:

@table @code

@item 'EndTemperature'
Terminal condition w.r.t the temperature. When the temperature reaches @code{EndTemperature}, the temperature is set to zero and the algorithm falls back into a standard simplex algorithm. Default: @code{.1}

@item 'MaxIter'
Maximum number of iterations. Default: @code{5000}

@item 'MaxFunvEvals'
Maximum number of objective function evaluations. No default.

@item 'TolFun'
Tolerance parameter (w.r.t the objective function). Default: @code{1e-4}

@item 'TolX'
Tolerance parameter (w.r.t the instruments). Default: @code{1e-4}

@item 'verbosity'
Controls verbosity of display during optimization. Set to 0 to set to silent. Default: @code{1}

@end table

@item 101
Available options are:

@table @code

@item 'LBGradientStep'
Lower bound for the stepsize used for the difference approximation of gradients. Default: @code{1e-11}

@item 'MaxIter'
Maximum number of iterations. Default: @code{15000}

@item 'SpaceDilation'
Coefficient of space dilation. Default: @code{2.5}

@item 'TolFun'
Tolerance parameter (w.r.t the objective function). Default: @code{1e-6}

@item 'TolX'
Tolerance parameter (w.r.t the instruments). Default: @code{1e-6}

@item 'verbosity'
Controls verbosity of display during optimization. Set to 0 to set to silent. Default: @code{1}

@end table

@item 102
Available options are given in the documentation of the MATLAB Global Optimization Toolbox.

@end table

@customhead{Example 1}
To change the defaults of csminwel (@code{mode_compute=4}):

@code{estimation(..., mode_compute=4, optim=('NumgradAlgorithm',3,'TolFun',1e-5), ...);}


@item nodiagnostic
@anchor{nodiagnostic} Does not compute the convergence diagnostics for
Metropolis-Hastings. Default: diagnostics are computed and displayed

@item bayesian_irf
@anchor{bayesian_irf} Triggers the computation of the posterior
distribution of IRFs. The length of the IRFs are controlled by the
@code{irf} option. Results are stored in @code{oo_.PosteriorIRF.dsge}
(see below for a description of this variable)

@item relative_irf
@xref{relative_irf}.

@item dsge_var = @var{DOUBLE}
@anchor{dsge_var} Triggers the estimation of a DSGE-VAR model, where the
weight of  the DSGE prior  of the VAR model  is calibrated to  the value
passed (see @cite{Del  Negro and Schorfheide (2004)}). It represents ratio of dummy over actual observations. 
To assure that the prior is proper, the value must be bigger than @math{(k+n)/T}, 
where @math{k} is the number of estimated parameters, @math{n} is the number of observables, #
and @math{T} is the number of observations. NB:  The previous method
of   declaring  @code{dsge_prior_weight} as a parameter and then
calibrating it is now deprecated and will be removed in a future release
of Dynare.
Some of objects arising during estimation are stored with their values at the mode in
@ref{oo_.dsge_var.posterior_mode}.

@item dsge_var
Triggers the  estimation of a  DSGE-VAR model,  where the weight  of the
DSGE prior of  the VAR model will  be estimated (as in  @cite{Adjemian et alii
(2008)}).    The   prior    on   the   weight   of    the   DSGE   prior,
@code{dsge_prior_weight}, must be defined in the @code{estimated_params}
section.  NB: The previous  method of declaring @code{dsge_prior_weight}
as a  parameter and  then placing it  in @code{estimated_params}  is now
deprecated and will be removed in a future release of Dynare.

@item dsge_varlag = @var{INTEGER}
@anchor{dsge_varlag} The number of lags used to estimate a DSGE-VAR
model. Default: @code{4}.



@item posterior_sampling_method=@var{NAME}
@anchor{posterior_sampling_method}
Selects the sampler used to sample from the posterior distribution during Bayesian 
estimation. Default: 'random_walk_metropolis_hastings'

@table @code
@item 'random_walk_metropolis_hastings'
Instructs Dynare to use the Random-Walk Metropolis-Hastings. In this algorithm, the proposal density is
recentered to the previous draw in every step.

@item 'tailored_random_block_metropolis_hastings'
Instructs Dynare to use the Tailored randomized block (TaRB) Metropolis-Hastings algorithm 
proposed by @cite{Chib and Ramamurthy (2010)} instead of the standard Random-Walk Metropolis-Hastings. 
In this algorithm, at each iteration the estimated parameters are randomly assigned to different 
blocks. For each of these blocks a mode-finding step is conducted. The inverse Hessian at this mode 
is then used as the covariance of the proposal density for a Random-Walk Metropolis-Hastings step. 
If the numerical Hessian is not positive definite, the generalized Cholesky decomposition of 
@cite{Schnabel and Eskow (1990)} is used, but without pivoting. The TaRB-MH algorithm massively reduces 
the autocorrelation in the MH draws and thus reduces the number of draws required to 
representatively sample from the posterior. However, this comes at a computational costs as the 
algorithm takes more time to run.

@item 'independent_metropolis_hastings'
Use the Independent Metropolis-Hastings algorithm where the proposal distribution - in contrast to the
Random Walk Metropolis-Hastings algorithm - does not depend on the state of the chain.

@item 'slice'
Instructs Dynare to use the Slice sampler of @cite{Planas, Ratto, and Rossi (2015)}.
Note that @code{'slice'} is incompatible with
@code{prior_trunc=0}.

@end table


@item posterior_sampler_options = (@var{NAME}, @var{VALUE}, ...)
@anchor{posterior_sampler_options}
A list of @var{NAME} and @var{VALUE} pairs. Can be used to set options for the posterior sampling methods.
The set of available options depends on the selected posterior sampling routine 
(@i{i.e.} on the value of option @ref{posterior_sampling_method}):

@table @code

@item 'random_walk_metropolis_hastings'

Available options are:

@table @code

@item 'proposal_distribution'
@anchor{proposal_distribution}
Specifies the statistical distribution used for the proposal density.

@table @code
@item 'rand_multivariate_normal'
Use a multivariate normal distribution. This is the default.

@item 'rand_multivariate_student'
Use a multivariate student distribution

@end table

@item 'student_degrees_of_freedom'
@anchor{student_degrees_of_freedom}
Specifies the degrees of freedom to be used with the multivariate student distribution. Default: 3

@item 'use_mh_covariance_matrix'
@anchor{use_mh_covariance_matrix}
Indicates to use the covariance matrix of the draws from a previous MCMC run to define the 
covariance of the proposal distribution. Requires the @ref{load_mh_file}-option to be specified. Default: 0

@item 'scale_file'
@anchor{scale_file}
Provides the name of a @file{_mh_scale.mat}-file storing the tuned scale factor from a 
previous run of @code{mode_compute=6}

@item 'save_tmp_file'
@anchor{save_tmp_file}
Save the MCMC draws into a @code{_mh_tmp_blck}-file at the refresh rate of the status bar instead of just saving the draws
when the current @code{_mh*_blck}-file is full. Default: 0

@end table

@item 'independent_metropolis_hastings'

Takes the same options as in the case of @code{random_walk_metropolis_hastings}

@item 'slice'

@table @code

@item 'rotated'
Triggers rotated slice iterations using a covariance matrix from initial burn-in iterations. 
Requires either  @code{use_mh_covariance_matrix} or @code{slice_initialize_with_mode}. Default: 0

@item 'mode_files'
For multimodal posteriors, provide the name of a file containing a @code{nparam by nmodes} variable called 
@code{xparams} storing the different modes. This array must have one column vector per mode and the estimated 
parameters along the row dimension. With this info, 
the code will automatically trigger the @code{rotated} and @code{mode} options. Default: @code{[]}.

@item 'slice_initialize_with_mode'
The default for slice is to set @code{mode_compute = 0} and start the chain(s) from a random 
location in the prior space. This option first runs the mode-finder and then starts the
chain from the mode. Together with @code{rotated}, it will use the inverse Hessian from the 
mode to perform rotated slice iterations. Default: 0

@item 'initial_step_size'
Sets the initial size of the interval in the stepping-out procedure as fraction of the prior support
@i{i.e.} the size will be initial_step_size*(UB-LB). @code{initial_step_size} must be a real number in the interval [0, 1]. 
Default: 0.8

@item 'use_mh_covariance_matrix'
@xref{use_mh_covariance_matrix}. Must be used with @code{'rotated'}. Default: 0

@item 'save_tmp_file'
@xref{save_tmp_file}. Default: 1.

@end table

@item 'tailored_random_block_metropolis_hastings'

@table @code

@item new_block_probability = @var{DOUBLE}
Specifies the probability of the next parameter belonging to a new block when the random blocking in the TaRB 
Metropolis-Hastings algorithm is conducted. The higher this number, the smaller is the average block size and the 
more random blocks are formed during each parameter sweep. Default: @code{0.25}. 

@item mode_compute = @var{INTEGER}
Specifies the mode-finder run in every iteration for every block of the 
TaRB Metropolis-Hastings algorithm. @xref{mode_compute}. Default: @code{4}. 

@item optim = (@var{NAME}, @var{VALUE}, ...)
Specifies the options for the mode-finder used in the TaRB 
Metropolis-Hastings algorithm. @xref{optim}. 

@item 'scale_file'
@xref{scale_file}.

@item 'save_tmp_file'
@xref{save_tmp_file}. Default: 1.

@end table

@end table


@item moments_varendo
@anchor{moments_varendo} Triggers the computation of the posterior
distribution of the theoretical moments of the endogenous
variables. Results are stored in
@code{oo_.PosteriorTheoreticalMoments} (@pxref{oo_.PosteriorTheoreticalMoments}). The number of lags in the autocorrelation function is
controlled by the @code{ar} option.

@item contemporaneous_correlation
@xref{contemporaneous_correlation}. Results are stored in @code{oo_.PosteriorTheoreticalMoments}. 
Note that the @code{nocorr}-option has no effect.

@item no_posterior_kernel_density 
Shuts off the computation of the kernel density estimator for the posterior objects (@pxref{density-field}). 

@item conditional_variance_decomposition = @var{INTEGER}
See below.

@item conditional_variance_decomposition = [@var{INTEGER1}:@var{INTEGER2}]
See below.

@item conditional_variance_decomposition = [@var{INTEGER1} @var{INTEGER2} @dots{}]
Computes the posterior distribution of the conditional variance
decomposition for the specified period(s). The periods must be strictly
positive. Conditional variances are given by @math{var(y_{t+k}|t)}. For
period 1, the conditional variance decomposition provides the
decomposition of the effects of shocks upon impact. The results are
stored in
@code{oo_.PosteriorTheoreticalMoments.dsge.ConditionalVarianceDecomposition},
but currently there is no displayed output. Note that this option requires the
option @code{moments_varendo} to be specified.

@item filtered_vars
@anchor{filtered_vars} Triggers the computation of the posterior
distribution of filtered endogenous variables/one-step ahead forecasts, @i{i.e.} @math{E_{t}{y_{t+1}}}. Results are
stored in @code{oo_.FilteredVariables} (see below for a description of
this variable)

@item smoother
@anchor{smoother} Triggers the computation of the posterior distribution
of smoothed endogenous variables and shocks, @i{i.e.} the expected value of variables and shocks given the information available in all observations up to the @emph{final} date (@math{E_{T}{y_t}}). Results are stored in
@code{oo_.SmoothedVariables}, @code{oo_.SmoothedShocks} and
@code{oo_.SmoothedMeasurementErrors}.  Also triggers the computation of
@code{oo_.UpdatedVariables}, which contains the estimation of the expected value of variables given the information available at the @emph{current} date (@math{E_{t}{y_t}}).  See below for a description of all these
variables.

@item forecast = @var{INTEGER}
@anchor{forecast} Computes the posterior distribution of a forecast on
@var{INTEGER} periods after the end of the sample used in
estimation. If no Metropolis-Hastings is computed, the result is
stored in variable @code{oo_.forecast} and corresponds to the forecast
at the posterior mode. If a Metropolis-Hastings is computed, the
distribution of forecasts is stored in variables
@code{oo_.PointForecast} and
@code{oo_.MeanForecast}. @xref{Forecasting}, for a description of
these variables.

@item tex
@pxref{tex}.

@item kalman_algo = @var{INTEGER}
@anchor{kalman_algo}

@table @code

@item 0
Automatically use the Multivariate Kalman Filter for stationary models and the Multivariate Diffuse Kalman Filter for non-stationary models

@item 1
Use the Multivariate Kalman Filter

@item 2
Use the Univariate Kalman Filter

@item 3
Use the Multivariate Diffuse Kalman Filter

@item 4
Use the Univariate Diffuse Kalman Filter

@end table
@noindent
Default value is @code{0}. In case of missing observations of single or all series, Dynare treats those missing values as unobserved states and uses the Kalman filter to infer their value (see @i{e.g.} @cite{Durbin and Koopman (2012), Ch. 4.10})
This procedure has the advantage of being capable of dealing with observations where the forecast error variance matrix becomes singular for some variable(s).
If this happens, the respective observation enters with a weight of zero in the log-likelihood, @i{i.e.} this observation for the respective variable(s) is dropped
from the likelihood computations (for details see @cite{Durbin and Koopman (2012), Ch. 6.4 and 7.2.5} and @cite{Koopman and Durbin (2000)}). If the use of a multivariate Kalman filter is specified and a
singularity is encountered, Dynare by default automatically switches to the univariate Kalman filter for this parameter draw. This behavior can be changed via the
@ref{use_univariate_filters_if_singularity_is_detected} option.

@item fast_kalman_filter
@anchor{fast_kalman_filter} Select the fast Kalman filter using Chandrasekhar
recursions as described by @cite{Herbst, 2015}. This setting is only used with
@code{kalman_algo=1} or @code{kalman_algo=3}. In case of using the diffuse Kalman 
filter (@code{kalman_algo=3/lik_init=3}), the observables must be stationary. This option 
is not yet compatible with @code{analytical_derivation}.

@item kalman_tol = @var{DOUBLE}
@anchor{kalman_tol} Numerical tolerance for determining the singularity of the covariance matrix of the prediction errors during the Kalman filter (minimum allowed reciprocal of the matrix condition number). Default value is @code{1e-10}

@item diffuse_kalman_tol = @var{DOUBLE}
@anchor{diffuse_kalman_tol} Numerical tolerance for determining the singularity of the covariance matrix of the prediction errors (@math{F_{\infty}}) and the rank of the covariance matrix of the non-stationary state variables (@math{P_{\infty}}) during the Diffuse Kalman filter. Default value is @code{1e-6}

@item filter_covariance
@anchor{filter_covariance} Saves the series of one step ahead error of
forecast covariance matrices. With Metropolis, they are saved in @ref{oo_.FilterCovariance},
otherwise in @ref{oo_.Smoother.Variance}. Saves also k-step ahead error of
forecast covariance matrices if @code{filter_step_ahead} is set.

@item filter_step_ahead = [@var{INTEGER1}:@var{INTEGER2}]
See below.

@item filter_step_ahead = [@var{INTEGER1} @var{INTEGER2}  @dots{}]
@anchor{filter_step_ahead}
Triggers the computation k-step ahead filtered values, @i{i.e.} @math{E_{t}{y_{t+k}}}. Stores results in
@code{oo_.FilteredVariablesKStepAhead}. Also stores 1-step ahead values in @code{oo_.FilteredVariables}. 
@code{oo_.FilteredVariablesKStepAheadVariances} is stored if @code{filter_covariance}.
 

@item filter_decomposition
@anchor{filter_decomposition} Triggers the computation of the shock
decomposition of the above k-step ahead filtered values. Stores results in @code{oo_.FilteredVariablesShockDecomposition}.

@item smoothed_state_uncertainty
@anchor{smoothed_state_uncertainty} Triggers the computation of the variance of smoothed estimates, @i{i.e.}
@code{Var_T(y_t)}. Stores results in @code{oo_.Smoother.State_uncertainty}.

@item diffuse_filter
@anchor{diffuse_filter}
Uses the diffuse Kalman filter (as described in
@cite{Durbin and Koopman (2012)} and @cite{Koopman and Durbin
(2003)} for the multivariate and @cite{Koopman and Durbin
(2000)} for the univariate filter) to estimate models with non-stationary observed variables.

When @code{diffuse_filter} is used the @code{lik_init} option of
@code{estimation} has no effect.

When there  are nonstationary exogenous variables in  a model, there is  no unique deterministic  steady state.  For instance,  if productivity  is a  pure random walk:

@math{a_t = a_{t-1} + e_t}

any value of  @math{\bar a} of @math{a} is a  deterministic steady state for productivity.  Consequently, the  model admits  an infinity  of steady states. In this situation, the user must help Dynare in selecting one steady state, except if zero is a trivial model's steady state, which happens when the @code{linear} option is used in the model declaration. The user can either provide the steady state to Dynare using a @code{steady_state_model} block (or writing a steady state file) if a closed form solution is available, @pxref{steady_state_model}, or specify some constraints on the steady state, @pxref{equation_tag_for_conditional_steady_state}, so that Dynare computes the steady state conditionally on some predefined levels for the non stationary variables. In both cases, the idea is to use dummy values for the steady state level of the exogenous non stationary variables.

Note that the nonstationary variables in the model must be integrated processes (their first difference or k-difference must be stationary).

@item selected_variables_only
@anchor{selected_variables_only}
Only run the classical smoother on the variables listed just after the
@code{estimation} command. This option is incompatible with requesting classical 
frequentist forecasts and will be overridden in this case. When using Bayesian estimation,
the smoother is by default only run on the declared endogenous variables.
Default: run the smoother on all the
declared endogenous variables.

@item cova_compute = @var{INTEGER}
When @code{0}, the covariance matrix of estimated parameters is not
computed after the computation of posterior mode (or maximum
likelihood). This increases speed of computation in large models
during development, when this information is not always necessary. Of
course, it will break all successive computations that would require
this covariance matrix. Otherwise, if this option is equal to
@code{1}, the covariance matrix is computed and stored in variable
@code{hh} of @file{@var{MODEL_FILENAME}_mode.mat}. Default is @code{1}.

@item solve_algo = @var{INTEGER}
@xref{solve_algo}.

@item order = @var{INTEGER}
Order of approximation, either @code{1} or @code{2}. When equal to
@code{2}, the likelihood is evaluated with a particle filter based on
a second order approximation of the model (see
@cite{Fernandez-Villaverde and Rubio-Ramirez (2005)}).  Default is
@code{1}, ie the likelihood of the linearized model is evaluated
using a standard Kalman filter.

@item irf = @var{INTEGER}
@xref{irf}. Only used if @ref{bayesian_irf} is passed.

@item irf_shocks = ( @var{VARIABLE_NAME} [[,] @var{VARIABLE_NAME} @dots{}] )
@xref{irf_shocks}. Only used if @ref{bayesian_irf} is passed.

@item irf_plot_threshold = @var{DOUBLE}
@xref{irf_plot_threshold}. Only used if @ref{bayesian_irf} is passed.

@item aim_solver
@xref{aim_solver}.

@item sylvester = OPTION
@xref{sylvester}.

@item sylvester_fixed_point_tol = @var{DOUBLE}
@xref{sylvester_fixed_point_tol}.

@item lyapunov = @var{OPTION}
@anchor{lyapunov}
Determines the algorithm used to solve the Lyapunov equation to initialized the variance-covariance matrix of the Kalman filter using the steady-state value of state variables. Possible values for @code{@var{OPTION}} are:

@table @code

@item default
Uses the default solver for Lyapunov equations based on Bartels-Stewart algorithm.

@item fixed_point
Uses a fixed point algorithm to solve the Lyapunov equation. This method is faster than the @code{default} one for large scale models, but it could require a large amount of iterations.

@item doubling
Uses a doubling algorithm to solve the Lyapunov equation (@code{disclyap_fast}). This method is faster than the two previous one for large scale models.


@item square_root_solver
Uses a square-root solver for Lyapunov equations
(@code{dlyapchol}). This method is fast for large scale models
(available under MATLAB if the control system toolbox is installed;
available under Octave if the
@uref{http://octave.sourceforge.net/control/,control} package from
Octave-Forge is installed)

@end table

@noindent
Default value is @code{default}

@item lyapunov_fixed_point_tol = @var{DOUBLE}
@anchor{lyapunov_fixed_point_tol}
This is the convergence criterion used in the fixed point Lyapunov solver. Its default value is 1e-10.

@item lyapunov_doubling_tol = @var{DOUBLE}
@anchor{lyapunov_doubling_tol}
This is the convergence criterion used in the doubling algorithm to solve the Lyapunov equation. Its default value is 1e-16.

@item use_penalized_objective_for_hessian
Use the penalized objective instead of the objective function to compute
numerically the hessian matrix at the mode. The penalties decrease the value of
the posterior density (or likelihood) when, for some perturbations, Dynare is
not able to solve the model (issues with steady state existence, Blanchard and
Kahn conditions, ...). In pratice, the penalized and original
objectives will only differ if the posterior mode is found to be near a region
where the model is ill-behaved. By default the original objective function is
used.

@item analytic_derivation
Triggers estimation with analytic gradient. The final hessian is also
computed analytically. Only works for stationary models without
missing observations.

@item ar = @var{INTEGER}
@xref{ar}. Only useful in conjunction with option @code{moments_varendo}.

@item endogenous_prior
Use endogenous priors as in @cite{Christiano, Trabandt and Walentin
(2011)}. 
The procedure is motivated by sequential Bayesian learning.  Starting from independent initial priors on the parameters, 
specified in the @code{estimated_params}-block, the standard deviations observed in a "pre-sample", 
taken to be the actual sample, are used to update the initial priors. Thus, the product of the initial 
priors and the pre-sample likelihood of the standard deviations of the observables is used as the new prior 
(for more information, see the technical appendix of @cite{Christiano, Trabandt and Walentin (2011)}). 
This procedure helps in cases where the regular posterior estimates, which minimize in-sample forecast 
errors, result in a large overprediction 
of model variable variances (a statistic that is not explicitly targeted, but often of particular interest to researchers).

@item use_univariate_filters_if_singularity_is_detected = @var{INTEGER}
@anchor{use_univariate_filters_if_singularity_is_detected}
Decide whether Dynare should automatically switch to univariate filter
if a singularity is encountered in the likelihood computation (this is
the behaviour if the option is equal to @code{1}). Alternatively, if
the option is equal to @code{0}, Dynare will not automatically change
the filter, but rather use a penalty value for the likelihood when
such a singularity is encountered. Default: @code{1}.

@item keep_kalman_algo_if_singularity_is_detected
@anchor{keep_kalman_algo_if_singularity_is_detected}
With the default @ref{use_univariate_filters_if_singularity_is_detected}=1, Dynare will switch 
to the univariate Kalman filter when it encounters a singular forecast error variance
matrix during Kalman filtering. Upon encountering such a singularity for the first time, all subsequent
parameter draws and computations will automatically rely on univariate filter, @i{i.e.} Dynare will never try 
the multivariate filter again. Use the @code{keep_kalman_algo_if_singularity_is_detected} option to have the 
@code{use_univariate_filters_if_singularity_is_detected} only affect the behavior for the current draw/computation.

@item rescale_prediction_error_covariance
@anchor{rescale_prediction_error_covariance}
Rescales the prediction error covariance in the Kalman filter to avoid badly scaled matrix and reduce the probability of a switch to univariate Kalman filters (which are slower). By default no rescaling is done.

@item qz_zero_threshold = @var{DOUBLE}
@xref{qz_zero_threshold}.

@item taper_steps = [@var{INTEGER1} @var{INTEGER2} @dots{}]
@anchor{taper_steps}
Percent tapering used for the spectral window in the @cite{Geweke (1992,1999)}
convergence diagnostics (requires @ref{mh_nblocks}=1). The tapering is used to
take the serial correlation of the posterior draws into account. Default: @code{[4 8 15]}.

@item geweke_interval = [@var{DOUBLE} @var{DOUBLE}]
@anchor{geweke_interval}
Percentage of MCMC draws at the beginning and end of the MCMC chain taken
to compute the @cite{Geweke (1992,1999)} convergence diagnostics (requires @ref{mh_nblocks}=1)
after discarding the first @ref{mh_drop} percent of draws as a burnin. Default: @code{[0.2 0.5]}.

@item raftery_lewis_diagnostics
@anchor{raftery_lewis_diagnostics}
Triggers the computation of the @cite{Raftery and Lewis (1992)} convergence diagnostics. The goal is deliver the number of draws 
required to estimate a particular quantile of the CDF @code{q} with precision @code{r} with a probability @code{s}. Typically, one wants to estimate
the @code{q=0.025} percentile (corresponding to a 95 percent HPDI) with a precision of 0.5 percent (@code{r=0.005}) with 95 percent 
certainty (@code{s=0.95}). The defaults can be changed via @ref{raftery_lewis_qrs}. Based on the 
theory of first order Markov Chains, the diagnostics will provide a required burn-in (@code{M}), the number of draws after the burnin (@code{N}) 
as well as a thinning factor that would deliver a first order chain (@code{k}). The last line of the table will also deliver the maximum over 
all parameters for the respective values.

@item raftery_lewis_qrs = [@var{DOUBLE} @var{DOUBLE} @var{DOUBLE}]
@anchor{raftery_lewis_qrs}
Sets the quantile of the CDF @code{q} that is estimated with precision @code{r} with a probability @code{s} in the 
@cite{Raftery and Lewis (1992)} convergence diagnostics. Default: @code{[0.025 0.005 0.95]}.

@item consider_all_endogenous
Compute the posterior moments, smoothed variables, k-step ahead
filtered variables and forecasts (when requested) on all the
endogenous variables. This is equivalent to manually listing all the
endogenous variables after the @code{estimation} command.

@item consider_only_observed
Compute the posterior moments, smoothed variables, k-step ahead
filtered variables and forecasts (when requested) on all the observed
variables. This is equivalent to manually listing all the observed
variables after the @code{estimation} command.

@item number_of_particles = @var{INTEGER}
@anchor{number_of_particles}
Number of particles used when evaluating the likelihood of a non linear state space model. Default: @code{1000}.

@item resampling = @var{OPTION}
@anchor{resampling}
Determines if resampling of the particles is done. Possible values for @var{OPTION} are:

@table @code

@item none
No resampling.

@item systematic
Resampling at each iteration, this is the default value.

@item generic
Resampling if and only if the effective sample size is below a certain level defined by @ref{resampling_threshold}*@ref{number_of_particles}.

@end table

@item resampling_threshold = @var{DOUBLE}
@anchor{resampling_threshold}
A real number between zero and one. The resampling step is triggered as soon as the effective number of particles is less than this number times the total number of particles (as set by @ref{number_of_particles}). This option is effective if and only if option @ref{resampling} has value @code{generic}.

@item resampling_method = @var{OPTION}
@anchor{resampling_method}
Sets the resampling method. Possible values for @var{OPTION} are: @code{kitagawa}, @code{stratified} and @code{smooth}.

@item filter_algorithm = @var{OPTION}
@anchor{filter_algorithm}
Sets the particle filter algorithm. Possible values for @var{OPTION} are:

@table @code

@item sis
Sequential importance sampling algorithm, this is the default value.

@item apf
Auxiliary particle filter.

@item gf
Gaussian filter.

@item gmf
Gaussian mixture filter.

@item cpf
Conditional particle filter.

@item nlkf
Use a standard (linear) Kalman filter algorithm with the nonlinear measurement and state equations.

@end table

@item proposal_approximation = @var{OPTION}
@anchor{proposal_approximation}
Sets the method for approximating the proposal distribution. Possible values for @var{OPTION} are: @code{cubature}, @code{montecarlo} and @code{unscented}. Default value is @code{unscented}.

@item distribution_approximation = @var{OPTION}
@anchor{distribution_approximation}
Sets the method for approximating the particle distribution. Possible values for @var{OPTION} are: @code{cubature}, @code{montecarlo} and @code{unscented}. Default value is @code{unscented}.

@item cpf_weights = @var{OPTION}
@anchor{cpf_weights} Controls the method used to update the weights in conditional particle filter, possible values are @code{amisanotristani} (@cite{Amisano et al (2010)}) or @code{murrayjonesparslow} (@cite{Murray et al. (2013)}). Default value is @code{amisanotristani}.

@item nonlinear_filter_initialization = @var{INTEGER}
@anchor{nonlinear_filter_initialization} Sets the initial condition of the
nonlinear filters. By default the nonlinear filters are initialized with the
unconditional covariance matrix of the state variables, computed with the
reduced form solution of the first order approximation of the model. If
@code{nonlinear_filter_initialization=2}, the nonlinear filter is instead
initialized with a covariance matrix estimated with a stochastic simulation of
the reduced form solution of the second order approximation of the model. Both
these initializations assume that the model is stationary, and cannot be used
if the model has unit roots (which can be seen with the @ref{check} command
prior to estimation). If the model has stochastic trends, user must use
@code{nonlinear_filter_initialization=3}, the filters are then initialized with
an identity matrix for the covariance matrix of the state variables. Default
value is @code{nonlinear_filter_initialization=1} (initialization based on the
first order approximation of the model).

@end table


@customhead{Note}

If no @code{mh_jscale} parameter is used for a parameter in @code{estimated_params}, 
the procedure uses @code{mh_jscale} for all parameters. If
@code{mh_jscale} option isn't set, the procedure uses @code{0.2} for
all parameters. Note that if @code{mode_compute=6} is used or the @code{posterior_sampler_option} 
called @code{scale_file} is specified, the values set in @code{estimated_params}
will be overwritten.

@customhead{``Endogenous'' prior restrictions}

It is also possible to impose implicit ``endogenous'' priors about IRFs and moments on the model during 
estimation. For example, one can specify that all valid parameter draws for the model must generate fiscal multipliers that are
bigger than 1 by specifying how the IRF to a government spending shock must look like. The prior restrictions can be imposed
via @code{irf_calibration} and @code{moment_calibration} blocks (@pxref{IRF/Moment calibration}). The way it works internally is that 
any parameter draw that is inconsistent with the ``calibration'' provided in these blocks is discarded, @i{i.e.} assigned a prior density of 0. 
When specifying these blocks, it is important to keep in mind that one won't be able to easily do @code{model_comparison} in this case, 
because the prior density will not integrate to 1.

@outputhead

@vindex M_.params
@vindex M_.Sigma_e
After running @code{estimation}, the parameters @code{M_.params} and
the variance matrix @code{M_.Sigma_e} of the shocks are set to the
mode for maximum likelihood estimation or posterior mode computation
without Metropolis iterations.

After @code{estimation} with Metropolis iterations (option
@code{mh_replic} > 0 or option @code{load_mh_file} set) the parameters
@code{M_.params} and the variance matrix @code{M_.Sigma_e} of the
shocks are set to the posterior mean.

Depending on the options, @code{estimation} stores results in various
fields of the @code{oo_} structure, described below.

@end deffn

In the following variables, we will adopt the following shortcuts for
specific field names:

@table @var

@item MOMENT_NAME

This field can take the following values:

@table @code

@item HPDinf
Lower bound of a 90% HPD interval@footnote{See option @ref{conf_sig}
to change the size of the HPD interval}

@item HPDsup
Upper bound of a 90% HPD interval

@item HPDinf_ME
Lower bound of a 90% HPD interval@footnote{See option @ref{conf_sig}
to change the size of the HPD interval} for observables when taking 
measurement error into account (see @i{e.g.} @cite{Christoffel et al. (2010), p.17}).

@item HPDsup_ME
Upper bound of a 90% HPD interval for observables when taking 
measurement error into account

@item Mean
Mean of the posterior distribution

@item Median
Median of the posterior distribution

@item Std
Standard deviation of the posterior distribution

@item Variance
Variance of the posterior distribution

@item deciles
Deciles of the distribution.

@item density
@anchor{density-field}
Non parametric estimate of the posterior density following the approach outlined in @cite{Skoeld and Roberts (2003)}. First and second
columns are respectively abscissa and ordinate coordinates. 

@end table

@item ESTIMATED_OBJECT

This field can take the following values:

@table @code

@item measurement_errors_corr
Correlation between two measurement errors

@item measurement_errors_std
Standard deviation of measurement errors

@item parameters
Parameters

@item shocks_corr
Correlation between two structural shocks

@item shocks_std
Standard deviation of structural shocks

@end table
@end table


@defvr {MATLAB/Octave variable} oo_.MarginalDensity.LaplaceApproximation
Variable set by the @code{estimation} command. Stores the marginal data density 
based on the Laplace Approximation.
@end defvr

@defvr {MATLAB/Octave variable} oo_.MarginalDensity.ModifiedHarmonicMean
Variable set by the @code{estimation} command, if it is used with
@code{mh_replic > 0} or @code{load_mh_file} option. Stores the marginal data density 
based on @cite{Geweke (1999)} Modified Harmonic Mean estimator.
@end defvr

@defvr {MATLAB/Octave variable} oo_.posterior.optimization
Variable set by the @code{estimation} command if mode-finding is used. Stores the results at the mode. 
Fields are of the form 
@example
@code{oo_.posterior.optimization.@var{OBJECT}}
@end example

where @var{OBJECT} is one of the following:

@table @code

@item mode
Parameter vector at the mode

@item Variance
Inverse Hessian matrix at the mode or MCMC jumping covariance matrix when used with the 
@ref{MCMC_jumping_covariance} option

@item log_density
Log likelihood (ML)/log posterior density (Bayesian) at the mode when used with @code{mode_compute>0}

@end table

@end defvr

@defvr {MATLAB/Octave variable} oo_.posterior.metropolis
Variable set by the @code{estimation} command if @code{mh_replic>0} is used. 
Fields are of the form 
@example
@code{oo_.posterior.metropolis.@var{OBJECT}}
@end example

where @var{OBJECT} is one of the following:

@table @code

@item mean
Mean parameter vector from the MCMC

@item Variance
Covariance matrix of the parameter draws in the MCMC 

@end table

@end defvr

@defvr {MATLAB/Octave variable} oo_.FilteredVariables
Variable set by the @code{estimation} command, if it is used with the
@code{filtered_vars} option.

After an estimation without Metropolis, fields are of the form:
@example
@code{oo_.FilteredVariables.@var{VARIABLE_NAME}}
@end example


After an estimation with Metropolis, fields are of the form:
@example
@code{oo_.FilteredVariables.@var{MOMENT_NAME}.@var{VARIABLE_NAME}}
@end example
@end defvr

@defvr {MATLAB/Octave variable} oo_.FilteredVariablesKStepAhead
Variable set by the @code{estimation} command, if it is used with the
@code{filter_step_ahead} option. The k-steps are stored along the rows while the columns 
indicate the respective variables. The third dimension of the array provides the
observation for which the forecast has been made. For example, if @code{filter_step_ahead=[1 2 4]} 
and @code{nobs=200}, the element (3,5,204) stores the four period ahead filtered 
value of variable 5 computed at time t=200 for time t=204. The periods at the beginning 
and end of the sample for which no forecasts can be made, @i{e.g.} entries (1,5,1) and 
(1,5,204) in the example, are set to zero. Note that in case of Bayesian estimation 
the variables will be ordered in the order of declaration after the estimation 
command (or in general declaration order if no variables are specified here). In case 
of running the classical smoother, the variables will always be ordered in general 
declaration order. If the @ref{selected_variables_only} option is specified with the classical smoother, 
non-requested variables will be simply left out in this order.
@end defvr

@defvr {MATLAB/Octave variable} oo_.FilteredVariablesKStepAheadVariances
Variable set by the @code{estimation} command, if it is used with the
@code{filter_step_ahead} option. It is a 4 dimensional array where the k-steps 
are stored along the first dimension, while the fourth dimension of the array 
provides the observation for which the forecast has been made. The second and third 
dimension provide the respective variables. 
For example, if @code{filter_step_ahead=[1 2 4]} and @code{nobs=200}, the element (3,4,5,204) 
stores the four period ahead forecast error covariance between variable 4 and variable 5, 
computed at time t=200 for time t=204. Padding with zeros and variable ordering is analogous to @code{oo_.FilteredVariablesKStepAhead}. 
@end defvr

@defvr {MATLAB/Octave variable} oo_.Filtered_Variables_X_step_ahead
Variable set by the @code{estimation} command, if it is used with the @code{filter_step_ahead} option in the context of Bayesian estimation. Fields are of the form:
@example
@code{oo_.Filtered_Variables_X_step_ahead.@var{VARIABLE_NAME}}
@end example
The nth entry stores the k-step ahead filtered variable computed at time n for time n+k.
@end defvr

@defvr {MATLAB/Octave variable} oo_.FilteredVariablesShockDecomposition
Variable set by the @code{estimation} command, if it is used with the
@code{filter_step_ahead} option. The k-steps are stored along the rows while the columns 
indicate the respective variables.  The third dimension corresponds to the shocks in declaration order. 
The fourth dimension of the array provides the
observation for which the forecast has been made. For example, if @code{filter_step_ahead=[1 2 4]} 
and @code{nobs=200}, the element (3,5,2,204) stores the contribution of the second shock to the 
four period ahead filtered value of variable 5 (in deviations from the mean) computed at time t=200 for time t=204. The periods at the beginning 
and end of the sample for which no forecasts can be made, @i{e.g.} entries (1,5,1) and 
(1,5,204) in the example, are set to zero. Padding with zeros and variable ordering is analogous to 
@code{oo_.FilteredVariablesKStepAhead}. 
@end defvr


@defvr {MATLAB/Octave variable} oo_.PosteriorIRF.dsge
Variable set by the @code{estimation} command, if it is used with the
@code{bayesian_irf} option. Fields are of the form:
@example
@code{oo_.PosteriorIRF.dsge.@var{MOMENT_NAME}.@var{VARIABLE_NAME}_@var{SHOCK_NAME}}
@end example
@end defvr

@defvr {MATLAB/Octave variable} oo_.SmoothedMeasurementErrors
Variable set by the @code{estimation} command, if it is used with the
@code{smoother} option. Fields are of the form:
@example
@code{oo_.SmoothedMeasurementErrors.@var{VARIABLE_NAME}}
@end example
@end defvr

@defvr {MATLAB/Octave variable} oo_.SmoothedShocks
Variable set by the @code{estimation} command (if used with the
@code{smoother} option), or by the @code{calib_smoother} command.

After an estimation without Metropolis, or if computed by
@code{calib_smoother}, fields are of the form:
@example
@code{oo_.SmoothedShocks.@var{VARIABLE_NAME}}
@end example

After an estimation with Metropolis, fields are of the form:
@example
@code{oo_.SmoothedShocks.@var{MOMENT_NAME}.@var{VARIABLE_NAME}}
@end example

@end defvr

@defvr {MATLAB/Octave variable} oo_.SmoothedVariables
Variable set by the @code{estimation} command (if used with the
@code{smoother} option), or by the @code{calib_smoother} command.

After an estimation without Metropolis, or if computed by
@code{calib_smoother}, fields are of the form:
@example
@code{oo_.SmoothedVariables.@var{VARIABLE_NAME}}
@end example

After an estimation with Metropolis, fields are of the form:
@example
@code{oo_.SmoothedVariables.@var{MOMENT_NAME}.@var{VARIABLE_NAME}}
@end example
@end defvr

@defvr {MATLAB/Octave variable} oo_.UpdatedVariables
Variable set by the @code{estimation} command (if used with the
@code{smoother} option), or by the @code{calib_smoother} command.
Contains the estimation of the expected value of variables given the
information available at the @emph{current} date.

After an estimation without Metropolis, or if computed by
@code{calib_smoother}, fields are of the form:
@example
@code{oo_.UpdatedVariables.@var{VARIABLE_NAME}}
@end example

After an estimation with Metropolis, fields are of the form:
@example
@code{oo_.UpdatedVariables.@var{MOMENT_NAME}.@var{VARIABLE_NAME}}
@end example
@end defvr

@defvr {MATLAB/Octave variable} oo_.FilterCovariance
@anchor{oo_.FilterCovariance}
Three-dimensional array set by the @code{estimation} command if used with the
@code{smoother} and Metropolis, if the @code{filter_covariance} option
has been requested.
Contains the series of one-step ahead forecast error covariance matrices
from the Kalman smoother. The @code{M_.endo_nbr} times @code{M_.endo_nbr} times
@code{T+1} array contains the variables in declaration order along the first 
two dimensions. The third dimension of the array provides the
observation for which the forecast has been made.
Fields are of the form:
@example
@code{oo_.FilterCovariance.@var{MOMENT_NAME}}
@end example
Note that density estimation is not supported.
@end defvr

@defvr {MATLAB/Octave variable} oo_.Smoother.Variance
@anchor{oo_.Smoother.Variance}
Three-dimensional array set by the @code{estimation} command (if used with the
@code{smoother}) without Metropolis, 
or by the @code{calib_smoother} command, if the @code{filter_covariance} option
has been requested.
Contains the series of one-step ahead forecast error covariance matrices
from the Kalman smoother. The @code{M_.endo_nbr} times @code{M_.endo_nbr} times
@code{T+1} array contains the variables in declaration order along the first 
two dimensions. The third dimension of the array provides the
observation for which the forecast has been made.
@end defvr

@defvr {MATLAB/Octave variable} oo_.Smoother.State_uncertainty
@anchor{oo_.Smoother.State_uncertainty}
Three-dimensional array set by the @code{estimation} command (if used with the
@code{smoother}) without Metropolis, 
or by the @code{calib_smoother} command, if the @code{o_smoothed_state_uncertainty} option
has been requested.
Contains the series of covariance matrices for the state estimate given the full data
from the Kalman smoother. The @code{M_.endo_nbr} times @code{M_.endo_nbr} times
@code{T} array contains the variables in declaration order along the first 
two dimensions. The third dimension of the array provides the
observation for which the smoothed estimate has been made.
@end defvr

@defvr {MATLAB/Octave variable} oo_.Smoother.SteadyState
@anchor{oo_.Smoother.SteadyState}
Variable set by the @code{estimation} command (if used with the
@code{smoother}) without Metropolis, 
or by the @code{calib_smoother} command.
Contains the steady state component of the endogenous variables used in the
smoother in order of variable declaration.
@end defvr

@defvr {MATLAB/Octave variable} oo_.Smoother.TrendCoeffs
@anchor{oo_.Smoother.TrendCoeffs}
Variable set by the @code{estimation} command (if used with the
@code{smoother}) without Metropolis, 
or by the @code{calib_smoother} command.
Contains the trend coefficients of the observed variables used in the
smoother in order of declaration of the observed variables.
@end defvr

@defvr {MATLAB/Octave variable} oo_.Smoother.Trend
Variable set by the @code{estimation} command (if used with the
@code{smoother} option), or by the @code{calib_smoother} command.
Contains the trend component of the variables used in the
smoother.

Fields are of the form:
@example
@code{oo_.Smoother.Trend.@var{VARIABLE_NAME}}
@end example
@end defvr

@defvr {MATLAB/Octave variable} oo_.Smoother.Constant
Variable set by the @code{estimation} command (if used with the
@code{smoother} option), or by the @code{calib_smoother} command.
Contains the constant part of the endogenous variables used in the
smoother, accounting @i{e.g.} for the data mean when using the @code{prefilter}
option.

Fields are of the form:
@example
@code{oo_.Smoother.Constant.@var{VARIABLE_NAME}}
@end example
@end defvr

@defvr {MATLAB/Octave variable} oo_.Smoother.loglinear
Indicator keeping track of whether the smoother was run with the @ref{loglinear} option 
and thus whether stored smoothed objects are in logs.
@end defvr

@defvr {MATLAB/Octave variable} oo_.PosteriorTheoreticalMoments
@anchor{oo_.PosteriorTheoreticalMoments}
Variable set by the @code{estimation} command, if it is used with the
@code{moments_varendo} option. Fields are of the form:
@example
@code{oo_.PosteriorTheoreticalMoments.dsge.@var{THEORETICAL_MOMENT}.@var{ESTIMATED_OBJECT}.@var{MOMENT_NAME}.@var{VARIABLE_NAME}}
@end example
where @var{THEORETICAL_MOMENT} is one of the following:

@table @code

@item covariance
Variance-covariance of endogenous variables

@item contemporaneous_correlation
Contemporaneous correlation of endogenous variables when the @ref{contemporaneous_correlation} option is specified.

@item correlation
Auto- and cross-correlation of endogenous variables. Fields are vectors with correlations from 1 up to order @code{options_.ar}


@item VarianceDecomposition
Decomposition of variance (unconditional variance, @i{i.e.} at horizon infinity)@footnote{When the shocks are correlated, it
is the decomposition of orthogonalized shocks via Cholesky
decomposition according to the order of declaration of shocks
(@pxref{Variable declarations})}

@item ConditionalVarianceDecomposition
Only if the @code{conditional_variance_decomposition} option has been
specified

@end table

@end defvr

@defvr {MATLAB/Octave variable} oo_.posterior_density
Variable set by the @code{estimation} command, if it is used with
@code{mh_replic > 0} or @code{load_mh_file} option. Fields are of the form:
@example
@code{oo_.posterior_density.@var{PARAMETER_NAME}}
@end example
@end defvr

@defvr {MATLAB/Octave variable} oo_.posterior_hpdinf
Variable set by the @code{estimation} command, if it is used with
@code{mh_replic > 0} or @code{load_mh_file} option. Fields are of the form:
@example
@code{oo_.posterior_hpdinf.@var{ESTIMATED_OBJECT}.@var{VARIABLE_NAME}}
@end example
@end defvr

@defvr {MATLAB/Octave variable} oo_.posterior_hpdsup
Variable set by the @code{estimation} command, if it is used with
@code{mh_replic > 0} or @code{load_mh_file} option. Fields are of the form:
@example
@code{oo_.posterior_hpdsup.@var{ESTIMATED_OBJECT}.@var{VARIABLE_NAME}}
@end example
@end defvr

@defvr {MATLAB/Octave variable} oo_.posterior_mean
Variable set by the @code{estimation} command, if it is used with
@code{mh_replic > 0} or @code{load_mh_file} option. Fields are of the form:
@example
@code{oo_.posterior_mean.@var{ESTIMATED_OBJECT}.@var{VARIABLE_NAME}}
@end example
@end defvr

@defvr {MATLAB/Octave variable} oo_.posterior_mode
Variable set by the @code{estimation} command during mode-finding. Fields are 
of the form:
@example
@code{oo_.posterior_mode.@var{ESTIMATED_OBJECT}.@var{VARIABLE_NAME}}
@end example
@end defvr

@defvr {MATLAB/Octave variable} oo_.posterior_std_at_mode
Variable set by the @code{estimation} command during mode-finding. It is based on the
inverse Hessian at @code{oo_.posterior_mode}. Fields are 
of the form:
@example
@code{oo_.posterior_std_at_mode.@var{ESTIMATED_OBJECT}.@var{VARIABLE_NAME}}
@end example
@end defvr

@defvr {MATLAB/Octave variable} oo_.posterior_std
Variable set by the @code{estimation} command, if it is used with
@code{mh_replic > 0} or @code{load_mh_file} option. Fields are of the form:
@example
@code{oo_.posterior_std.@var{ESTIMATED_OBJECT}.@var{VARIABLE_NAME}}
@end example
@end defvr

@defvr {MATLAB/Octave variable} oo_.posterior_var
Variable set by the @code{estimation} command, if it is used with
@code{mh_replic > 0} or @code{load_mh_file} option. Fields are of the form:
@example
@code{oo_.posterior_var.@var{ESTIMATED_OBJECT}.@var{VARIABLE_NAME}}
@end example
@end defvr

@defvr {MATLAB/Octave variable} oo_.posterior_median
Variable set by the @code{estimation} command, if it is used with
@code{mh_replic > 0} or @code{load_mh_file} option. Fields are of the form:
@example
@code{oo_.posterior_median.@var{ESTIMATED_OBJECT}.@var{VARIABLE_NAME}}
@end example
@end defvr

Here are some examples of generated variables:

@example
oo_.posterior_mode.parameters.alp
oo_.posterior_mean.shocks_std.ex
oo_.posterior_hpdsup.measurement_errors_corr.gdp_conso
@end example

@defvr {MATLAB/Octave variable} oo_.dsge_var.posterior_mode
@anchor{oo_.dsge_var.posterior_mode}
Structure set by the @code{dsge_var} option of the @code{estimation} command after @code{mode_compute}.

The following fields are saved:

@table @code

@item PHI_tilde
Stacked posterior DSGE-BVAR autoregressive matrices at the mode (equation (28) of 
@cite{Del Negro and Schorfheide (2004)}).

@item SIGMA_u_tilde
Posterior covariance matrix of the DSGE-BVAR at the mode (equation (29) of 
@cite{Del Negro and Schorfheide (2004)}).

@item iXX
Posterior population moments in the DSGE-BVAR at the mode (@math{inv(\lambda T \Gamma_{XX}^*+ X'X)}).

@item prior
Structure storing the DSGE-BVAR prior.

@table @code


@item PHI_star
Stacked prior DSGE-BVAR autoregressive matrices at the mode (equation (22) of 
@cite{Del Negro and Schorfheide (2004)}).

@item SIGMA_star
Prior covariance matrix of the DSGE-BVAR at the mode (equation (23) of 
@cite{Del Negro and Schorfheide (2004)}).

@item ArtificialSampleSize
Size of the artifical prior sample (@math{inv(\lambda T)}).

@item DF
Prior degrees of freedom (@math{inv(\lambda T-k-n)}).

@item iGXX_star
Inverse of the theoretical prior ``covariance'' between X and X (@math{\Gamma_{xx}^*} in @cite{Del Negro and Schorfheide (2004)}).

@end table

@end table

@end defvr


@defvr {MATLAB/Octave variable} oo_.RecursiveForecast
@anchor{RecursiveForecast}
Variable set by the @code{forecast} option of the @code{estimation} command when used with the nobs = [@var{INTEGER1}:@var{INTEGER2}] option (@pxref{nobs1,,nobs}).

Fields are of the form:
@example
@code{oo_.RecursiveForecast.@var{FORECAST_OBJECT}.@var{VARIABLE_NAME}}
@end example
where @var{FORECAST_OBJECT} is one of the following@footnote{See @ref{forecast} for more information}:

@table @code

@item Mean
Mean of the posterior forecast distribution

@item HPDinf/HPDsup
Upper/lower bound of the 90% HPD interval taking into account only parameter uncertainty (corresponding to @ref{oo_.MeanForecast})

@item HPDTotalinf/HPDTotalsup
Upper/lower bound of the 90% HPD interval taking into account both parameter and future shock uncertainty (corresponding to @ref{oo_.PointForecast})

@end table

@var{VARIABLE_NAME} contains a matrix of the following size: number of time periods for which forecasts are requested using the nobs = [@var{INTEGER1}:@var{INTEGER2}] option times the number of forecast horizons requested by the @code{forecast} option. @i{i.e.}, the row indicates the period at which the forecast is performed and the column the respective k-step ahead forecast. The starting periods are sorted in ascending order, not in declaration order.

@end defvr

@defvr {MATLAB/Octave variable} oo_.convergence.geweke
@anchor{convergence.geweke}
Variable set by the convergence diagnostics of the @code{estimation} command when used with @ref{mh_nblocks}=1 option (@pxref{mh_nblocks}).

Fields are of the form:
@example
@code{oo_.convergence.geweke.@var{VARIABLE_NAME}.@var{DIAGNOSTIC_OBJECT}}
@end example
where @var{DIAGNOSTIC_OBJECT} is one of the following:

@table @code

@item posteriormean
Mean of the posterior parameter distribution

@item posteriorstd
Standard deviation of the posterior parameter distribution

@item nse_iid
Numerical standard error (NSE) under the assumption of iid draws

@item rne_iid
Relative numerical efficiency (RNE) under the assumption of iid draws

@item nse_x
Numerical standard error (NSE) when using an x% taper

@item rne_x
Relative numerical efficiency (RNE) when using an x% taper

@item pooled_mean
Mean of the parameter when pooling the beginning and end parts of the chain
specified in @ref{geweke_interval} and weighting them with their relative precision.
It is a vector containing the results under the iid assumption followed by the ones
using the @ref{taper_steps} (@pxref{taper_steps}).

@item pooled_nse
NSE of the parameter when pooling the beginning and end parts of the chain and weighting them with their relative precision. See @code{pooled_mean}

@item prob_chi2_test
p-value of a chi squared test for equality of means in the beginning and the end
of the MCMC chain. See @code{pooled_mean}. A value above 0.05 indicates that
the null hypothesis of equal means and thus convergence cannot be rejected
at the 5 percent level. Differing values along the @ref{taper_steps} signal
the presence of significant autocorrelation in draws. In this case, the
estimates using a higher tapering are usually more reliable.

@end table
@end defvr

@deffn Command unit_root_vars @var{VARIABLE_NAME}@dots{};

This command is deprecated. Use @code{estimation} option @code{diffuse_filter} instead for estimating a model with non-stationary observed variables or @code{steady} option @code{nocheck} to prevent @code{steady} to check the steady state returned by your steady state file.
@end deffn

Dynare also has the ability to estimate Bayesian VARs:

@deffn Command bvar_density ;
Computes the marginal density of an estimated BVAR model, using
Minnesota priors.

See @file{bvar-a-la-sims.pdf}, which comes with Dynare distribution,
for more information on this command.
@end deffn

@node Model Comparison
@section Model Comparison

@deffn Command model_comparison @var{FILENAME}[(@var{DOUBLE})]@dots{};
@deffnx Command model_comparison (marginal_density = laplace | modifiedharmonicmean) @var{FILENAME}[(@var{DOUBLE})]@dots{};
@anchor{model_comparison}
@descriptionhead

This command computes odds ratios and estimate a posterior density over a
collection of models (see @i{e.g.} @cite{Koop (2003), Ch. 1}). The priors over
models can be specified as the @var{DOUBLE} values, otherwise a uniform prior
over all models is assumed.  In contrast to frequentist econometrics, the
models to be compared do not need to be nested.  However, as the computation of
posterior odds ratios is a Bayesian technique, the comparison of models
estimated with maximum likelihood is not supported.

It is important to keep in mind that model comparison of this type is only
valid with proper priors.  If the prior does not integrate to one for all
compared models, the comparison is not valid. This may be the case if part of
the prior mass is implicitly truncated because Blanchard and Kahn conditions
(instability or indeterminacy of the model) are not fulfilled, or because for
some regions of the parameters space the deterministic steady state is
undefined (or Dynare is unable to find it). The compared marginal densities
should be renormalized by the effective prior mass, but this not done by
Dynare: it is the user's responsibility to make sure that model comparison is
based on proper priors. Note that, for obvious reasons, this is not an issue if
the compared marginal densities are based on Laplace approximations.

@optionshead

@table @code

@item marginal_density = @var{ESTIMATOR}
Specifies the estimator for computing the marginal data density. @var{ESTIMATOR} can 
take one of the following two values:
@code{laplace} for the Laplace estimator or @code{modifiedharmonicmean} for the 
@cite{Geweke (1999)} Modified Harmonic Mean estimator. Default value: @code{laplace}
@end table

@outputhead

The results are stored in @code{oo_.Model_Comparison}, which is described below.

@examplehead

@example
model_comparison my_model(0.7) alt_model(0.3);
@end example
This example attributes a 70% prior over @code{my_model} and 30% prior
over @code{alt_model}.

@end deffn

@defvr {MATLAB/Octave variable} oo_.Model_Comparison
Variable set by the @code{model_comparison} command. Fields are of the form:
@example
@code{oo_.Model_Comparison.@var{FILENAME}.@var{VARIABLE_NAME}}
@end example
where @var{FILENAME} is the file name of the model and @var{VARIABLE_NAME} is one of the following:

@table @code

@item Prior
(Normalized) prior density over the model

@item Log_Marginal_Density
Logarithm of the marginal data density

@item Bayes_Ratio
Ratio of the marginal data density of the model relative to the one of the first declared model

@item Posterior_Model_Probability
Posterior probability of the respective model

@end table

@end defvr

@node Shock Decomposition
@section Shock Decomposition

@deffn Command shock_decomposition [@var{VARIABLE_NAME}]@dots{};
@deffnx Command shock_decomposition (@var{OPTIONS}@dots{}) [@var{VARIABLE_NAME}]@dots{};
@anchor{shock_decomposition}

@descriptionhead

This command computes the historical shock decomposition for a given sample based on 
the Kalman smoother, @i{i.e.} it decomposes the historical deviations of the endogenous 
variables from their respective steady state values into the contribution coming 
from the various shocks. The @code{variable_names} provided govern for which 
variables the decomposition is plotted.

Note that this command must come after either @code{estimation} (in case
of an estimated model) or @code{stoch_simul} (in case of a calibrated
model).

@optionshead

@table @code

@item parameter_set = @code{calibration} | @code{prior_mode} | @code{prior_mean} | @code{posterior_mode} | @code{posterior_mean} | @code{posterior_median} | @code{mle_mode}
@anchor{parameter_set} Specify the parameter set to use for running the smoother. Note that the
parameter set used in subsequent commands like @code{stoch_simul} will be set
to the specified @code{parameter_set}. Default value: @code{posterior_mean} if
Metropolis has been run, @code{mle_mode} if MLE has been run.

@item datafile = @var{FILENAME}
@anchor{datafile_shock_decomp} @xref{datafile}. Useful when computing the shock decomposition on a
calibrated model.

@item first_obs = @var{INTEGER}
@xref{first_obs}.

@item nobs = @var{INTEGER}
@xref{nobs}.

@item use_shock_groups [= @var{STRING}]
@anchor{use_shock_groups} Uses shock grouping defined by the string instead of individual shocks in
the decomposition. The groups of shocks are defined in the @ref{shock_groups} block.

@item colormap = @var{STRING}
@anchor{colormap} Controls the colormap used for the shocks decomposition
graphs. See @code{colormap} in Matlab/Octave manual for valid arguments.

@item nograph
@xref{nograph}. Suppresses the display and creation only within the
@code{shock_decomposition}-command, but does not affect other commands.
@xref{plot_shock_decomposition} for plotting graphs.

@item init_state = @var{BOOLEAN}
@anchor{init_state} If equal to @math{0}, the shock decomposition is computed conditional on the smoothed state
variables in period @math{0}, @i{i.e.} the smoothed shocks starting in period
@math{1} are used.  If equal to @math{1}, the shock decomposition is computed
conditional on the smoothed state variables in period @math{1}. Default:
@math{0}
@end table

@outputhead

@defvr {MATLAB/Octave variable} oo_.shock_decomposition
@vindex oo_.shock_decomposition
@anchor{oo_.shock_decomposition}
The results are stored in the field @code{oo_.shock_decomposition}, which is a three
dimensional array. The first dimension contains the @code{M_.endo_nbr} endogenous variables. 
The second dimension stores 
in the first @code{M_.exo_nbr} columns the contribution of the respective shocks.
Column @code{M_.exo_nbr+1} stores the contribution of the initial conditions,
while column @code{M_.exo_nbr+2} stores the smoothed value of the respective
endogenous variable in deviations from their steady state, @i{i.e.} the mean and trends are
subtracted. The third dimension stores the time periods. Both the variables 
and shocks are stored in the order of declaration, @i{i.e.} @code{M_.endo_names} and 
@code{M_.exo_names}, respectively.
@end defvr

@end deffn

@deffn Block shock_groups;
@deffnx Block shock_groups(@var{OPTIONS}@dots{});

@anchor{shock_groups} Shocks can be regrouped for the purpose of shock decomposition. The composition
of the shock groups is written in a block delimited by @code{shock_groups} and
@code{end}.

Each line defines a group of shocks as a list of exogenous variables:

@example
SHOCK_GROUP_NAME   = VARIABLE_1 [[,] VARIABLE_2 [,]@dots{}];
'SHOCK GROUP NAME' = VARIABLE_1 [[,] VARIABLE_2 [,]@dots{}];
@end example

@optionshead

@table @code

@item name = @var{NAME}
Specifies a name for the following definition of shock groups. It is possible
to use several @code{shock_groups} blocks in a model file, each grouping being
identified by a different name. This name must in turn be used in the
@code{shock_decomposition} command.

@end table

@examplehead

@example
varexo e_a, e_b, e_c, e_d;

@dots{}

shock_groups(name=group1);
supply = e_a, e_b;
'aggregate demand' = e_c, e_d;
end;

shock_decomposition(use_shock_groups=group1);
@end example
This example defines a shock grouping with the name @code{group1}, containing a set of supply and demand shocks 
and conducts the shock decomposition for these two groups.
@end deffn

@deffn Command realtime_shock_decomposition [@var{VARIABLE_NAME}]@dots{};
@deffnx Command realtime_shock_decomposition (@var{OPTIONS}@dots{}) [@var{VARIABLE_NAME}]@dots{};
@anchor{realtime_shock_decomposition}

@descriptionhead

This command computes the realtime historical shock decomposition for a given
sample based on the Kalman smoother. For each period
@math{T=[@code{presample},@dots{},@code{nobs}]}, it recursively computes three objects:
@itemize @bullet
@item
realtime historical shock decomposition @math{Y(t|T)} for @math{t=[1,@dots{},T]},
@i{i.e.} without observing data in @math{[T+1,@dots{},@code{nobs}]}. This results in a standard 
shock decomposition being computed for each additional datapoint becoming available after @code{presample}.
@item
forecast shock decomposition @math{Y(T+k|T)} for @math{k=[1,@dots{},forecast]}, @i{i.e.} the @math{k}-step 
ahead forecast made for every @math{T} is decomposed in its shock contributions.
@item
realtime conditional shock decomposition of the difference between the realtime historical shock decomposition and the 
forecast shock decomposition. If @ref{vintage} is equal to @math{0}, it computes the effect of shocks realizing in period 
@math{T}, @i{i.e.} decomposes @math{Y(T|T)-Y(T|T-1)}. Put differently it conducts a @math{1}-period ahead shock decomposition from 
@math{T-1} to @math{T}, by decomposing the update step of the Kalman filter. If @code{vintage>0} and smaller than @code{nobs},
the decomposition is conducted of the forecast revision @math{Y(T+k|T+k)-Y(T+k|T)}.

@end itemize

Like @ref{shock_decomposition} it decomposes the historical deviations of the endogenous 
variables from their respective steady state values into the contribution coming 
from the various shocks. The @code{variable_names} provided govern for which 
variables the decomposition is plotted.

Note that this command must come after either @code{estimation} (in case
of an estimated model) or @code{stoch_simul} (in case of a calibrated
model).

@optionshead

@table @code

@item parameter_set = @code{calibration} | @code{prior_mode} | @code{prior_mean} | @code{posterior_mode} | @code{posterior_mean} | @code{posterior_median} | @code{mle_mode}
@xref{parameter_set}.

@item datafile = @var{FILENAME}
@xref{datafile_shock_decomp}.

@item first_obs = @var{INTEGER}
@xref{first_obs}.

@item nobs = @var{INTEGER}
@xref{nobs}.

@item use_shock_groups [= @var{STRING}]
@xref{use_shock_groups}.

@item colormap = @var{STRING}
@xref{colormap}.

@item nograph
@xref{nograph}. Only shock decompositions are computed and stored in @code{oo_.realtime_shock_decomposition},
@code{oo_.conditional_shock_decomposition} and @code{oo_.realtime_forecast_shock_decomposition} but no plot is made 
(@xref{plot_shock_decomposition}).

@item presample = @var{INTEGER}
@anchor{presample_shock_decomposition} First data point from which recursive
realtime shock decompositions are computed, @i{i.e.} for
@math{T=[@code{presample}@dots{}@code{nobs}]}.

@item forecast = @var{INTEGER}
@anchor{forecast_shock_decomposition} Compute shock decompositions up to
@math{T+k} periods, @i{i.e.} get shock contributions to k-step ahead forecasts.

@item save_realtime = @var{INTEGER_VECTOR}
@anchor{save_realtime} Choose for which vintages to save the full realtime
shock decomposition. Default: @math{0}.
@end table

@outputhead

@defvr {MATLAB/Octave variable} oo_.realtime_shock_decomposition
@vindex oo_.realtime_shock_decomposition
Structure storing the results of realtime historical decompositions. Fields are three-dimensional arrays with 
the first two dimension equal to the ones of @ref{oo_.shock_decomposition}. The third dimension stores the time 
periods and is therefore of size @code{T+forecast}. Fields are of the form:
@example
@code{oo_.realtime_shock_decomposition.@var{OBJECT}}
@end example
where @var{OBJECT} is one of the following:

@table @code

@item pool
Stores the pooled decomposition, @i{i.e.} for every realtime shock decomposition terminal period
@math{T=[@code{presample},@dots{},@code{nobs}]} it collects the last period's decomposition @math{Y(T|T)}
(see also @ref{plot_shock_decomposition}). The third dimension of the array will have size 
@code{nobs+forecast}.

@item time_*
Stores the vintages of realtime historical shock decompositions if @code{save_realtime} is used. For example, if
@code{save_realtime=[5]} and @code{forecast=8}, the third dimension will be of size 13.

@end table
@end defvr

@defvr {MATLAB/Octave variable} oo_.realtime_conditional_shock_decomposition
@vindex oo_.realtime_conditional_shock_decomposition
Structure storing the results of realtime conditional decompositions. Fields are of the form:
@example
@code{oo_.realtime_conditional_shock_decomposition.@var{OBJECT}}
@end example
where @var{OBJECT} is one of the following:

@table @code

@item pool
Stores the pooled realtime conditional shock decomposition, @i{i.e.} collects the decompositions of 
@math{Y(T|T)-Y(T|T-1)} for the terminal periods @math{T=[@code{presample},@dots{},@code{nobs}]}. 
The third dimension is of size @code{nobs}.

@item time_*
Store the vintages of @math{k}-step conditional forecast shock decompositions @math{Y(t|T+k)}, for
@math{t=[T@dots{}T+k]}. @xref{vintage}. The third dimension is of size @code{1+forecast}.

@end table
@end defvr

@defvr {MATLAB/Octave variable} oo_.realtime_forecast_shock_decomposition
@vindex oo_.realtime_forecast_shock_decomposition
Structure storing the results of realtime forecast decompositions. Fields are of the form:
@example
@code{oo_.realtime_forecast_shock_decomposition.@var{OBJECT}}
@end example
where @var{OBJECT} is one of the following:

@table @code

@item pool
Stores the pooled realtime forecast decomposition of the @math{1}-step ahead effect of shocks
on the @math{1}-step ahead prediction, @i{i.e.} @math{Y(T|T-1)}. 

@item time_*
Stores the vintages of @math{k}-step out-of-sample forecast shock
decompositions, @i{i.e.} @math{Y(t|T)}, for @math{t=[T@dots{}T+k]}. @xref{vintage}.
@end table
@end defvr

@end deffn

@deffn Command plot_shock_decomposition [@var{VARIABLE_NAME}]@dots{};
@deffnx Command plot_shock_decomposition (@var{OPTIONS}@dots{}) [@var{VARIABLE_NAME}]@dots{};
@anchor{plot_shock_decomposition}

@descriptionhead

This command plots the historical shock decomposition already computed by
@code{shock_decomposition} or @code{realtime_shock_decomposition}. For that reason,
it must come after one of these commands. The @code{variable_names} provided govern which
variables the decomposition is plotted for.

Further note that, unlike the majority of Dynare commands, the options
specified below are overwritten with their defaults before every call to
@code{plot_shock_decomposition}. Hence, if you want to reuse an option in a
subsequent call to @code{plot_shock_decomposition}, you must pass it to the
command again.

@optionshead

@table @code

@item use_shock_groups [= @var{STRING}]
@xref{use_shock_groups}.

@item colormap = @var{STRING}
@xref{colormap}.

@item nodisplay
@xref{nodisplay}.

@item graph_format = @var{FORMAT}
@itemx graph_format = ( @var{FORMAT}, @var{FORMAT}@dots{} )
@xref{graph_format}.

@item detail_plot
Plots shock contributions using subplots, one per shock (or group of
shocks). Default: not activated

@item interactive
Under MATLAB, add uimenus for detailed group plots. Default: not activated

@item screen_shocks
@anchor{screen_shcoks} For large models (@i{i.e.} for models with more than @math{16}
shocks), plots only the shocks that have the largest historical contribution
for chosen selected @code{variable_names}.  Historical contribution is ranked
by the mean absolute value of all historical contributions.

@item steadystate
@anchor{steadystate} If passed, the the @math{y}-axis value of the zero line in
the shock decomposition plot is translated to the steady state level. Default:
not activated

@item type = @code{qoq} | @code{yoy} | @code{aoa}
@anchor{type} For quarterly data, valid arguments are: @code{qoq} for
quarter-on-quarter plots, @code{yoy} for year-on-year plots of growth rates,
@code{aoa} for annualized variables, @i{i.e.} the value in the last quarter for
each year is plotted.  Default value: @code{empty}, @i{i.e.} standard
period-on-period plots (@code{qoq} for quarterly data).

@item fig_name = @var{STRING}
@anchor{fig_name} Specifies a user-defined keyword to be appended to the
default figure name set by @code{plot_shock_decomposition}.  This can avoid to
overwrite plots in case of sequential calls to @code{plot_shock_decomposition}.

@item write_xls 
@anchor{write_xls} Saves shock decompositions to Excel-file in the main directory, named 
@code{FILENAME_shock_decomposition_TYPE_FIG_NAME.xls}. This option requires your system to be
configured to be able to write Excel files.@footnote{In case of Excel not being installed, 
@url{https://mathworks.com/matlabcentral/fileexchange/38591-xlwrite--generate-xls-x--files-without-excel-on-mac-linux-win} may be helpful.}

@item realtime = @var{INTEGER}
@anchor{realtime} Which kind of shock decomposition to plot. @var{INTEGER} can take following values:
@itemize @bullet
@item
@code{0}: standard historical shock decomposition. @xref{shock_decomposition}.
@item
@code{1}: realtime historical shock decomposition. @xref{realtime_shock_decomposition}.
@item
@code{2}: conditional realtime shock decomposition. @xref{realtime_shock_decomposition}.
@item
@code{3}: realtime forecast shock decomposition. @xref{realtime_shock_decomposition}.
@end itemize
If no @ref{vintage} is requested, @i{i.e.} @code{vintage=0} then the pooled objects from @ref{realtime_shock_decomposition}
will be plotted and the respective vintage otherwise.
Default: @math{0}

@item vintage = @var{INTEGER}
@anchor{vintage} Selects a particular data vintage in @math{[presample,@dots{},nobs]} for which to plot the results from
@ref{realtime_shock_decomposition} selected via the @ref{realtime} option. If the standard 
historical shock decomposition is selected (@code{realtime=0}), @code{vintage} will have no effect. If @code{vintage=0}
the pooled objects from @ref{realtime_shock_decomposition} will be plotted. If @code{vintage>0}, it plots the shock
decompositions for vintage @math{T=@code{vintage}} under the following scenarios:
@itemize @bullet
@item
@code{realtime=1}: the full vintage shock decomposition @math{Y(t|T)} for
@math{t=[1,@dots{},T]}
@item
@code{realtime=2}: the conditional forecast shock decomposition from @math{T},
@i{i.e.} plots @math{Y(T+j|T+j)} and the shock contributions needed to get to
the data @math{Y(T+j)} conditional on @math{T=}@code{vintage}, with
@math{j=[0,@dots{},@code{forecast}]}.
@item
@code{realtime=3}: plots unconditional forecast shock decomposition from
@math{T}, @i{i.e.} @math{Y(T+j|T)}, where @math{T=@code{vintage}} and
@math{j=[0,@dots{},@code{forecast}]}.
@end itemize
Default: @math{0}
@end table

@end deffn

@node Calibrated Smoother
@section Calibrated Smoother

Dynare can also run the smoother on a calibrated model:

@deffn Command calib_smoother [@var{VARIABLE_NAME}]@dots{};
@deffnx Command calib_smoother (@var{OPTIONS}@dots{}) [@var{VARIABLE_NAME}]@dots{};

@descriptionhead

This command computes the smoothed variables (and possible the filtered
variables) on a @code{calibrated} model.

A datafile must be provided, and the observable variables declared with
@code{varobs}. The smoother is based on a first-order approximation of
the model.

By default, the command computes the smoothed variables and shocks and stores the
results in @code{oo_.SmoothedVariables} and
@code{oo_.SmoothedShocks}. It also fills @code{oo_.UpdatedVariables}.

@optionshead

@table @code

@item datafile = @var{FILENAME}
@xref{datafile}.

@item filtered_vars
Triggers the computation of filtered variables. @xref{filtered_vars}, for
more details.

@item filter_step_ahead = [@var{INTEGER1}:@var{INTEGER2}]
@xref{filter_step_ahead}.

@item prefilter = @var{INTEGER}
@xref{prefilter}.

@item loglinear
@xref{loglinear}.

@item first_obs = @var{INTEGER}
@xref{first_obs}.

@item filter_decomposition
@xref{filter_decomposition}.

@item diffuse_filter = @var{INTEGER}
@xref{diffuse_filter}.

@item diffuse_kalman_tol = @var{DOUBLE}
@xref{diffuse_kalman_tol}.

@end table

@end deffn


@node Forecasting
@section Forecasting

On a calibrated model, forecasting is done using the @code{forecast}
command. On an estimated model, use the @code{forecast} option of
@code{estimation} command.

It is also possible to compute forecasts on a calibrated or estimated
model for a given constrained path of the future endogenous
variables. This is done, from the reduced form representation of the
DSGE model, by finding the structural shocks that are needed to match
the restricted paths. Use @code{conditional_forecast},
@code{conditional_forecast_paths} and @code{plot_conditional_forecast}
for that purpose.

Finally, it is possible to do forecasting with a Bayesian VAR using
the @code{bvar_forecast} command.

@deffn Command forecast [@var{VARIABLE_NAME}@dots{}];
@deffnx Command forecast (@var{OPTIONS}@dots{}) [@var{VARIABLE_NAME}@dots{}];

@descriptionhead

This command computes a simulation of a stochastic model from an
arbitrary initial point.

When the model also contains deterministic exogenous shocks, the
simulation is computed conditionally to the agents knowing the future
values of the deterministic exogenous variables.

@code{forecast} must be called after @code{stoch_simul}.

@code{forecast} plots the trajectory of endogenous variables. When a
list of variable names follows the command, only those variables are
plotted. A 90% confidence interval is plotted around the mean
trajectory. Use option @code{conf_sig} to change the level of the
confidence interval.

@optionshead

@table @code

@item periods = @var{INTEGER}
Number of periods of the forecast. Default: @code{5}.

@item conf_sig = @var{DOUBLE}
@anchor{conf_sig} Level of significance for confidence
interval. Default: @code{0.90}

@item nograph
@xref{nograph}.

@item nodisplay
@xref{nodisplay}.

@item graph_format = @var{FORMAT}
@itemx graph_format = ( @var{FORMAT}, @var{FORMAT}@dots{} )
@xref{graph_format}.

@end table

@customhead{Initial Values}

@code{forecast} computes the forecast taking as initial values the values specified in @code{histval} (@pxref{Initial and terminal conditions,histval}). When no @code{histval} block is present, the initial values are the one stated in @code{initval}. When @code{initval} is followed by command @code{steady}, the initial values are the steady state (@pxref{Steady state,steady}).

@outputhead

The results are stored in @code{oo_.forecast}, which is described below.

@examplehead

@example
varexo_det tau;
varexo e;

@dots{}

shocks;
var e; stderr 0.01;
var tau;
periods 1:9;
values -0.15;
end;

stoch_simul(irf=0);

forecast;
@end example

@end deffn

@defvr {MATLAB/Octave variable} oo_.forecast
Variable set by the @code{forecast} command, or by the
@code{estimation} command if used with the @code{forecast} option and
if no Metropolis-Hastings has been computed (in that case, the
forecast is computed for the posterior mode). Fields are of the form:
@example
@code{oo_.forecast.@var{FORECAST_MOMENT}.@var{VARIABLE_NAME}}
@end example
where @var{FORECAST_MOMENT} is one of the following:

@table @code

@item HPDinf
Lower bound of a 90% HPD interval@footnote{See option @ref{conf_sig}
to change the size of the HPD interval} of forecast due to parameter
uncertainty, but ignoring the effect of measurement error on 
observed variables

@item HPDsup
Lower bound of a 90% HPD interval due to parameter uncertainty, but 
ignoring the effect of measurement error on 
observed variables

@item HPDinf_ME
Lower bound of a 90% HPD interval@footnote{See option @ref{conf_sig}
to change the size of the HPD interval} of forecast for observed variables 
due to parameter uncertainty and measurement error 

@item HPDsup_ME
Lower bound of a 90% HPD interval of forecast for observed variables 
due to parameter uncertainty and measurement error 

@item Mean
Mean of the posterior distribution of forecasts

@item Median
Median of the posterior distribution of forecasts

@item Std
Standard deviation of the posterior distribution of forecasts
@end table

@end defvr


@defvr {MATLAB/Octave variable} oo_.PointForecast
@anchor{oo_.PointForecast}
Set by the @code{estimation} command, if it is used with the
@code{forecast} option and if either @code{mh_replic > 0} or
@code{load_mh_file} option is used.

Contains the distribution of forecasts taking into account the
uncertainty about both parameters and shocks.

Fields are of the form:
@example
@code{oo_.PointForecast.@var{MOMENT_NAME}.@var{VARIABLE_NAME}}
@end example
@end defvr

@defvr {MATLAB/Octave variable} oo_.MeanForecast
@anchor{oo_.MeanForecast}
Set by the @code{estimation} command, if it is used with the
@code{forecast} option and if either @code{mh_replic > 0} or
@code{load_mh_file} option is used.

Contains the distribution of forecasts where the uncertainty about
shocks is averaged out. The distribution of forecasts therefore only
represents the uncertainty about parameters.

Fields are of the form:
@example
@code{oo_.MeanForecast.@var{MOMENT_NAME}.@var{VARIABLE_NAME}}
@end example
@end defvr


@deffn Command conditional_forecast (@var{OPTIONS}@dots{}) [@var{VARIABLE_NAME}@dots{}];
@anchor{conditional_forecast}
@descriptionhead

This command computes forecasts on an estimated or calibrated model for a
given constrained path of some future endogenous variables. This is done
using the reduced form first order state-space representation of the DSGE
model by finding the structural shocks that are needed to match the
restricted paths. Consider the an augmented state space representation
that stacks both predetermined and non-predetermined variables into a
vector @math{y_{t}}:

@math{y_t=Ty_{t-1}+R\varepsilon_t}

Both
@math{y_t} and @math{\varepsilon_t} are split up into controlled and
uncontrolled ones to get:

@math{y_t(contr\_vars)=Ty_{t-1}(contr\_vars)+R(contr\_vars,uncontr\_shocks)\varepsilon_t(uncontr\_shocks)
+R(contr\_vars,contr\_shocks)\varepsilon_t(contr\_shocks)}

which can be solved algebraically for @math{\varepsilon_t(contr\_shocks)}.

Using these controlled shocks, the state-space representation can be used
for forecasting. A few things need to be noted. First, it is assumed that
controlled exogenous variables are fully under control of the policy
maker for all forecast periods and not just for the periods where the
endogenous variables are controlled. For all uncontrolled periods, the
controlled exogenous variables are assumed to be 0. This implies that
there is no forecast uncertainty arising from these exogenous variables
in uncontrolled periods. Second, by making use of the first order state
space solution, even if a higher-order approximation was performed, the
conditional forecasts will be based on a first order approximation.
Third, although controlled exogenous variables are taken as instruments
perfectly under the control of the policy-maker, they are nevertheless
random and unforeseen shocks from the perspective of the households. That is,
households are in each period surprised by the realization of a shock
that keeps the controlled endogenous variables at their respective level.
Fourth, keep in mind that if the structural innovations are correlated,
because the calibrated or estimated covariance matrix has non zero off
diagonal elements, the results of the conditional forecasts will depend on
the ordering of the innovations (as declared after @code{varexo}). As in VAR
models, a Cholesky decomposition is used to factorize the covariance matrix
and identify orthogonal impulses. It is preferable to declare the correlations
in the @code{model} block (explicitly imposing the identification restrictions),
unless you are satisfied with the implicit identification restrictions implied
by the Cholesky decomposition.

This command has to be called after @code{estimation} or @code{stoch_simul}.

Use @code{conditional_forecast_paths} block to give the list of
constrained endogenous, and their constrained future path.
Option @code{controlled_varexo} is used to specify the structural shocks
which will be matched to generate the constrained path.

Use @code{plot_conditional_forecast} to graph the results.

@optionshead

@table @code

@item parameter_set = @code{calibration} | @code{prior_mode} | @code{prior_mean} | @code{posterior_mode} | @code{posterior_mean} | @code{posterior_median}
Specify the parameter set to use for the forecasting. No default
value, mandatory option. Note that in case of estimated models, @code{conditional_forecast} does not support the @code{prefilter}-option.

@item controlled_varexo = (@var{VARIABLE_NAME}@dots{})
Specify the exogenous variables to use as control variables. No
default value, mandatory option.

@item periods = @var{INTEGER}
Number of periods of the forecast. Default: @code{40}.  @code{periods}
cannot be less than the number of constrained periods.

@item replic = @var{INTEGER}
Number of simulations. Default: @code{5000}.

@item conf_sig = @var{DOUBLE}
Level of significance for confidence interval. Default: @code{0.90}

@end table

@outputhead

The results are not stored in the @code{oo_} structure but in a separate structure @code{forecasts} saved to the harddisk into a file called @code{conditional_forecasts.mat}.

@defvr {MATLAB/Octave variable} forecasts.cond
Variable set by the @code{conditional_forecast} command. It stores the conditional forecasts. Fields are @code{periods+1} by 1 vectors storing the steady state (time 0) and the subsequent @code{periods} forecasts periods. Fields are of the form:
@example
@code{forecasts.cond.@var{FORECAST_MOMENT}.@var{VARIABLE_NAME}}
@end example
where @var{FORECAST_MOMENT} is one of the following:

@table @code

@item Mean
Mean of the conditional forecast distribution.

@item ci
Confidence interval of the conditional forecast distribution. The size corresponds to @code{conf_sig}.
@end table

@end defvr

@defvr {MATLAB/Octave variable} forecasts.uncond
Variable set by the @code{conditional_forecast} command. It stores the unconditional forecasts. Fields are of the form:
@example
@code{forecasts.uncond.@var{FORECAST_MOMENT}.@var{VARIABLE_NAME}}
@end example
@end defvr

@defvr {MATLAB/Octave variable} forecasts.instruments
Variable set by the @code{conditional_forecast} command. Stores the names of the exogenous instruments.
@end defvr

@defvr {MATLAB/Octave variable} forecasts.controlled_variables
Variable set by the @code{conditional_forecast} command. Stores the position of the constrained endogenous variables in declaration order.
@end defvr

@defvr {MATLAB/Octave variable} forecasts.controlled_exo_variables
Variable set by the @code{conditional_forecast} command. Stores the values of the controlled exogenous 
variables underlying the conditional forecasts to achieve the constrained endogenous 
variables. Fields are number of constrained periods by 1 vectors and are of the form:
@example
@code{forecasts.controlled_exo_variables.@var{FORECAST_MOMENT}.@var{SHOCK_NAME}}
@end example
@end defvr

@defvr {MATLAB/Octave variable} forecasts.graphs
Variable set by the @code{conditional_forecast} command. Stores the information for generating the conditional forecast plots.
@end defvr


@examplehead

@example
var y a
varexo e u;

@dots{}

estimation(@dots{});

conditional_forecast_paths;
var y;
periods 1:3, 4:5;
values 2, 5;
var a;
periods 1:5;
values 3;
end;

conditional_forecast(parameter_set = calibration, controlled_varexo = (e, u), replic = 3000);

plot_conditional_forecast(periods = 10) a y;
@end example


@end deffn

@deffn Block conditional_forecast_paths ;

Describes the path of constrained endogenous, before calling
@code{conditional_forecast}. The syntax is similar to deterministic
shocks in @code{shocks}, see @code{conditional_forecast} for an
example.

The syntax of the block is the same as for the deterministic shocks in
the @code{shocks} blocks (@pxref{Shocks on exogenous variables}). Note that you need to specify the full path for all constrained endogenous 
variables between the first and last specified period. If an intermediate period 
is not specified, a value of 0 is assumed. That is, if you specify only 
values for periods 1 and 3, the values for period 2 will be 0. Currently, it is not 
possible to have uncontrolled intermediate periods.
In case of the presence of @code{observation_trends}, the specified controlled path for 
these variables needs to include the trend component. When using the @ref{loglinear} option, 
it is necessary to specify the logarithm of the controlled variables.

@end deffn

@deffn Command plot_conditional_forecast [@var{VARIABLE_NAME}@dots{}];
@deffnx Command plot_conditional_forecast (periods = @var{INTEGER}) [@var{VARIABLE_NAME}@dots{}];

@descriptionhead

Plots the conditional (plain lines) and unconditional (dashed lines) forecasts.

To be used after @code{conditional_forecast}.

@optionshead

@table @code

@item periods = @var{INTEGER}
Number of periods to be plotted. Default: equal to @code{periods} in
@code{conditional_forecast}. The number of periods declared in
@code{plot_conditional_forecast} cannot be greater than the one
declared in @code{conditional_forecast}.
@end table

@end deffn

@deffn Command bvar_forecast ;
This command computes (out-of-sample) forecasts for an estimated BVAR
model, using Minnesota priors.

See @file{bvar-a-la-sims.pdf}, which comes with Dynare distribution,
for more information on this command.
@end deffn

If the model contains strong non-linearities or if some perfectly expected shocks are considered, the forecasts and the conditional forecasts
can be computed using an extended path method. The forecast scenario describing the shocks and/or the constrained paths on some endogenous variables should be build.
The first step is the forecast scenario initialization using the function @code{init_plan}:

@anchor{init_plan}
@deftypefn {MATLAB/Octave command} {HANDLE =} init_plan (DATES) ;

Creates a new forecast scenario for a forecast period (indicated as a dates class, see @ref{dates class members}). This function return a handle on the new forecast scenario.

@end deftypefn

The forecast scenario can contain some simple shocks on the exogenous variables. This shocks are described using the function @code{basic_plan}:

@anchor{basic_plan}
@deftypefn {MATLAB/Octave command} {HANDLE =} basic_plan (HANDLE, 'VARIABLE_NAME', 'SHOCK_TYPE', DATES, MATLAB VECTOR OF DOUBLE |  [DOUBLE | EXPRESSION [DOUBLE | | EXPRESSION] ] ) ;

Adds to the forecast scenario a shock on the exogenous variable indicated between quotes in the second argument. The shock type has to be specified in the third argument between quotes: 'surprise' in case of an unexpected shock  or 'perfect_foresight' for a perfectly anticipated shock. The fourth argument indicates the period of the shock using a dates class (see @ref{dates class members}). The last argument is the shock path indicated as a Matlab vector of double. This function return the handle of the updated forecast scenario.

@end deftypefn

The forecast scenario can also contain a constrained path on an endogenous variable. The values of the related exogenous variable compatible with the constrained path are in this case computed. In other words, a conditional forecast is performed. This kind of shock is described with the function  @code{flip_plan}:

@anchor{flip_plan}
@deftypefn {MATLAB/Octave command} {HANDLE =} flip_plan (HANDLE, 'VARIABLE_NAME, 'VARIABLE_NAME', 'SHOCK_TYPE', DATES, MATLAB VECTOR OF DOUBLE |  [DOUBLE | EXPRESSION [DOUBLE | | EXPRESSION] ] ) ;

Adds to the forecast scenario a constrained path on the endogenous variable specified between quotes in the second argument. The associated exogenous variable provided in the third argument between quotes, is considered as an endogenous variable and its values compatible with the constrained path on the endogenous variable will be computed. The nature of the expectation on the constrained  path has to be specified in the fourth argument between quotes: 'surprise' in case of an unexpected path or 'perfect_foresight' for a perfectly anticipated path. The fifth argument indicates the period where the path of the endogenous variable is constrained using a dates class (see @ref{dates class members}). The last argument contains the constrained path as a Matlab vector of double. This function return the handle of the updated forecast scenario.

@end deftypefn

Once the forecast scenario if fully described, the forecast is computed with the command @code{det_cond_forecast}:
@anchor{det_cond_forecast}
@deftypefn {MATLAB/Octave command} {DSERIES =} det_cond_forecast (HANDLE[, DSERIES [, DATES]]) ;

Computes the forecast or the conditional forecast using an extended path method for the given forecast scenario (first argument). The past values of the endogenous and exogenous variables provided with a dseries class (see @ref{dseries class members}) can be indicated in the second argument. By default, the past values of the variables are equal to their steady-state values. The initial date of the forecast can be provided in the third argument. By default, the forecast will start at the first date indicated in the @code{init_plan} command. This function returns a dset containing the historical and forecast values for the endogenous and exogenous variables.

@end deftypefn



@examplehead
@example
/* conditional forecast using extended path method
with perfect foresight on r path*/
var y r
varexo e u;

@dots{}

smoothed = dseries('smoothed_variables.csv');

fplan = init_plan(2013Q4:2029Q4);

fplan = flip_plan(fplan, 'y', 'u', 'surprise', 2013Q4:2014Q4,  [1 1.1 1.2 1.1 ]);

fplan = flip_plan(fplan, 'r', 'e', 'perfect_foresight', 2013Q4:2014Q4,  [2 1.9 1.9 1.9 ]);

dset_forecast = det_cond_forecast(fplan, smoothed);

plot(dset_forecast.@{'y','u'@});
plot(dset_forecast.@{'r','e'@});
@end example

@deffn Command smoother2histval [(@var{OPTIONS}@dots{})]

@descriptionhead

The purpose of this command is to construct initial conditions (for a
subsequent simulation) that are the smoothed values of a previous estimation.

More precisely, after an estimation run with the @code{smoother} option,
@code{smoother2histval} will extract the smoothed values (from
@code{oo_.SmoothedVariables}, and possibly from @code{oo_.SmoothedShocks} if
there are lagged exogenous), and will use these values to construct initial
conditions (as if they had been manually entered through @code{histval}).

@optionshead

@table @code

@item period = @var{INTEGER}
Period number to use as the starting point for the subsequent simulation.
It should be between @code{1} and the number of observations that were used to produce the
smoothed values. Default: the last observation.

@item infile = @var{FILENAME}
Load the smoothed values from a @file{_results.mat} file created by a previous
Dynare run. Default: use the smoothed values currently in the global workspace.

@item invars = ( @var{VARIABLE_NAME} [@var{VARIABLE_NAME} @dots{}] )
A list of variables to read from the smoothed values. It can contain state
endogenous variables, and also exogenous variables having a lag. Default: all
the state endogenous variables, and all the exogenous variables with a lag.

@item outfile = @var{FILENAME}
Write the initial conditions to a file. Default: write the initial conditions
in the current workspace, so that a simulation can be performed.

@item outvars = ( @var{VARIABLE_NAME} [@var{VARIABLE_NAME} @dots{}] )
A list of variables which will be given the initial conditions. This list must
have the same length than the list given to @code{invars}, and there will be a
one-to-one mapping between the two list. Default: same value as option
@code{invars}.

@end table

@customhead{Use cases}

There are three possible ways of using this command:

@itemize

@item
Everything in a single file: run an estimation with a smoother, then run @code{smoother2histval} (without the @code{infile} and @code{outfile} options), then run a stochastic simulation.

@item
In two files: in the first file, run the smoother and then run @code{smoother2histval} with the @code{outfile} option; in the second file, run @code{histval_file} to load the initial conditions, and run a (deterministic or stochastic) simulation

@item
In two files: in the first file, run the smoother; in the second file, run @code{smoother2histval} with the @code{infile} option equal to the @file{_results.mat} file created by the first file, and then run a (deterministic or stochastic) simulation

@end itemize

@end deffn

@node Optimal policy
@section Optimal policy

Dynare has tools to compute optimal policies for various types of
objectives. @code{ramsey_model} computes automatically the First Order
Conditions (FOC) of a model, given the @code{planner_objective}. You can
then use other standard commands to solve, estimate or simulate this
new, expanded model.

Alternatively, you can either solve for optimal policy under commitment
with @code{ramsey_policy}, for optimal policy under discretion with
@code{discretionary_policy} or for optimal simple rule with
@code{osr} (also implying commitment).


@anchor{osr}

@deffn Command osr [@var{VARIABLE_NAME}@dots{}];
@deffnx Command osr (@var{OPTIONS}@dots{}) [@var{VARIABLE_NAME}@dots{}];

@descriptionhead

This command computes optimal simple policy rules for
linear-quadratic problems of the form:

@quotation
@math{\min_\gamma E(y'_tWy_t)}
@end quotation

such that:
@quotation
@math{A_1 E_ty_{t+1}+A_2 y_t+ A_3 y_{t-1}+C e_t=0}
@end quotation

where:

@itemize 
@item
@math{E} denotes the unconditional expectations operator;

@item
@math{\gamma} are parameters to be optimized. They must be elements
of the matrices @math{A_1}, @math{A_2}, @math{A_3}, @i{i.e.} be specified as
parameters in the @code{params}-command and be entered in the
@code{model}-block;

@item
@math{y} are the endogenous variables, specified in the
@code{var}-command, whose (co)-variance enters the loss function;

@item
@math{e} are the exogenous stochastic shocks, specified in the
@code{varexo}-command;

@item
@math{W} is the weighting matrix;

@end itemize

The linear quadratic problem consists of choosing a subset of model
parameters to minimize the weighted (co)-variance of a specified subset
of endogenous variables, subject to a linear law of motion implied by the
first order conditions of the model. A few things are worth mentioning.
First, @math{y} denotes the selected endogenous variables' deviations
from their steady state, @i{i.e.} in case they are not already mean 0 the
variables entering the loss function are automatically demeaned so that
the centered second moments are minimized. Second, @code{osr} only solves
linear quadratic problems of the type resulting from combining the
specified quadratic loss function with a first order approximation to the
model's equilibrium conditions. The reason is that the first order
state-space representation is used to compute the unconditional
(co)-variances. Hence, @code{osr} will automatically select
@code{order=1}. Third, because the objective involves minimizing a
weighted sum of unconditional second moments, those second moments must
be finite. In particular, unit roots in @math{y} are not allowed.

The subset of the model parameters over which the optimal simple rule is
to be optimized, @math{\gamma}, must be listed with @code{osr_params}.

The weighting matrix @math{W} used for the quadratic objective function
is specified in the @code{optim_weights}-block. By attaching weights to
endogenous variables, the subset of endogenous variables entering the
objective function, @math{y}, is implicitly specified.


The linear quadratic problem is solved using the numerical optimizer specified with @ref{opt_algo}.

@optionshead

The @code{osr} command will subsequently run @code{stoch_simul} and
accepts the same options, including restricting the endogenous variables
by listing them after the command, as @code{stoch_simul}
(@pxref{Computing the stochastic solution}) plus

@table @code

@item opt_algo = @var{INTEGER}
@anchor{opt_algo}
Specifies the optimizer for minimizing the objective function. The same solvers as for @code{mode_compute} (@pxref{mode_compute}) are available, except for 5,6, and 10. 

@item optim = (@var{NAME}, @var{VALUE}, ...)
A list of @var{NAME} and @var{VALUE} pairs. Can be used to set options for the optimization routines. The set of available options depends on the selected optimization routine (@i{i.e.} on the value of option @ref{opt_algo}). @xref{optim}.

@item maxit = @var{INTEGER} 
Determines the maximum number of iterations used in @code{opt_algo=4}.  This option is now deprecated and will be 
removed in a future release of Dynare. Use @code{optim} instead to set optimizer-specific values. Default: @code{1000}

@item tolf = @var{DOUBLE}
Convergence criterion for termination based on the function value used in @code{opt_algo=4}. Iteration will cease when it proves impossible to
improve the function value by more than tolf.  This option is now deprecated and will be 
removed in a future release of Dynare. Use @code{optim} instead to set optimizer-specific values. Default: @code{e-7}

@item silent_optimizer
@pxref{silent_optimizer}

@item huge_number = @var{DOUBLE}
Value for replacing the infinite bounds on parameters by finite numbers. Used by some optimizers for numerical reasons (@pxref{huge_number}).
Users need to make sure that the optimal parameters are not larger than this value. Default: @code{1e7}

@end table

The value of the objective is stored in the variable
@code{oo_.osr.objective_function} and the value of parameters at the
optimum is stored in @code{oo_.osr.optim_params}. See below for more
details.

After running @code{osr} the parameters entering the simple rule will be
set to their optimal value so that subsequent runs of @code{stoch_simul}
will be conducted at these values.

@end deffn

@anchor{osr_params}
@deffn Command osr_params @var{PARAMETER_NAME}@dots{};
This command declares parameters to be optimized by @code{osr}.
@end deffn

@anchor{optim_weights}
@deffn Block optim_weights ;

This block specifies quadratic objectives for optimal policy problems

More precisely, this block specifies the nonzero elements of the weight
matrix @math{W} used in the quadratic form of the objective function in
@code{osr}.

An element of the diagonal of the weight matrix is given by a line of the
form:
@example
@var{VARIABLE_NAME} @var{EXPRESSION};
@end example

An off-the-diagonal element of the weight matrix is given by a line of
the form:
@example
@var{VARIABLE_NAME},  @var{VARIABLE_NAME} @var{EXPRESSION};
@end example

@end deffn

@examplehead

@example
var y inflation r; 
varexo y_ inf_;

parameters delta sigma alpha kappa gammarr gammax0 gammac0 gamma_y_ gamma_inf_;

delta =  0.44;
kappa =  0.18;
alpha =  0.48;
sigma = -0.06;

gammarr = 0;
gammax0 = 0.2;
gammac0 = 1.5;
gamma_y_ = 8;
gamma_inf_ = 3;

model(linear); 
y  = delta * y(-1)  + (1-delta)*y(+1)+sigma *(r - inflation(+1)) + y_;
inflation  =   alpha * inflation(-1) + (1-alpha) * inflation(+1) + kappa*y + inf_;
r = gammax0*y(-1)+gammac0*inflation(-1)+gamma_y_*y_+gamma_inf_*inf_; 
end;

shocks; 
var y_; stderr 0.63; 
var inf_; stderr 0.4; 
end;

optim_weights; 
inflation 1; 
y 1; 
y, inflation 0.5; 
end;

osr_params gammax0 gammac0 gamma_y_ gamma_inf_; 
osr y; 
@end example


@anchor{osr_params_bounds}
@deffn Block osr_params_bounds ;

This block declares lower and upper bounds for parameters in the optimal simple rule. If not specified
the optimization is unconstrained.

Each line has the following syntax:

@example
PARAMETER_NAME, LOWER_BOUND, UPPER_BOUND;
@end example

Note that the use of this block requires the use of a constrained optimizer, @i{i.e.} setting @ref{opt_algo} to 
1,2,5, or 9.

@examplehead

@example

osr_param_bounds;
gamma_inf_, 0, 2.5;
end;

osr(solve_algo=9) y; 
@end example

@end deffn


@defvr {MATLAB/Octave variable} oo_.osr.objective_function 
After an execution of the @code{osr} command, this variable contains the value of
the objective under optimal policy.
@end defvr

@defvr {MATLAB/Octave variable} oo_.osr.optim_params 
After an execution of the @code{osr} command, this variable contains the value of parameters
at the optimum, stored in fields of the form
@code{oo_.osr.optim_params.@var{PARAMETER_NAME}}.
@end defvr

@defvr {MATLAB/Octave variable} M_.osr.param_names 
After an execution of the @code{osr} command, this cell contains the names of the parameters
@end defvr

@defvr {MATLAB/Octave variable} M_.osr.param_indices 
After an execution of the @code{osr} command, this vector contains the indices of the OSR parameters
in @var{M_.params}.
@end defvr

@defvr {MATLAB/Octave variable} M_.osr.param_bounds 
After an execution of the @code{osr} command, this two by number of OSR parameters
matrix contains the lower and upper bounds of the parameters in the first and second
column, respectively.
@end defvr

@defvr {MATLAB/Octave variable} M_.osr.variable_weights 
After an execution of the @code{osr} command, this sparse matrix
contains the weighting matrix associated with the variables in the
objective function.
@end defvr

@defvr {MATLAB/Octave variable} M_.osr.variable_indices 
After an execution of the @code{osr} command, this vector contains the 
indices of the variables entering the objective function in @code{M_.endo_names}.
@end defvr

@anchor{Ramsey}

@deffn Command ramsey_model (@var{OPTIONS}@dots{});

@descriptionhead

This command computes the First Order Conditions for maximizing the policy maker objective function subject to the
constraints provided by the equilibrium path of the private economy.

The planner objective must be declared with the @code{planner_objective} command.

This command only creates the expanded model, it doesn't perform any
computations. It needs to be followed by other instructions to actually
perform desired computations. Note that it is the only way to perform
perfect foresight simulation of the Ramsey policy problem.

@xref{Auxiliary
variables}, for an explanation of how Lagrange multipliers are
automatically created.

@optionshead

This command accepts the following options:

@table @code

@anchor{planner_discount}
@item planner_discount = @var{EXPRESSION}
Declares or reassigns the discount factor of the central planner
@code{optimal_policy_discount_factor}. Default: @code{1.0}

@item instruments = (@var{VARIABLE_NAME},@dots{})
Declares instrument variables for the computation of the steady state
under optimal policy. Requires a @code{steady_state_model} block or a
@code{@dots{}_steadystate.m} file. See below.

@end table

@customhead{Steady state}
@anchor{Ramsey steady state}

Dynare takes advantage of the fact that the Lagrange multipliers appear
linearly in the equations of the steady state of the model under optimal
policy. Nevertheless, it is in general very difficult to compute the
steady state with simply a numerical guess in @code{initval} for the
endogenous variables.

It greatly facilitates the computation, if the user provides an
analytical solution for the steady state (in @code{steady_state_model}
block or in a @code{@dots{}_steadystate.m} file). In this case, it is
necessary to provide a steady state solution CONDITIONAL on the value
of the instruments in the optimal policy problem and declared with
option @code{instruments}. Note that choosing the instruments is
partly a matter of interpretation and you can choose instruments that
are handy from a mathematical point of view but different from the
instruments you would refer to in the analysis of the paper. A typical
example is choosing inflation or nominal interest rate as an
instrument.


@end deffn

@deffn Block ramsey_constraints
@anchor{ramsey_constraints}

@descriptionhead

This block lets you define constraints on the variables in the Ramsey
problem. The constraints take the form of a variable, an inequality
operator (@code{>} or @code{<}) and a constant.

@examplehead

@example
ramsey_constraints;
i > 0;
end;
@end example
@end deffn
 
@deffn Command ramsey_policy [@var{VARIABLE_NAME}@dots{}];
@deffnx Command ramsey_policy (@var{OPTIONS}@dots{}) [@var{VARIABLE_NAME}@dots{}];
@anchor{ramsey_policy}

@descriptionhead

This command computes the first order approximation of the policy that
maximizes the policy maker's objective function subject to the
constraints provided by the equilibrium path of the private economy and under 
commitment to this optimal policy. The Ramsey policy is computed
by approximating the equilibrium system around the perturbation point where the 
Lagrange multipliers are at their steady state, @i{i.e.} where the Ramsey planner acts 
as if the initial multipliers had 
been set to 0 in the distant past, giving them time to converge to their steady 
state value. Consequently, the optimal decision rules are computed around this steady state 
of the endogenous variables and the Lagrange multipliers.

This first order approximation to the optimal policy conducted by Dynare is not to be 
confused with a naive linear quadratic approach to optimal policy that can lead to 
spurious welfare rankings (see @cite{Kim and Kim (2003)}). In the latter, the optimal policy 
would be computed subject to the first order approximated FOCs of the 
private economy. In contrast, Dynare first computes the FOCs of the Ramsey planner's problem
subject to the nonlinear constraints that are the FOCs of the private economy 
and only then approximates these FOCs of planner's problem to first order. Thereby, the second
order terms that are required for a second-order correct welfare evaluation are 
preserved.

Note that the variables in the list after the @code{ramsey_policy}-command can also contain multiplier 
names. In that case, Dynare will for example display the IRFs of the respective multipliers when @code{irf>0}.

The planner objective must be declared with the @code{planner_objective} command.

@xref{Auxiliary
variables}, for an explanation of how this operator is handled
internally and how this affects the output.

@optionshead

This command accepts all options of @code{stoch_simul}, plus:

@table @code

@item planner_discount = @var{EXPRESSION}
@xref{planner_discount}.

@item instruments = (@var{VARIABLE_NAME},@dots{})
Declares instrument variables for the computation of the steady state
under optimal policy. Requires a @code{steady_state_model} block or a
@code{@dots{}_steadystate.m} file. See below.

@end table

Note that only a first order approximation of the optimal Ramsey policy is 
available, leading to a second-order accurate welfare ranking 
(@i{i.e.} @code{order=1} must be specified).

@outputhead

This command generates all the output variables of @code{stoch_simul}. For specifying
the initial values for the endogenous state variables (except for the Lagrange
multipliers), @pxref{histval}.

@vindex oo_.planner_objective_value
@anchor{planner_objective_value}

In addition, it stores the value of planner objective function under
Ramsey policy in @code{oo_.planner_objective_value}, given the initial values 
of the endogenous state variables. If not specified with @code{histval}, they are 
taken to be at their steady state values. The result is a 1 by 2 
vector, where the first entry stores the value of the planner objective when the initial Lagrange
multipliers associated with the planner's problem are set to their steady state
values (@pxref{ramsey_policy}).

In contrast, the second entry stores the value of the planner objective with 
initial Lagrange multipliers of the planner's problem set to 0, @i{i.e.} it is assumed 
that the planner exploits its ability to surprise private agents in the first
period of implementing Ramsey policy. This is the value of implementating
optimal policy for the first time and committing not to re-optimize in the future.

Because it entails computing at least a second order approximation, this
computation is skipped with a message when the model is too large (more than 180 state
variables, including lagged Lagrange multipliers).
@customhead{Steady state}
@xref{Ramsey steady state}.


@end deffn

@anchor{discretionary_policy}
@deffn Command discretionary_policy [@var{VARIABLE_NAME}@dots{}];
@deffnx Command discretionary_policy (@var{OPTIONS}@dots{}) [@var{VARIABLE_NAME}@dots{}];

@descriptionhead

This command computes an approximation of the optimal policy under
discretion. The algorithm implemented is essentially an LQ solver, and
is described by @cite{Dennis (2007)}.

You should ensure that your model is linear and your objective is
quadratic. Also, you should set the @code{linear} option of the
@code{model} block.

@optionshead

This command accepts the same options than @code{ramsey_policy}, plus:

@table @code

@item discretionary_tol = @var{NON-NEGATIVE DOUBLE}
Sets the tolerance level used to assess convergence of the solution
algorithm. Default: @code{1e-7}.

@item maxit = @var{INTEGER}
Maximum number of iterations. Default: @code{3000}.

@end table

@end deffn


@anchor{planner_objective}
@deffn Command planner_objective @var{MODEL_EXPRESSION};

This command declares the policy maker objective, for use with
@code{ramsey_policy} or @code{discretionary_policy}.

You need to give the one-period objective, not the discounted lifetime
objective. The discount factor is given by the @code{planner_discount}
option of @code{ramsey_policy} and @code{discretionary_policy}. The
objective function can only contain current endogenous variables and no
exogenous ones. This limitation is easily circumvented by defining an
appropriate auxiliary variable in the model.

With @code{ramsey_policy}, you are not limited to quadratic
objectives: you can give any arbitrary nonlinear expression.

With @code{discretionary_policy}, the objective function must be quadratic.
@end deffn

@node Sensitivity and identification analysis
@section Sensitivity and identification analysis

Dynare provides an interface to the global sensitivity analysis (GSA)
toolbox (developed by the Joint Research Center (JRC) of the European
Commission), which is now part of the official Dynare distribution. The
GSA toolbox can be used to answer the following questions:

@enumerate
@item
What is the domain of structural coefficients assuring the stability and determinacy
of a DSGE model?

@item
Which parameters mostly drive the fit of, @i{e.g.}, GDP and which the fit of inflation?
Is there any conflict between the optimal fit of one observed series versus another?

@item
How to represent in a direct, albeit approximated, form the relationship between
structural parameters and the reduced form of a rational expectations model?
@end enumerate

The discussion of the methodologies and their application is described in
@cite{Ratto (2008)}.

With respect to the previous version of the toolbox, in order to work
properly, the GSA toolbox no longer requires that the Dynare
estimation environment is set up.


@menu
* Performing sensitivity analysis::
* IRF/Moment calibration::
* Performing identification analysis::
* Types of analysis and output files::
@end menu


@node Performing sensitivity analysis
@subsection Performing sensitivity analysis

@anchor{dynare_sensitivity}
@deffn Command dynare_sensitivity ;
@deffnx Command dynare_sensitivity (@var{OPTIONS}@dots{});

@descriptionhead

This command triggers sensitivity analysis on a DSGE model.

@optionshead
@customhead{Sampling Options}
@anchor{Sampling Options}
@table @code

@item Nsam = @var{INTEGER}
Size of the Monte-Carlo sample. Default: @code{2048}

@item ilptau = @var{INTEGER}
If equal to @code{1}, use @math{LP_\tau} quasi-Monte-Carlo.
If equal to @code{0}, use LHS Monte-Carlo. Default: @code{1}

@item pprior = @var{INTEGER}
If equal to @code{1}, sample from the prior distributions.
If equal to @code{0}, sample from the multivariate normal @math{N(\bar{\theta},\Sigma)},
where @math{\bar{\theta}} is the posterior mode and @math{\Sigma=H^{-1}}, @math{H}
is the Hessian at the mode. Default: @code{1}

@item prior_range = @var{INTEGER}
If equal to @code{1}, sample uniformly from prior ranges.
If equal to @code{0}, sample from prior distributions. Default: @code{1}

@item morris = @var{INTEGER}
@anchor{morris}
If equal to @code{0}, ANOVA mapping (Type I error)
If equal to @code{1}, Screening analysis (Type II error)
If equal to @code{2}, Analytic derivatives (similar to Type II error, only valid when
@code{identification=1}).Default: @code{1} when @code{identification=1}, @code{0} otherwise

@item morris_nliv = @var{INTEGER}
@anchor{morris_nliv}
Number of levels in Morris design. Default: @code{6}

@item morris_ntra = @var{INTEGER}
@anchor{morris_ntra}
Number trajectories in Morris design. Default: @code{20}

@item ppost = @var{INTEGER}
If equal to @code{1}, use Metropolis posterior sample.
If equal to @code{0}, do not use Metropolis posterior sample. NB: This
overrides any other sampling option. Default: @code{0}

@item neighborhood_width = @var{DOUBLE}
When @code{pprior=0} and @code{ppost=0}, allows for the sampling of
parameters around the value specified in the @code{mode_file}, in the range
@code{xparam1}@math{\pm\left|@code{xparam1}\times@code{neighborhood_width}\right|}. Default: @code{0}

@end table
@customhead{Stability Mapping Options}
@table @code

@item stab = @var{INTEGER}
If equal to @code{1}, perform stability mapping.
If equal to @code{0}, do not perform stability mapping. Default: @code{1}

@item load_stab = @var{INTEGER}
If equal to @code{1}, load a previously created sample.
If equal to @code{0}, generate a new sample. Default: @code{0}

@item alpha2_stab = @var{DOUBLE}
Critical value for correlations @math{\rho} in filtered samples:
plot couples of parmaters with @math{\left|\rho\right|>} @code{alpha2_stab}.
Default: @code{0}

@item pvalue_ks = @var{DOUBLE}
The threshold @math{pvalue} for significant Kolmogorov-Smirnov test (@i{i.e.} plot parameters with
@math{pvalue<} @code{pvalue_ks}). Default: @code{0.001}

@item pvalue_corr = @var{DOUBLE}
The threshold @math{pvalue} for significant correlation in filtered samples
(@i{i.e.} plot bivariate samples when @math{pvalue<} @code{pvalue_corr}). Default: @code{1e-5}

@end table
@customhead{Reduced Form Mapping Options}
@table @code

@item redform = @var{INTEGER}
If equal to @code{1}, prepare Monte-Carlo sample of reduced form matrices.
If equal to @code{0}, do not prepare Monte-Carlo sample of reduced form matrices. Default: @code{0}

@item load_redform = @var{INTEGER}
If equal to @code{1}, load previously estimated mapping.
If equal to @code{0}, estimate the mapping of the reduced form model. Default: @code{0}

@item logtrans_redform = @var{INTEGER}
If equal to @code{1}, use log-transformed entries.
If equal to @code{0}, use raw entries. Default: @code{0}

@item threshold_redform = [@var{DOUBLE} @var{DOUBLE}]
The range over which the filtered Monte-Carlo entries of the reduced form coefficients
should be analyzed. The first number is the lower bound and the second is the upper bound.
An empty vector indicates that these entries will not be filtered. Default: @code{empty}

@item ksstat_redform = @var{DOUBLE}
Critical value for Smirnov statistics @math{d} when reduced form entries
are filtered. Default: @code{0.001}

@item alpha2_redform = @var{DOUBLE}
Critical value for correlations @math{\rho}  when reduced form entries
are filtered. Default: @code{1e-5}

@item namendo = (@var{VARIABLE_NAME}@dots{})
List of endogenous variables. `@code{:}' indicates all endogenous variables.
Default: @code{empty}

@item namlagendo = (@var{VARIABLE_NAME}@dots{})
List of lagged endogenous variables. `@code{:}' indicates all lagged endogenous variables.
Analyze entries @code{[namendo}@math{\times}@code{namlagendo]} Default: @code{empty}

@item namexo = (@var{VARIABLE_NAME}@dots{})
List of exogenous variables. `@code{:}' indicates all exogenous variables.
Analyze entries @code{[namendo}@math{\times}@code{namexo]}. Default: @code{empty}

@end table
@customhead{RMSE Options}
@table @code

@item rmse = @var{INTEGER}
If equal to @code{1}, perform RMSE analysis.
If equal to @code{0}, do not perform RMSE analysis. Default: @code{0}

@item load_rmse = @var{INTEGER}
If equal to @code{1}, load previous RMSE analysis.
If equal to @code{0}, make a new RMSE analysis. Default: @code{0}

@item lik_only = @var{INTEGER}
If equal to @code{1}, compute only likelihood and posterior.
If equal to @code{0}, compute RMSE's for all observed series. Default: @code{0}

@item var_rmse = (@var{VARIABLE_NAME}@dots{})
List of observed series to be considered. `@code{:}' indicates all observed
variables. Default: @code{varobs}

@item pfilt_rmse = @var{DOUBLE}
Filtering threshold for RMSE's. Default: @code{0.1}

@item istart_rmse = @var{INTEGER}
Value at which to start computing RMSE's (use @code{2} to avoid big intitial
error). Default: @code{presample+1}

@item alpha_rmse = @var{DOUBLE}
Critical value for Smirnov statistics @math{d}: plot parameters with
@math{d>} @code{alpha_rmse}. Default: @code{0.001}

@item alpha2_rmse = @var{DOUBLE}
Critical value for correlation @math{\rho}: plot couples of parmaters with
@math{\left|\rho\right|=} @code{alpha2_rmse}. Default: @code{1e-5}

@item datafile = @var{FILENAME}
@xref{datafile}.

@item nobs = @var{INTEGER}
@item nobs = [@var{INTEGER1}:@var{INTEGER2}]
@xref{nobs}.

@item first_obs = @var{INTEGER}
@xref{first_obs}.

@item prefilter = @var{INTEGER}
@xref{prefilter}.

@item presample = @var{INTEGER}
@xref{presample}.

@item nograph
@xref{nograph}.

@item nodisplay
@xref{nodisplay}.

@item graph_format = @var{FORMAT}
@itemx graph_format = ( @var{FORMAT}, @var{FORMAT}@dots{} )
@xref{graph_format}.

@item conf_sig = @var{DOUBLE}
@xref{conf_sig}.

@item loglinear
@xref{loglinear}.

@item mode_file = @var{FILENAME}
@xref{mode_file}.

@item kalman_algo = @var{INTEGER}
@xref{kalman_algo}.

@end table
@customhead{Identification Analysis Options}
@table @code

@item identification = @var{INTEGER}
If equal to @code{1}, performs identification anlysis (forcing @code{redform=0} and @code{morris=1})
If equal to @code{0}, no identification analysis. Default: @code{0}

@item morris = @var{INTEGER}
@xref{morris}.

@item morris_nliv = @var{INTEGER}
@xref{morris_nliv}.

@item morris_ntra = @var{INTEGER}
@xref{morris_ntra}.

@item load_ident_files = @var{INTEGER}
Loads previously performed identification analysis. Default: @code{0}

@item useautocorr = @var{INTEGER}
Use autocorrelation matrices in place of autocovariance matrices in moments
for identification analysis. Default: @code{0}

@item ar = @var{INTEGER}
Maximum number of lags for moments in identification analysis. Default: @code{1}

@item diffuse_filter = @var{INTEGER}
@xref{diffuse_filter}.

@end table

@end deffn

@node IRF/Moment calibration
@subsection IRF/Moment calibration

The @code{irf_calibration} and @code{moment_calibration} blocks allow imposing implicit ``endogenous'' priors 
about IRFs and moments on the model. The way it works internally is that 
any parameter draw that is inconsistent with the ``calibration'' provided in these blocks is discarded, @i{i.e.} assigned a prior density of @math{0}. 
In the context of @code{dynare_sensitivity}, these restrictions allow tracing out which parameters are driving the model to
satisfy or violate the given restrictions.

IRF and moment calibration can be defined in @code{irf_calibration} and @code{moment_calibration} blocks:

@deffn Block irf_calibration ;
@deffnx Block irf_calibration (@var{OPTIONS}@dots{});

@descriptionhead

This block allows defining IRF calibration criteria and is terminated by @code{end;}. 
To set IRF sign restrictions, the following syntax is used
@example
@var{VARIABLE_NAME}(@var{INTEGER}),@var{EXOGENOUS_NAME}, -;
@var{VARIABLE_NAME}(@var{INTEGER}:@var{INTEGER}),@var{EXOGENOUS_NAME}, +;
@end example
To set IRF restrictions with specific intervals, the following syntax is used
@example
@var{VARIABLE_NAME}(@var{INTEGER}),@var{EXOGENOUS_NAME}, [@var{DOUBLE} @var{DOUBLE}];
@var{VARIABLE_NAME}(@var{INTEGER}:@var{INTEGER}),@var{EXOGENOUS_NAME}, [@var{DOUBLE} @var{DOUBLE}];
@end example

When @code{(@var{INTEGER}:@var{INTEGER})} is used, the restriction is considered to be fulfilled by a logical OR.
A list of restrictions must always be fulfilled with logical AND.

@optionshead

@table @code

@item relative_irf
@xref{relative_irf}.

@end table

@examplehead

@example
irf_calibration;
y(1:4), e_ys, [ -50 50]; //[first year response with logical OR]
@@#for ilag in 21:40
R_obs(@@@{ilag@}), e_ys, [0 6]; //[response from 5th to 10th years with logical AND]
@@#endfor
end;
@end example

@end deffn

@deffn Block moment_calibration ;
@deffnx Block moment_calibration (@var{OPTIONS}@dots{});

@descriptionhead

This block allows defining moment calibration criteria. This block is terminated by @code{end;}, and contains lines of the
form:
@example
@var{VARIABLE_NAME1},@var{VARIABLE_NAME2}(+/-@var{INTEGER}), [@var{DOUBLE} @var{DOUBLE}];
@var{VARIABLE_NAME1},@var{VARIABLE_NAME2}(+/-@var{INTEGER}), +/-;
@var{VARIABLE_NAME1},@var{VARIABLE_NAME2}(+/-(@var{INTEGER}:@var{INTEGER})), [@var{DOUBLE} @var{DOUBLE}];
@var{VARIABLE_NAME1},@var{VARIABLE_NAME2}((-@var{INTEGER}:+@var{INTEGER})), [@var{DOUBLE} @var{DOUBLE}];
@end example

When @code{(@var{INTEGER}:@var{INTEGER})} is used, the restriction is considered to be fulfilled by a logical OR.
A list of restrictions must always be fulfilled with logical AND.

@examplehead

@example
moment_calibration;
y_obs,y_obs, [0.5 1.5]; //[unconditional variance]
y_obs,y_obs(-(1:4)), +; //[sign restriction for first year acf with logical OR]
@@#for ilag in -2:2
y_obs,R_obs(@@@{ilag@}), -; //[-2:2 ccf with logical AND]
@@#endfor
@@#for ilag in -4:4
y_obs,pie_obs(@@@{ilag@}), -; //[-4_4 ccf with logical AND]
@@#endfor
end;
@end example

@end deffn
@node Performing identification analysis
@subsection Performing identification analysis

@anchor{identification}
@deffn Command identification ;
@deffnx Command identification (@var{OPTIONS}@dots{});

@descriptionhead

This command triggers identification analysis.

@optionshead

@table @code

@item ar = @var{INTEGER}
Number of lags of computed autocorrelations (theoretical moments). Default: @code{1}

@item useautocorr = @var{INTEGER}
If equal to @code{1}, compute derivatives of autocorrelation. If equal
to @code{0}, compute derivatives of autocovariances. Default: @code{0}

@item load_ident_files = @var{INTEGER}
If equal to @code{1}, allow Dynare to load previously
computed analyzes. Default: @code{0}

@item prior_mc = @var{INTEGER}
Size of Monte-Carlo sample. Default: @code{1}

@item prior_range = @var{INTEGER}
Triggers uniform sample within the range implied by the prior specifications (when
@code{prior_mc>1}). Default: @code{0}

@item advanced = @var{INTEGER}
Shows a more detailed analysis, comprised of an analysis for the linearized rational
expectation model as well as the associated reduced form solution. Further performs a brute
force search of the groups of parameters best reproducing the behavior of each single parameter.
The maximum dimension of the group searched is triggered by @code{max_dim_cova_group}. Default: @code{0}

@item max_dim_cova_group = @var{INTEGER}
In the brute force search (performed when @code{advanced=1}) this option sets the maximum dimension of groups
of parameters that best reproduce the behavior of each single model parameter. Default: @code{2}

@item periods = @var{INTEGER}
When the analytic Hessian is not available (@i{i.e.} with missing values or diffuse
Kalman filter or univariate Kalman filter), this triggers the length of stochastic simulation
to compute Simulated Moments Uncertainty. Default: @code{300}

@item replic = @var{INTEGER}
When the analytic Hessian is not available, this triggers the number of replicas
to compute Simulated Moments Uncertainty. Default: @code{100}

@item gsa_sample_file = @var{INTEGER}
If equal to @code{0}, do not use sample file.
If equal to @code{1}, triggers gsa prior sample.
If equal to @code{2}, triggers gsa Monte-Carlo sample (@i{i.e.} loads a sample corresponding to
@code{pprior=0} and @code{ppost=0} in the @code{dynare_sensitivity} options). Default: @code{0}

@item gsa_sample_file = @var{FILENAME}
Uses the provided path to a specific user defined sample file. Default: @code{0}

@item parameter_set = @code{calibration} | @code{prior_mode} | @code{prior_mean} | @code{posterior_mode} | @code{posterior_mean} | @code{posterior_median}
Specify the parameter set to use. Default: @code{prior_mean}

@item lik_init = @var{INTEGER}
@xref{lik_init}.

@item kalman_algo = @var{INTEGER}
@xref{kalman_algo}.

@item nograph
@xref{nograph}.

@item nodisplay
@xref{nodisplay}.

@item graph_format = @var{FORMAT}
@itemx graph_format = ( @var{FORMAT}, @var{FORMAT}@dots{} )
@xref{graph_format}.

@end table

@end deffn

@node Types of analysis and output files
@subsection Types of analysis and output files

The sensitivity analysis toolbox includes several types of analyses.
Sensitivity analysis results are saved locally in @code{<mod_file>/gsa},
where @code{<mod_file>.mod} is the name of the DYNARE model file.

@menu
* Sampling::
* Stability Mapping::
* IRF/Moment restrictions::
* Reduced Form Mapping::
* RMSE::
* Screening Analysis::
* Identification Analysis::
@end menu

@node Sampling
@subsubsection Sampling

The following binary files are produced:
@itemize
@item
@code{<mod_file>_prior.mat}: this file stores information about the analyses
performed sampling from the prior, @i{i.e.} @code{pprior=1} and @code{ppost=0};

@item
@code{<mod_file>_mc.mat}: this file stores information about the analyses performed
sampling from multivariate normal, @i{i.e.} @code{pprior=0} and @code{ppost=0};

@item
@code{<mod_file>_post.mat}: this file stores information about analyses performed
using the Metropolis posterior sample, @i{i.e.} @code{ppost=1}.
@end itemize

@node Stability Mapping
@subsubsection Stability Mapping

Figure files produced are of the form @code{<mod_file>_prior_*.fig} and store results
for stability mapping from prior Monte-Carlo samples:
@itemize
@item
@code{<mod_file>_prior_stable.fig}: plots of the Smirnov test and the correlation analyses
confronting the cdf of the sample fulfilling Blanchard-Kahn conditions (blue color)
with the cdf of the rest of the sample (red color), @i{i.e.} either
instability or indeterminacy or the solution could not be found (@i{e.g.}
the steady state solution could not be found by the solver);

@item
@code{<mod_file>_prior_indeterm.fig}: plots of the Smirnov test and the correlation
analyses confronting the cdf of the sample producing indeterminacy (red color)
with the cdf of the rest of the sample (blue color);

@item
@code{<mod_file>_prior_unstable.fig}: plots of the Smirnov test and the correlation
analyses confronting the cdf of the sample producing explosive roots (red color) 
with the cdf of the rest of the sample (blue color);

@item
@code{<mod_file>_prior_wrong.fig}: plots of the Smirnov test and the correlation
analyses confronting the cdf of the sample where the solution could not be found (@i{e.g.}
the steady state solution could not be found by the solver - red color) 
with the cdf of the rest of the sample (blue color);

@item
@code{<mod_file>_prior_calib.fig}: plots of the Smirnov test and the correlation
analyses splitting the sample fulfilling Blanchard-Kahn conditions, 
by confronting the cdf of the sample where IRF/moment restrictions are matched (blue color)
with the cdf where IRF/moment restrictions are NOT matched (red color);

@end itemize

Similar conventions apply for @code{<mod_file>_mc_*.fig} files, obtained when
samples from multivariate normal are used.

@node IRF/Moment restrictions
@subsubsection IRF/Moment restrictions

The following binary files are produced:
@itemize
@item
@code{<mod_file>_prior_restrictions.mat}: this file stores information about the IRF/moment restriction analysis
performed sampling from the prior ranges, @i{i.e.} @code{pprior=1} and @code{ppost=0};

@item
@code{<mod_file>_mc_restrictions.mat}: this file stores information about the IRF/moment restriction analysis performed
sampling from multivariate normal, @i{i.e.} @code{pprior=0} and @code{ppost=0};

@item
@code{<mod_file>_post_restrictions.mat}: this file stores information about IRF/moment restriction analysis performed
using the Metropolis posterior sample, @i{i.e.} @code{ppost=1}.
@end itemize

Figure files produced are of the form @code{<mod_file>_prior_irf_calib_*.fig} and @code{<mod_file>_prior_moment_calib_*.fig} and store results
for mapping restrictions from prior Monte-Carlo samples:
@itemize
@item
@code{<mod_file>_prior_irf_calib_<ENDO_NAME>_vs_<EXO_NAME>_<PERIOD>.fig}: plots of the Smirnov test and the correlation
analyses splitting the sample fulfilling Blanchard-Kahn conditions,
by confronting the cdf of the sample where the individual IRF restriction 
@code{<ENDO_NAME>} vs. @code{<EXO_NAME>} at period(s) @code{<PERIOD>} is matched (blue color)
with the cdf where the IRF restriction is NOT matched (red color)

@item
@code{<mod_file>_prior_irf_calib_<ENDO_NAME>_vs_<EXO_NAME>_ALL.fig}: plots of the Smirnov test and the correlation
analyses splitting the sample fulfilling Blanchard-Kahn conditions,
by confronting the cdf of the sample where ALL the individual IRF restrictions for the same couple
@code{<ENDO_NAME>} vs. @code{<EXO_NAME>} are matched (blue color)
with the cdf where the IRF restriction is NOT matched (red color)

@item
@code{<mod_file>_prior_irf_restrictions.fig}: plots visual information on the IRF restrictions 
compared to the actual Monte Carlo realization from prior sample.

@item
@code{<mod_file>_prior_moment_calib_<ENDO_NAME1>_vs_<ENDO_NAME2>_<LAG>.fig}: plots of the Smirnov test and the correlation
analyses splitting the sample fulfilling Blanchard-Kahn conditions,
by confronting the cdf of the sample where the individual acf/ccf moment restriction 
@code{<ENDO_NAME1>} vs. @code{<ENDO_NAME2>} at lag(s) @code{<LAG>} is matched (blue color)
with the cdf where the IRF restriction is NOT matched (red color)

@item
@code{<mod_file>_prior_moment_calib_<ENDO_NAME>_vs_<EXO_NAME>_ALL.fig}: plots of the Smirnov test and the correlation
analyses splitting the sample fulfilling Blanchard-Kahn conditions,
by confronting the cdf of the sample where ALL the individual acf/ccf moment restrictions for the same couple
@code{<ENDO_NAME1>} vs. @code{<ENDO_NAME2>} are matched (blue color)
with the cdf where the IRF restriction is NOT matched (red color)

@item
@code{<mod_file>_prior_moment_restrictions.fig}: plots visual information on the moment restrictions 
compared to the actual Monte Carlo realization from prior sample.

@end itemize

Similar conventions apply for @code{<mod_file>_mc_*.fig} and @code{<mod_file>_post_*.fig} files, obtained when
samples from multivariate normal or from posterior are used.

@node Reduced Form Mapping
@subsubsection Reduced Form Mapping

When the option @code{threshold_redform} is not set, or it is empty (the default), this analysis estimates a multivariate
smoothing spline ANOVA model (the 'mapping') for the selected entries in the transition matrix of the shock matrix of the reduce form first order solution of the model.
This mapping is done either with prior samples or with MC samples with @code{neighborhood_width}.
Unless @code{neighborhood_width} is set with MC samples, the  mapping of the reduced form solution forces the use of samples from
prior ranges or prior distributions, @i{i.e.}: @code{pprior=1} and @code{ppost=0}. It
uses 250 samples to optimize smoothing parameters and 1000 samples to compute the
fit. The rest of the sample is used for out-of-sample validation. One can also
load a previously estimated mapping with a new Monte-Carlo sample, to look at the
forecast for the new Monte-Carlo sample.

The following synthetic figures are produced:
@itemize
@item
@code{<mod_file>_redform_<endo name>_vs_lags_*.fig}: shows bar charts
of the sensitivity indices for the ten most important parameters driving
the reduced form coefficients of the selected endogenous variables
(@code{namendo}) versus lagged endogenous variables (@code{namlagendo}); suffix
@code{log} indicates the results for log-transformed entries;

@item
@code{<mod_file>_redform_<endo name>_vs_shocks_*.fig}: shows bar charts
of the sensitivity indices for the ten most important parameters driving
the reduced form coefficients of the selected endogenous variables
(@code{namendo}) versus exogenous variables (@code{namexo}); suffix @code{log}
indicates the results for log-transformed entries;

@item
@code{<mod_file>_redform_gsa(_log).fig}: shows bar chart of all sensitivity
indices for each parameter: this allows one to notice parameters that
have a minor effect for any of the reduced form coefficients.
@end itemize

Detailed results of the analyses are shown in the subfolder @code{<mod_file>/gsa/redform_prior} for prior samples and in @code{<mod_file>/gsa/redform_mc} for MC samples with option @code{neighborhood_width},
where the detailed results of the estimation of the single functional relationships
between parameters @math{\theta} and reduced form coefficient (denoted as @math{y} hereafter) are stored in separate directories
named as:

@itemize
@item
@code{<namendo>_vs_<namlagendo>}: for the entries of the transition matrix;

@item
@code{<namendo>_vs_<namexo>}: for entries of the matrix of the shocks.
@end itemize

The following files are stored in each directory (we stick with prior sample but similar convetins are used for MC samples):
@itemize
@item
@code{<mod_file>_prior_<namendo>_vs_<namexo>.fig}: histogram and CDF plot of the MC sample of the individual entry
of the shock matrix, in sample and out of sample fit of the ANOVA model;

@item
@code{<mod_file>_prior_<namendo>_vs_<namexo>_map_SE.fig}: for entries of the shock matrix it shows graphs of the estimated first order ANOVA terms @math{y = f(\theta_i)} for each deep parameter @math{\theta_i}; 

@item
@code{<mod_file>_prior_<namendo>_vs_<namlagendo>.fig}: histogram and CDF plot of the MC sample of the individual entry
of the transition matrix, in sample and out of sample fit of the ANOVA model;

@item
@code{<mod_file>_prior_<namendo>_vs_<namlagendo>_map_SE.fig}: for entries of the transition matrix it shows graphs of the estimated first order ANOVA terms @math{y = f(\theta_i)} for each deep parameter @math{\theta_i}; 

@item
@code{<mod_file>_prior_<namendo>_vs_<namexo>_map.mat}, @code{<mod_file>_<namendo>_vs_<namlagendo>_map.mat}: these files store info in the estimation; 

@end itemize

When option @code{logtrans_redform} is set, the ANOVA estimation is performed using a log-transformation of each @code{y}.
The ANOVA mapping is then transformed back onto the original scale, to allow comparability with the baseline estimation.
Graphs for this log-transformed case, are stored in the same folder in files denoted with the @code{_log} suffix.

When the option @code{threshold_redform} is set, the analysis is performed via Monte Carlo filtering, by displaying parameters that drive the individual entry @code{y} inside the range specified in @code{threshold_redform}. If no entry is found (or all entries are in the range), the MCF algorithm ignores the range specified in @code{threshold_redform} and performs the analysis splitting the MC sample of @code{y} into deciles. Setting @code{threshold_redform=[-inf inf]} triggers this approach for all @code{y}'s.

Results are stored in subdirectories of @code{<mod_file>/gsa/redform_prior} named 
@itemize
@item
@code{<mod_file>_prior_<namendo>_vs_<namlagendo>_threshold}: for the entries of the transition matrix;

@item
@code{<mod_file>_prior_<namendo>_vs_<namexo>_threshold}: for entries of the matrix of the shocks.
@end itemize

The files saved are named
@itemize
@item
@code{<mod_file>_prior_<namendo>_vs_<namexo>_threshold.fig},@code{<mod_file>_<namendo>_vs_<namlagendo>_threshold.fig}: graphical outputs; 
@item
@code{<mod_file>_prior_<namendo>_vs_<namexo>_threshold.mat},@code{<mod_file>_<namendo>_vs_<namlagendo>_threshold.mat}: info on the analysis; 

@end itemize

@node RMSE
@subsubsection RMSE

The RMSE analysis can be performed with different types of sampling options:
@enumerate
@item
When @code{pprior=1} and @code{ppost=0}, the toolbox analyzes the RMSEs for
the Monte-Carlo sample obtained by sampling parameters from their prior distributions
(or prior ranges): this analysis provides some hints about
what parameter drives the fit of which observed series, prior to the full
estimation;

@item
When @code{pprior=0} and @code{ppost=0}, the toolbox analyzes the RMSEs for
a multivariate normal Monte-Carlo sample, with covariance matrix based on
the inverse Hessian at the optimum: this analysis is useful when maximum likelihood
estimation is done (@i{i.e.} no Bayesian estimation);

@item
When @code{ppost=1} the toolbox analyzes the RMSEs for the posterior sample
obtained by Dynare's Metropolis procedure.
@end enumerate

The use of cases 2 and 3 requires an estimation step beforehand. To
facilitate the sensitivity analysis after estimation, the @code{dynare_sensitivity}
command also allows you to indicate some options of the @code{estimation}
command. These are:
@itemize @bullet
@item @code{datafile}
@item @code{nobs}
@item @code{first_obs}
@item @code{prefilter}
@item @code{presample}
@item @code{nograph}
@item @code{nodisplay}
@item @code{graph_format}
@item @code{conf_sig}
@item @code{loglinear}
@item @code{mode_file}
@end itemize

Binary files produced my RMSE analysis are:
@itemize
@item
@code{<mod_file>_prior_*.mat}: these files store the filtered and smoothed
    variables for the prior Monte-Carlo sample, generated when doing RMSE analysis
    (@code{pprior=1} and @code{ppost=0});
@item
@code{<mode_file>_mc_*.mat}: these files store the filtered and smoothed variables
    for the multivariate normal Monte-Carlo sample, generated when doing
    RMSE analysis (@code{pprior=0} and @code{ppost=0}).
@end itemize

Figure files @code{<mod_file>_rmse_*.fig} store results for the RMSE analysis.

@itemize
@item
@code{<mod_file>_rmse_prior*.fig}: save results for the analysis using prior
Monte-Carlo samples;

@item
@code{<mod_file>_rmse_mc*.fig}: save results for the analysis using multivariate
normal Monte-Carlo samples;

@item
@code{<mod_file>_rmse_post*.fig}: save results for the analysis using Metropolis
posterior samples.
@end itemize

The following types of figures are saved (we show prior sample to fix ideas,
but the same conventions are used for multivariate normal and posterior):

@itemize
@item
@code{<mod_file>_rmse_prior_params_*.fig}: for each parameter, plots the cdfs 
corresponding to the best 10% RMSEs of each observed series (only those cdfs below the significance threshold @code{alpha_rmse});

@item
@code{<mod_file>_rmse_prior_<var_obs>_*.fig}: if a parameter significantly affects the fit of @code{var_obs}, all possible trade-off's with other observables for same parameter are plotted;

@item
@code{<mod_file>_rmse_prior_<var_obs>_map.fig}: plots the MCF analysis of parameters significantly driving the fit the observed series @code{var_obs};

@item
@code{<mod_file>_rmse_prior_lnlik*.fig}: for each observed series, plots
in BLUE the cdf of the log-likelihood corresponding to the best 10%
RMSEs, in RED the cdf of the rest of the sample and in BLACK the
cdf of the full sample; this allows one to see the presence of some
idiosyncratic behavior;

@item
@code{<mod_file>_rmse_prior_lnpost*.fig}: for each observed series, plots
in BLUE the cdf of the log-posterior corresponding to the best 10% RMSEs,
in RED the cdf of the rest of the sample and in BLACK the cdf of the full
sample; this allows one to see idiosyncratic behavior;

@item
@code{<mod_file>_rmse_prior_lnprior*.fig}: for each observed series, plots
in BLUE the cdf of the log-prior corresponding to the best 10% RMSEs,
in RED the cdf of the rest of the sample and in BLACK the cdf of the full
sample; this allows one to see idiosyncratic behavior;

@item
@code{<mod_file>_rmse_prior_lik.fig}: when @code{lik_only=1}, this shows
the MCF tests for the filtering of the best 10% log-likelihood values;

@item
@code{<mod_file>_rmse_prior_post.fig}: when @code{lik_only=1}, this shows
the MCF tests for the filtering of the best 10% log-posterior values.
@end itemize

@node Screening Analysis
@subsubsection Screening Analysis

Screening analysis does not require any additional options with respect to
those listed in @ref{Sampling Options}. The toolbox performs all the
analyses required and displays results.

The results of the screening analysis with Morris sampling design are stored
in the subfolder @code{<mod_file>/gsa/screen}. The data file @code{<mod_file>_prior} stores
all the information of the analysis (Morris sample, reduced form coefficients,
etc.).

Screening analysis merely concerns reduced form coefficients. Similar
synthetic bar charts as for the reduced form analysis with Monte-Carlo samples are
saved:
@itemize
@item
@code{<mod_file>_redform_<endo name>_vs_lags_*.fig}: shows bar charts
of the elementary effect tests for the ten most important parameters
driving the reduced form coefficients of the selected endogenous variables
(@code{namendo}) versus lagged endogenous variables (@code{namlagendo});

@item
@code{<mod_file>_redform_<endo name>_vs_shocks_*.fig}: shows bar charts
of the elementary effect tests for the ten most important parameters
driving the reduced form coefficients of the selected endogenous variables
(@code{namendo}) versus exogenous variables (@code{namexo});

@item
@code{<mod_file>_redform_screen.fig}: shows bar chart of all elementary
effect tests for each parameter: this allows one to identify parameters that
have a minor effect for any of the reduced form coefficients.
@end itemize

@node Identification Analysis
@subsubsection Identification Analysis

Setting the option @code{identification=1}, an identification analysis based on
theoretical moments is performed. Sensitivity plots are provided that allow
to infer which parameters are most likely to be less identifiable.

Prerequisite for properly running all the identification routines, is the keyword
@code{identification}; in the Dynare model file. This keyword triggers
the computation of analytic derivatives of the model with respect to estimated
parameters and shocks. This is required for option @code{morris=2},
which implements @cite{Iskrev (2010)} identification analysis.

For example, the placing @code{identification; dynare_sensitivity(identification=1, morris=2);}
in the Dynare model file trigger identification analysis using analytic derivatives
@cite{Iskrev (2010)}, jointly with the mapping of the acceptable region.

The identification analysis with derivatives can also be triggered by the
commands @code{identification;} This does not do the mapping of
acceptable regions for the model and uses the standard random sampler of Dynare.
It completely offsets any use of the sensitivity analysis toolbox.


@node Markov-switching SBVAR
@section Markov-switching SBVAR

Given a list of variables, observed variables and a data file, Dynare
can be used to solve a Markov-switching SBVAR model according to
@cite{Sims, Waggoner and Zha (2008)}.@footnote{If you want to align
the paper with the description herein, please note that @math{A} is
@math{A^0} and @math{F} is @math{A^+}.} Having done this, you can
create forecasts and compute the marginal data density, regime
probabilities, IRFs, and variance decomposition of the model.

The commands have been modularized, allowing for multiple calls to the
same command within a @code{<mod_file>.mod} file. The default is to use
@code{<mod_file>} to tag the input (output) files used (produced) by the
program. Thus, to call any command more than once within a
@code{<mod_file>.mod} file, you must use the @code{*_tag} options
described below.

@anchor{markov_switching}
@deffn Command markov_switching (@var{OPTIONS}@dots{});
@descriptionhead

Declares the Markov state variable information of a Markov-switching
SBVAR model.

@optionshead

@table @code

@item chain = @var{INTEGER}
@anchor{ms_chain} The Markov chain considered. Default: @code{none} 

@item number_of_regimes = @var{INTEGER}
Specifies the total number of regimes in the Markov Chain. This is a required option.

@item duration = @var{DOUBLE} | @var{[ROW VECTOR OF DOUBLES]}
The duration of the regimes or regimes. This is a required option. 
When passed a scalar real number, it specifies the average duration for all regimes in 
this chain. When passed a vector of size equal @code{number_of_regimes}, it specifies 
the average duration of the associated regimes @code{(1:number_of_regimes)} in this chain.
An absorbing state can be specified through the @ref{restrictions}-option.

@item restrictions = @var{[[ROW VECTOR OF 3 DOUBLES],[ROW VECTOR OF 3 DOUBLES],...]}
@anchor{restrictions}
Provides restrictions on this chain's regime transition matrix. 
Its vector argument takes three inputs of the form: 
@code{[current_period_regime, next_period_regime, transition_probability]} 

The first two entries are positive integers, and the third is a non-negative real in the set [0,1]. 
If restrictions are specified for every transition for a regime, the sum of the probabilities 
must be 1. Otherwise, if restrictions are not provided for every transition for a given 
regime the sum of the provided transition probabilities msut be <1. 
Regardless of the number of lags, the restrictions are specified for parameters 
at time @code{t} since the transition probability for a parameter at @code{t} is equal to 
that of the parameter at @code{t-1}. 

@end table

In case of estimating a MS-DSGE model,@footnote{An example can be found at @uref{https://github.com/DynareTeam/dynare/blob/master/tests/ms-dsge/test_ms_dsge.mod}.} in addition the following options are allowed:

@table @code

@item parameters = @var{[LIST OF PARAMETERS]}
This option specifies which parameters are controlled by this Markov Chai

@item number_of_lags = @var{DOUBLE}
Provides the number of lags that each parameter can take within each regime in this chain. 

@end table

@examplehead

@example
markov_switching(chain=1, duration=2.5, restrictions=[[1,3,0],[3,1,0]]);
@end example
Specifies a Markov-switching BVAR with a first chain with 3 regimes that all have a 
duration of 2.5 periods. The probability of directly going from regime 1 to regime 3 and vice versa is 0.

@examplehead

@example
markov_switching(chain=2, number_of_regimes=3, duration=[0.5, 2.5, 2.5],
parameter=[alpha, rho], number_of_lags=2, restrictions=[[1,3,0],[3,3,1]]);
@end example

Specifies a Markov-switching DSGE model with a second chain with 3 regimes 
that have durations of 0.5, 2.5, and 2.5 periods, respectively. The switching parameters
are @code{alpha} and @code{rho}. The probability of directly going from 
regime 1 to regime 3 is 0, while regime 3 is an absorbing state.

@end deffn


@anchor{svar}
@deffn Command svar (@var{OPTIONS}@dots{});
@descriptionhead

Each Markov chain can control the switching of a set of parameters. We
allow the parameters to be divided equation by equation and by variance
or slope and intercept.

@optionshead

@table @code

@item coefficients
Specifies that only the slope and intercept in the given equations are
controlled by the given chain.  One, but not both, of
@code{coefficients} or @code{variances} must appear. Default:
@code{none}

@item variances
Specifies that only variances in the given equations are controlled by
the given chain. One, but not both, of @code{coefficients} or
@code{variances} must appear. Default: @code{none}

@item equations
Defines the equation controlled by the given chain. If not specified,
then all equations are controlled by @code{chain}. Default: @code{none}

@item chain = @var{INTEGER}
Specifies a Markov chain defined by @ref{markov_switching}. Default:
@code{none}

@end table
@end deffn


@deffn Command sbvar (@var{OPTIONS}@dots{});
@descriptionhead

To be documented. For now, see the wiki: @uref{http://www.dynare.org/DynareWiki/SbvarOptions}

@optionshead

@table @code

@item datafile
@item freq
@item initial_year
@item initial_subperiod
@item final_year
@item final_subperiod
@item data
@item vlist
@item vlistlog
@item vlistper
@item restriction_fname
@item nlags
@item cross_restrictions
@item contemp_reduced_form
@item real_pseudo_forecast
@item no_bayesian_prior
@item dummy_obs
@item nstates
@item indxscalesstates
@item alpha
@item beta
@item gsig2_lmdm
@item q_diag
@item flat_prior
@item ncsk
@item nstd
@item ninv
@item indxparr
@item indxovr
@item aband
@item indxap
@item apband
@item indximf
@item indxfore
@item foreband
@item indxgforhat
@item indxgimfhat
@item indxestima
@item indxgdls
@item eq_ms
@item cms
@item ncms
@item eq_cms
@item tlindx
@item tlnumber
@item cnum
@item forecast
@item coefficients_prior_hyperparameters

@end table
@end deffn


@deffn Block svar_identification ;

@descriptionhead

This block is terminated by @code{end;}, and contains lines of the
form:
@example
UPPER_CHOLESKY;
LOWER_CHOLESKY;
EXCLUSION CONSTANTS;
EXCLUSION LAG @var{INTEGER}; @var{VARIABLE_NAME} [,@var{VARIABLE_NAME}@dots{}]
EXCLUSION LAG @var{INTEGER}; EQUATION @var{INTEGER}, @var{VARIABLE_NAME} [,@var{VARIABLE_NAME}@dots{}]
RESTRICTION EQUATION @var{INTEGER}, @var{EXPRESSION} = @var{EXPRESSION};
@end example

To be documented. For now, see the wiki: @uref{http://www.dynare.org/DynareWiki/MarkovSwitchingInterface}

@end deffn

@anchor{ms_estimation}
@deffn Command ms_estimation (@var{OPTIONS}@dots{});
@descriptionhead

Triggers the creation of an initialization file for, and the estimation
of, a Markov-switching SBVAR model. At the end of the run, the
@math{A^0}, @math{A^+}, @math{Q} and @math{\zeta} matrices are contained
in the @code{oo_.ms} structure.

@optionshead

@customhead{General Options}
@table @code

@item file_tag = @var{FILENAME}
The portion of the filename associated with this run. This will create
the model initialization file, @code{init_<file_tag>.dat}. Default:
@code{<mod_file>}

@item output_file_tag = @var{FILENAME}
The portion of the output filename that will be assigned to this run.
This will create, among other files,
@code{est_final_<output_file_tag>.out},
@code{est_intermediate_<output_file_tag>.out}. Default:
@code{<file_tag>}

@item no_create_init
Do not create an initialization file for the model. Passing this option
will cause the @i{Initialization Options} to be ignored. Further, the
model will be generated from the output files associated with the
previous estimation run (@i{i.e.} @code{est_final_<file_tag>.out},
@code{est_intermediate_<file_tag>.out} or @code{init_<file_tag>.dat},
searched for in sequential order). This functionality can be useful for
continuing a previous estimation run to ensure convergence was reached
or for reusing an initialization file. NB: If this option is not passed,
the files from the previous estimation run will be overwritten. Default:
@code{off} (@i{i.e.} create initialization file)

@end table
@customhead{Initialization Options}
@table @code

@item coefficients_prior_hyperparameters = [@var{DOUBLE1} @var{DOUBLE2} @var{DOUBLE3} @var{DOUBLE4} @var{DOUBLE5} @var{DOUBLE6}]
Sets the hyper parameters for the model. The six elements of the
argument vector have the following interpretations:

@table @code

@item Position
@code{Interpretation}

@item 1
Overall tightness for @math{A^0} and @math{A^+}

@item 2
Relative tightness for @math{A^+}

@item 3
Relative tightness for the constant term

@item 4
Tightness on lag decay (range: 1.2 - 1.5); a faster decay produces
better inflation process

@item 5
Weight on nvar sums of coeffs dummy observations (unit roots)

@item 6
Weight on single dummy initial observation including constant

@end table

Default: @code{[1.0 1.0 0.1 1.2 1.0 1.0]}

@item freq = @var{INTEGER} | @code{monthly} | @code{quarterly} | @code{yearly}
Frequency of the data (@i{e.g.} @code{monthly}, @code{12}). Default:
@code{4}

@item initial_year = @var{INTEGER}
The first year of data. Default: @code{none}

@item initial_subperiod = @var{INTEGER}
The first period of data (@i{i.e.} for quarterly data, an integer in
[@code{1,4}]). Default: @code{1}

@item final_year = @var{INTEGER}
The last year of data. Default: Set to encompass entire dataset.

@item final_subperiod = @var{INTEGER}
The final period of data (@i{i.e.} for monthly data, an integer in
[@code{1,12}]. Default: When final_year is also missing, set to
encompass entire dataset; when final_year is indicated, set to the
maximum number of subperiods given the frequency (@i{i.e}. 4 for
quarterly data, 12 for monthly,...).

@item datafile = @var{FILENAME}
@xref{datafile}.

@item xls_sheet = @var{NAME}
@xref{xls_sheet}.

@item xls_range = @var{RANGE}
@xref{xls_range}.

@item nlags = @var{INTEGER}
The number of lags in the model. Default: @code{1}

@item cross_restrictions
Use cross @math{A^0} and @math{A^+} restrictions. Default: @code{off}

@item contemp_reduced_form
Use contemporaneous recursive reduced form. Default: @code{off}

@item no_bayesian_prior
Do not use Bayesian prior. Default: @code{off} (@i{i.e.} use Bayesian
prior)

@item alpha = @var{INTEGER}
Alpha value for squared time-varying structural shock lambda. Default:
@code{1}

@item beta = @var{INTEGER}
Beta value for squared time-varying structural shock lambda. Default:
@code{1}

@item gsig2_lmdm = @var{INTEGER}
The variance for each independent @math{\lambda} parameter under
@code{SimsZha} restrictions. Default: @code{50^2}

@item specification = @code{sims_zha} | @code{none}
This controls how restrictions are imposed to reduce the number of
parameters. Default: @code{Random Walk}

@end table
@customhead{Estimation Options}
@table @code

@item convergence_starting_value = @var{DOUBLE}
This is the tolerance criterion for convergence and refers to changes in
the objective function value. It should be rather loose since it will
gradually be tightened during estimation. Default: @code{1e-3}

@item convergence_ending_value = @var{DOUBLE}
The convergence criterion ending value. Values much smaller than square
root machine epsilon are probably overkill. Default: @code{1e-6}

@item convergence_increment_value = @var{DOUBLE}
Determines how quickly the convergence criterion moves from the starting
value to the ending value. Default: @code{0.1}

@item max_iterations_starting_value = @var{INTEGER}
This is the maximum number of iterations allowed in the hill-climbing
optimization routine and should be rather small since it will gradually
be increased during estimation. Default: @code{50}

@item max_iterations_increment_value = @var{DOUBLE}
Determines how quickly the maximum number of iterations is
increased. Default: @code{2}

@item max_block_iterations = @var{INTEGER}
@anchor{max_block_iterations} The parameters are divided into blocks and
optimization proceeds over each block. After a set of blockwise
optimizations are performed, the convergence criterion is checked and
the blockwise optimizations are repeated if the criterion is
violated. This controls the maximum number of times the blockwise
optimization can be performed. Note that after the blockwise
optimizations have converged, a single optimization over all the
parameters is performed before updating the convergence value and
maximum number of iterations. Default: @code{100}

@item max_repeated_optimization_runs = @var{INTEGER}
The entire process described by @ref{max_block_iterations} is repeated
until improvement has stopped. This is the maximum number of times the
process is allowed to repeat. Set this to @code{0} to not allow
repetitions. Default: @code{10}

@item function_convergence_criterion = @var{DOUBLE}
The convergence criterion for the objective function when
@code{max_repeated_optimizations_runs} is positive. Default: @code{0.1}

@item parameter_convergence_criterion = @var{DOUBLE}
The convergence criterion for parameter values when
@code{max_repeated_optimizations_runs} is positive. Default: @code{0.1}

@item number_of_large_perturbations = @var{INTEGER}
The entire process described by @ref{max_block_iterations} is repeated
with random starting values drawn from the posterior. This specifies the
number of random starting values used. Set this to @code{0} to not use
random starting values. A larger number should be specified to ensure
that the entire parameter space has been covered. Default: @code{5}

@item number_of_small_perturbations = @var{INTEGER}
The number of small perturbations to make after the large perturbations
have stopped improving. Setting this number much above @code{10} is
probably overkill. Default: @code{5}

@item number_of_posterior_draws_after_perturbation = @var{INTEGER}
The number of consecutive posterior draws to make when producing a small
perturbation. Because the posterior draws are serially correlated, a
small number will result in a small perturbation. Default: @code{1}

@item max_number_of_stages = @var{INTEGER}
The small and large perturbation are repeated until improvement has
stopped. This specifics the maximum number of stages allowed. Default:
@code{20}

@item random_function_convergence_criterion = @var{DOUBLE}
The convergence criterion for the objective function when
@code{number_of_large_perturbations} is positive. Default: @code{0.1}

@item random_parameter_convergence_criterion = @var{DOUBLE}
The convergence criterion for parameter values when
@code{number_of_large_perturbations} is positive. Default: @code{0.1}

@end table
@end deffn

@examplehead

@example
ms_estimation(datafile=data, initial_year=1959, final_year=2005,
nlags=4, max_repeated_optimization_runs=1, max_number_of_stages=0);

ms_estimation(file_tag=second_run, datafile=data, initial_year=1959,
final_year=2005, nlags=4, max_repeated_optimization_runs=1,
max_number_of_stages=0);

ms_estimation(file_tag=second_run, output_file_tag=third_run,
no_create_init, max_repeated_optimization_runs=5,
number_of_large_perturbations=10);
@end example


@anchor{ms_simulation}
@deffn Command ms_simulation ;
@deffnx Command ms_simulation (@var{OPTIONS}@dots{});
@descriptionhead

Simulates a Markov-switching SBVAR model.

@optionshead

@table @code

@item file_tag = @var{FILENAME}
@anchor{file_tag} The portion of the filename associated with the
@code{ms_estimation} run. Default: @code{<mod_file>}

@item output_file_tag = @var{FILENAME}
@anchor{output_file_tag} The portion of the output filename that will be
assigned to this run. Default: @code{<file_tag>}

@item mh_replic = @var{INTEGER}
The number of draws to save. Default: @code{10,000}

@item drop = @var{INTEGER}
The number of burn-in draws. Default:
@code{0.1*mh_replic*thinning_factor}

@item thinning_factor = @var{INTEGER}
The total number of draws is equal to
@code{thinning_factor*mh_replic+drop}.  Default: @code{1}

@item adaptive_mh_draws = @var{INTEGER}
Tuning period for Metropolis-Hastings draws. Default: @code{30,000}

@item save_draws
Save all elements of @math{A^0}, @math{A^+}, @math{Q}, and
@math{\zeta}, to a file named @code{draws_<<file_tag>>.out} with each
draw on a separate line. A file that describes how these matrices are
laid out is contained in @code{draws_header_<<file_tag>>.out}. A file
called @code{load_flat_file.m} is provided to simplify loading the
saved files into the corresponding variables @code{A0}, @code{Aplus},
@code{Q}, and @code{Zeta} in your MATLAB/Octave workspace. Default:
@code{off}

@end table
@end deffn

@examplehead

@example
ms_simulation(file_tag=second_run);

ms_simulation(file_tag=third_run, mh_replic=5000, thinning_factor=3);
@end example


@anchor{ms_compute_mdd}
@deffn Command ms_compute_mdd ;
@deffnx Command ms_compute_mdd (@var{OPTIONS}@dots{});
@descriptionhead

Computes the marginal data density of a Markov-switching SBVAR model
from the posterior draws. At the end of the run, the Muller and Bridged
log marginal densities are contained in the @code{oo_.ms} structure.

@optionshead

@table @code

@item file_tag = @var{FILENAME}
@xref{file_tag}.

@item output_file_tag = @var{FILENAME}
@xref{output_file_tag}.

@item simulation_file_tag = @var{FILENAME}
@anchor{simulation_file_tag} The portion of the filename associated with
the simulation run.  Default: @code{<file_tag>}

@item proposal_type = @var{INTEGER}
The proposal type:
@table @code

@item 1
Gaussian

@item 2
Power

@item 3
Truncated Power

@item 4
Step

@item 5
Truncated Gaussian

@end table

Default: @code{3}

@item proposal_lower_bound = @var{DOUBLE}
The lower cutoff in terms of probability. Not used for
@code{proposal_type} in [@code{1,2}]. Required for all other proposal
types. Default: @code{0.1}

@item proposal_upper_bound = @var{DOUBLE}
The upper cutoff in terms of probability. Not used for
@code{proposal_type} equal to @code{1}. Required for all other proposal
types. Default: @code{0.9}

@item mdd_proposal_draws = @var{INTEGER}
The number of proposal draws. Default: @code{100,000}

@item mdd_use_mean_center
Use the posterior mean as center. Default: @code{off}

@end table

@end deffn


@anchor{ms_compute_probabilities}
@deffn Command ms_compute_probabilities ;
@deffnx Command ms_compute_probabilities (@var{OPTIONS}@dots{});
@descriptionhead

Computes smoothed regime probabilities of a Markov-switching SBVAR
model. Output @code{.eps} files are contained in
@code{<output_file_tag/Output/Probabilities>}.

@optionshead

@table @code

@item file_tag = @var{FILENAME}
@xref{file_tag}.

@item output_file_tag = @var{FILENAME}
@xref{output_file_tag}.

@item filtered_probabilities
Filtered probabilities are computed instead of smoothed. Default:
@code{off}

@item real_time_smoothed
Smoothed probabilities are computed based on time @code{t} information
for @math{0\le t\le nobs}. Default: @code{off}

@end table

@end deffn


@anchor{ms_irf}
@deffn Command ms_irf ;
@deffnx Command ms_irf (@var{OPTIONS}@dots{});
@descriptionhead

Computes impulse response functions for a Markov-switching SBVAR
model. Output @code{.eps} files are contained in
@code{<output_file_tag/Output/IRF>}, while data files are contained in
@code{<output_file_tag/IRF>}.

@optionshead

@table @code

@item file_tag = @var{FILENAME}
@xref{file_tag}.

@item output_file_tag = @var{FILENAME}
@xref{output_file_tag}.

@item simulation_file_tag = @var{FILENAME}
@xref{simulation_file_tag}.

@item horizon = @var{INTEGER}
@anchor{horizon} The forecast horizon. Default: @code{12}

@item filtered_probabilities
@anchor{filtered_probabilities} Uses filtered probabilities at the end
of the sample as initial conditions for regime probabilities. Only one
of @code{filtered_probabilities}, @code{regime} and @code{regimes} may
be passed. Default: @code{off}

@item error_band_percentiles = [@var{DOUBLE1} @dots{}]
@anchor{error_band_percentiles} The percentiles to compute. Default:
@code{[0.16 0.50 0.84]}. If @code{median} is passed, the default
is @code{[0.5]}

@item shock_draws = @var{INTEGER}
@anchor{shock_draws} The number of regime paths to draw. Default:
@code{10,000}

@item shocks_per_parameter = @var{INTEGER}
@anchor{shocks_per_parameter} The number of regime paths to draw under
parameter uncertainty. Default: @code{10}

@item thinning_factor = @var{INTEGER}
@anchor{thinning_factor} Only @math{1/@code{thinning_factor}} of the
draws in posterior draws file are used. Default: @code{1}

@item free_parameters = @var{NUMERICAL_VECTOR}
@anchor{free_parameters} A vector of free parameters to initialize theta
of the model. Default: use estimated parameters

@item parameter_uncertainty
@anchor{parameter_uncertainty} Calculate IRFs under parameter
uncertainty. Requires that @command{ms_simulation} has been
run. Default: @code{off}

@item regime = @var{INTEGER}
@anchor{regime} Given the data and model parameters, what is the ergodic
probability of being in the specified regime. Only one of
@code{filtered_probabilities}, @code{regime} and @code{regimes} may be
passed. Default: @code{off}

@item regimes
@anchor{regimes} Describes the evolution of regimes. Only one of
@code{filtered_probabilities}, @code{regime} and @code{regimes} may be
passed. Default: @code{off}

@item median
@anchor{median} A shortcut to setting
@code{error_band_percentiles=[0.5]}. Default: @code{off}

@end table

@end deffn


@anchor{ms_forecast}
@deffn Command ms_forecast ;
@deffnx Command ms_forecast (@var{OPTIONS}@dots{});
@descriptionhead

Generates forecasts for a Markov-switching SBVAR model. Output
@code{.eps} files are contained in @code{<output_file_tag/Output/Forecast>},
while data files are contained in @code{<output_file_tag/Forecast>}.

@optionshead

@table @code

@item file_tag = @var{FILENAME}
@xref{file_tag}.

@item output_file_tag = @var{FILENAME}
@xref{output_file_tag}.

@item simulation_file_tag = @var{FILENAME}
@xref{simulation_file_tag}.

@item data_obs_nbr = @var{INTEGER}
The number of data points included in the output. Default: @code{0}

@item error_band_percentiles = [@var{DOUBLE1} @dots{}]
@xref{error_band_percentiles}.

@item shock_draws = @var{INTEGER}
@xref{shock_draws}.

@item shocks_per_parameter = @var{INTEGER}
@xref{shocks_per_parameter}.

@item thinning_factor = @var{INTEGER}
@xref{thinning_factor}.

@item free_parameters = @var{NUMERICAL_VECTOR}
@xref{free_parameters}.

@item parameter_uncertainty
@xref{parameter_uncertainty}.

@item regime = @var{INTEGER}
@xref{regime}.

@item regimes
@xref{regimes}.

@item median
@xref{median}.

@item horizon = @var{INTEGER}
@xref{horizon}.

@end table

@end deffn


@anchor{ms_variance_decomposition}
@deffn Command ms_variance_decomposition ;
@deffnx Command ms_variance_decomposition (@var{OPTIONS}@dots{});
@descriptionhead

Computes the variance decomposition for a Markov-switching SBVAR
model. Output @code{.eps} files are contained in
@code{<output_file_tag/Output/Variance_Decomposition>}, while data files
are contained in @code{<output_file_tag/Variance_Decomposition>}.

@optionshead

@table @code

@item file_tag = @var{FILENAME}
@xref{file_tag}.

@item output_file_tag = @var{FILENAME}
@xref{output_file_tag}.

@item simulation_file_tag = @var{FILENAME}
@xref{simulation_file_tag}.

@item horizon = @var{INTEGER}
@xref{horizon}.

@item filtered_probabilities
@xref{filtered_probabilities}.

@item no_error_bands
Do not output percentile error bands (@i{i.e.} compute mean). Default:
@code{off} (@i{i.e.} output error bands)

@item error_band_percentiles = [@var{DOUBLE1} @dots{}]
@xref{error_band_percentiles}.

@item shock_draws = @var{INTEGER}
@xref{shock_draws}.

@item shocks_per_parameter = @var{INTEGER}
@xref{shocks_per_parameter}.

@item thinning_factor = @var{INTEGER}
@xref{thinning_factor}.

@item free_parameters = @var{NUMERICAL_VECTOR}
@xref{free_parameters}.

@item parameter_uncertainty
@xref{parameter_uncertainty}.

@item regime = @var{INTEGER}
@xref{regime}.

@item regimes

@xref{regimes}.

@end table

@end deffn


@node Displaying and saving results
@section Displaying and saving results

Dynare has comments to plot the results of a simulation and to save the results.

@deffn Command rplot @var{VARIABLE_NAME}@dots{};
@anchor{rplot}
Plots the simulated path of one or several variables, as stored in
@code{oo_.endo_simul} by either @code{perfect_foresight_solver}, @code{simul}
(@pxref{Deterministic simulation}) or @code{stoch_simul} with option
@code{periods} (@pxref{Computing the stochastic solution}). The variables are
plotted in levels.

@end deffn


@deffn Command dynatype (@var{FILENAME}) [@var{VARIABLE_NAME}@dots{}];
This command prints the listed variables in a text file named
@var{FILENAME}. If no @var{VARIABLE_NAME} is listed, all endogenous
variables are printed.
@end deffn

@deffn Command dynasave (@var{FILENAME}) [@var{VARIABLE_NAME}@dots{}];

This command saves the listed variables in a binary file named
@var{FILENAME}. If no @var{VARIABLE_NAME} are listed, all endogenous
variables are saved.

In MATLAB or Octave, variables saved with the @code{dynasave} command
can be retrieved by the command:

@example
load -mat @var{FILENAME}
@end example

@end deffn

@node Macro-processing language
@section Macro-processing language

It is possible to use ``macro'' commands in the @file{.mod} file for
doing the following tasks: including modular source files, replicating
blocks of equations through loops, conditionally executing some code,
writing indexed sums or products inside equations@dots{}

The Dynare macro-language provides a new set of @emph{macro-commands}
which can be inserted inside @file{.mod} files. It features:

@itemize
@item
file inclusion

@item
loops (@code{for} structure)

@item
conditional inclusion (@code{if/then/else} structures)

@item
expression substitution
@end itemize

Technically, this macro language is totally independent of the basic
Dynare language, and is processed by a separate component of the
Dynare pre-processor. The macro processor transforms a @file{.mod}
file with macros into a @file{.mod} file without macros (doing
expansions/inclusions), and then feeds it to the Dynare parser. The
key point to understand is that the macro-processor only does
@emph{text substitution} (like the C preprocessor or the PHP
language).  Note that it is possible to see the output of the
macro-processor by using the @code{savemacro} option of the
@code{dynare} command (@pxref{Dynare invocation}).

The macro-processor is invoked by placing @emph{macro directives} in
the @file{.mod} file. Directives begin with an at-sign followed by a
pound sign (@code{@@#}). They produce no output, but give instructions
to the macro-processor. In most cases, directives occupy exactly one
line of text. In case of need, two anti-slashes (@code{\\}) at the end
of the line indicates that the directive is continued on the next
line. The main directives are:
@itemize
@item
@code{@@#includepath}, paths to search for files that are to be included,
@item
@code{@@#include}, for file inclusion,
@item
@code{@@#define}, for defining a macro-processor variable,
@item
@code{@@#if}, @code{@@#ifdef}, @code{@@#ifndef}, @code{@@#else},
@code{@@#endif} for conditional statements,
@item
@code{@@#for}, @code{@@#endfor} for constructing loops.
@end itemize

The macro-processor maintains its own list of variables (distinct of
model variables and of MATLAB/Octave variables). These macro-variables
are assigned using the @code{@@#define} directive, and can be of four
types: integer, character string, array of integers, array of
strings.

@menu
* Macro expressions::
* Macro directives::
* Typical usages::
* MATLAB/Octave loops versus macro-processor loops::
@end menu

@node Macro expressions
@subsection Macro expressions

It is possible to construct macro-expressions which can be assigned to
macro-variables or used within a macro-directive. The expressions are
constructed using literals of the four basic types (integers, strings,
arrays of strings, arrays of integers), macro-variables names and
standard operators.

String literals have to be enclosed between @strong{double} quotes
(like @code{"name"}). Arrays are enclosed within brackets, and their
elements are separated by commas (like @code{[1,2,3]} or @code{["US",
"EA"]}).

Note that there is no boolean type: @emph{false} is represented by integer zero
and @emph{true} is any non-null integer. Further note that, as the
macro-processor cannot handle non-integer real numbers, integer division
results in the quotient with the fractional part truncated (hence,
@math{5/3=3/3=1}).

The following operators can be used on integers:
@itemize
@item
arithmetic operators: @code{+}, @code{-}, @code{*}, @code{/}
@item
comparison operators: @code{<}, @code{>}, @code{<=}, @code{>=},
@code{==}, @code{!=}
@item
logical operators: @code{&&}, @code{||}, @code{!}
@item
integer ranges, using the following syntax:
@code{@var{INTEGER1}:@var{INTEGER2}} (for example, @code{1:4} is
equivalent to integer array @code{[1,2,3,4]})
@end itemize

The following operators can be used on strings:
@itemize
@item
comparison operators: @code{==}, @code{!=}
@item
concatenation of two strings: @code{+}
@item
extraction of substrings: if @code{@var{s}} is a string, then
@code{@var{s}[3]} is a string containing only the third character of
@code{@var{s}}, and @code{@var{s}[4:6]} contains the characters from
4th to 6th
@end itemize

The following operators can be used on arrays:
@itemize
@item
dereferencing: if @code{@var{v}} is an array, then @code{@var{v}[2]} is its 2nd element
@item
concatenation of two arrays: @code{+}
@item
difference @code{-}: returns the first operand from which the elements
of the second operand have been removed
@item
extraction of sub-arrays: @i{e.g.} @code{@var{v}[4:6]}
@item
testing membership of an array: @code{in} operator (for example:
@code{"b" in ["a", "b", "c"]} returns @code{1})
@item
getting the length of an array: @code{length} operator (for example:
@code{length(["a", "b", "c"])} returns @code{3} and, hence,
@code{1:length(["a", "b", "c"])} is equivalent to integer array
@code{[1,2,3]})
@end itemize

Macro-expressions can be used at two places:
@itemize
@item
inside macro directives, directly;
@item
in the body of the @code{.mod} file, between an at-sign and curly
braces (like @code{@@@{@var{expr}@}}): the macro processor will
substitute the expression with its value.
@end itemize

In the following, @var{MACRO_EXPRESSION} designates an expression
constructed as explained above.

@node Macro directives
@subsection Macro directives

@anchor{@@#includepath}
@deffn {Macro directive} @@#includepath "@var{PATH}"
@deffnx {Macro directive} @@#includepath @var{MACRO_VARIABLE}
This directive adds the colon-separated paths contained in @var{PATH}
to the list of those to search when looking for a @code{.mod} file
specified by @ref{@@#include}. Note that these paths are added
@i{after} any paths passed using @ref{-I}.

@examplehead

@example
@@#include "/path/to/folder/containing/modfiles:/path/to/another/folder"
@@#include folders_containing_mod_files
@end example

@end deffn


@anchor{@@#include}
@deffn {Macro directive} @@#include "@var{FILENAME}"
@deffnx {Macro directive} @@#include @var{MACRO_VARIABLE}
This directive simply includes the content of another file at the
place where it is inserted. It is exactly equivalent to a copy/paste
of the content of the included file. Note that it is possible to nest
includes (@i{i.e.} to include a file from an included file). The file
will be searched for in the current directory. If it is not found, the
file will be searched for in the folders provided by @ref{-I} and
@ref{@@#includepath}.

@examplehead

@example
@@#include "modelcomponent.mod"
@@#include location_of_modfile
@end example

@end deffn

@deffn {Macro directive} @@#define @var{MACRO_VARIABLE} = @var{MACRO_EXPRESSION}
Defines a macro-variable.

@customhead{Example 1}
@example
@@#define x = 5              // Integer
@@#define y = "US"           // String
@@#define v = [ 1, 2, 4 ]    // Integer array
@@#define w = [ "US", "EA" ] // String array
@@#define z = 3 + v[2]       // Equals 5
@@#define t = ("US" in w)    // Equals 1 (true)
@end example

@customhead{Example 2}

@example
@@#define x = [ "B", "C" ]
@@#define i = 2

model;
  A = @@@{x[i]@};
end;
@end example
is strictly equivalent to:
@example
model;
  A = C;
end;
@end example

@end deffn

@deffn {Macro directive} @@#if @var{MACRO_EXPRESSION}
@deffnx {Macro directive} @@#ifdef @var{MACRO_VARIABLE}
@deffnx {Macro directive} @@#ifndef @var{MACRO_VARIABLE}
@deffnx {Macro directive} @@#else
@deffnx {Macro directive} @@#endif
Conditional inclusion of some part of the @file{.mod} file.
The lines between @code{@@#if}, @code{@@#ifdef} or @code{@@#ifndef} and the next
@code{@@#else} or @code{@@#endif} is executed only if the condition
evaluates to a non-null integer. The @code{@@#else} branch is optional
and, if present, is only evaluated if the condition evaluates to
@code{0}.

@examplehead

Choose between two alternative monetary policy rules using a macro-variable:
@example
@@#define linear_mon_pol = 0 // or 1
...
model;
@@#if linear_mon_pol
  i = w*i(-1) + (1-w)*i_ss + w2*(pie-piestar);
@@#else
  i = i(-1)^w * i_ss^(1-w) * (pie/piestar)^w2;
@@#endif
...
end;
@end example

@examplehead

Choose between two alternative monetary policy rules using a
macro-variable. As @code{linear_mon_pol} was not previously defined in
this example, the second equation will be chosen:

@example
model;
@@#ifdef linear_mon_pol
  i = w*i(-1) + (1-w)*i_ss + w2*(pie-piestar);
@@#else
  i = i(-1)^w * i_ss^(1-w) * (pie/piestar)^w2;
@@#endif
...
end;
@end example

Choose between two alternative monetary policy rules using a
macro-variable. As @code{linear_mon_pol} was not previously defined in
this example, the first equation will be chosen:

@example
model;
@@#ifndef linear_mon_pol
  i = w*i(-1) + (1-w)*i_ss + w2*(pie-piestar);
@@#else
  i = i(-1)^w * i_ss^(1-w) * (pie/piestar)^w2;
@@#endif
...
end;
@end example

@end deffn

@deffn {Macro directive} @@#for @var{MACRO_VARIABLE} in @var{MACRO_EXPRESSION}
@deffnx {Macro directive} @@#endfor
Loop construction for replicating portions of the @file{.mod} file.
Note that this construct can enclose variable/parameters declaration,
computational tasks, but not a model declaration.

@examplehead
@example
model;
@@#for country in [ "home", "foreign" ]
  GDP_@@@{country@} = A * K_@@@{country@}^a * L_@@@{country@}^(1-a);
@@#endfor
end;
@end example
is equivalent to:
@example
model;
  GDP_home = A * K_home^a * L_home^(1-a);
  GDP_foreign = A * K_foreign^a * L_foreign^(1-a);
end;
@end example

@end deffn

@deffn {Macro directive} @@#echo @var{MACRO_EXPRESSION}
Asks the preprocessor to display some message on standard output. The
argument must evaluate to a string.
@end deffn

@deffn {Macro directive} @@#error @var{MACRO_EXPRESSION}
Asks the preprocessor to display some error message on standard output
and to abort. The argument must evaluate to a string.
@end deffn

@node Typical usages
@subsection Typical usages

@menu
* Modularization::
* Indexed sums or products::
* Multi-country models::
* Endogeneizing parameters::
@end menu

@node Modularization
@subsubsection Modularization

The @code{@@#include} directive can be used to split @file{.mod} files
into several modular components.

Example setup:

@table @file

@item modeldesc.mod
Contains variable declarations, model equations and shocks declarations
@item simul.mod
Includes @file{modeldesc.mod}, calibrates parameters and runs
stochastic simulations
@item estim.mod
Includes @file{modeldesc.mod}, declares priors on parameters and runs
Bayesian estimation
@end table

Dynare can be called on @file{simul.mod} and @file{estim.mod}, but it
makes no sense to run it on @file{modeldesc.mod}.

The main advantage is that it is no longer needed to manually
copy/paste the whole model (at the beginning) or changes to the model
(during development).

@node Indexed sums or products
@subsubsection Indexed sums or products

The following example shows how to construct a moving average:

@example
@@#define window = 2

var x MA_x;
...
model;
...
MA_x = 1/@@@{2*window+1@}*(
@@#for i in -window:window
        +x(@@@{i@})
@@#endfor
       );
...
end;
@end example

After macro-processing, this is equivalent to:
@example
var x MA_x;
...
model;
...
MA_x = 1/5*(
        +x(-2)
        +x(-1)
        +x(0)
        +x(1)
        +x(2)
       );
...
end;
@end example

@node Multi-country models
@subsubsection Multi-country models

Here is a skeleton example for a multi-country model:

@example
@@#define countries = [ "US", "EA", "AS", "JP", "RC" ]
@@#define nth_co = "US"

@@#for co in countries
var Y_@@@{co@} K_@@@{co@} L_@@@{co@} i_@@@{co@} E_@@@{co@} ...;
parameters a_@@@{co@} ...;
varexo ...;
@@#endfor

model;
@@#for co in countries
 Y_@@@{co@} = K_@@@{co@}^a_@@@{co@} * L_@@@{co@}^(1-a_@@@{co@});
...
@@# if co != nth_co
 (1+i_@@@{co@}) = (1+i_@@@{nth_co@}) * E_@@@{co@}(+1) / E_@@@{co@}; // UIP relation
@@# else
 E_@@@{co@} = 1;
@@# endif
@@#endfor
end;
@end example

@node Endogeneizing parameters
@subsubsection Endogeneizing parameters

When doing the steady state calibration of the model, it may be useful
to consider a parameter as an endogenous (and vice-versa).

For example, suppose production is defined by a CES function:

@math{y = \left(\alpha^{1/\xi} \ell^{1-1/\xi}+(1-\alpha)^{1/\xi}k^{1-1/\xi}\right)^{\xi/(\xi-1)}}

The labor share in GDP is defined as:

@code{lab_rat} @math{= (w \ell)/(p y)}

In the model, @math{\alpha} is a (share) parameter, and
@code{lab_rat} is an endogenous variable.

It is clear that calibrating @math{\alpha} is not straightforward; but
on the contrary, we have real world data for @code{lab_rat}, and
it is clear that these two variables are economically linked.

The solution is to use a method called @emph{variable flipping}, which
consist in changing the way of computing the steady state. During this
computation, @math{\alpha} will be made an endogenous variable and
@code{lab_rat} will be made a parameter. An economically relevant
value will be calibrated for @code{lab_rat}, and the solution
algorithm will deduce the implied value for @math{\alpha}.

An implementation could consist of the following files:

@table @file

@item modeqs.mod
This file contains variable declarations and model equations. The code
for the declaration of @math{\alpha} and @code{lab_rat} would look like:
@example
@@#if steady
 var alpha;
 parameter lab_rat;
@@#else
 parameter alpha;
 var lab_rat;
@@#endif
@end example

@item steady.mod
This file computes the steady state. It begins with:
@example
@@#define steady = 1
@@#include "modeqs.mod"
@end example
Then it initializes parameters (including @code{lab_rat}, excluding
@math{\alpha}, computes the steady state (using guess values for
endogenous, including @math{\alpha}, then saves values of parameters
and endogenous at steady state in a file, using the
@code{save_params_and_steady_state} command.

@item simul.mod
This file computes the simulation. It begins with:
@example
@@#define steady = 0
@@#include "modeqs.mod"
@end example
Then it loads values of parameters and endogenous at steady state from
file, using the @code{load_params_and_steady_state} command, and
computes the simulations.
@end table

@node MATLAB/Octave loops versus macro-processor loops
@subsection MATLAB/Octave loops versus macro-processor loops

Suppose you have a model with a parameter @math{\rho}, and you want to make
simulations for three values: @math{\rho = 0.8, 0.9, 1}. There are
several ways of doing this:

@table @asis

@item With a MATLAB/Octave loop
@example
rhos = [ 0.8, 0.9, 1];
for i = 1:length(rhos)
  rho = rhos(i);
  stoch_simul(order=1);
end
@end example
Here the loop is not unrolled, MATLAB/Octave manages the iterations.
This is interesting when there are a lot of iterations.

@item With a macro-processor loop (case 1)
@example
rhos = [ 0.8, 0.9, 1];
@@#for i in 1:3
  rho = rhos(@@@{i@});
  stoch_simul(order=1);
@@#endfor
@end example
This is very similar to previous example, except that the loop is
unrolled.  The macro-processor manages the loop index but not the data
array (@code{rhos}).

@item With a macro-processor loop (case 2)
@example
@@#for rho_val in [ "0.8", "0.9", "1"]
  rho = @@@{rho_val@};
  stoch_simul(order=1);
@@#endfor
@end example
The advantage of this method is that it uses a shorter syntax, since
list of values directly given in the loop construct. Note that values
are given as character strings (the macro-processor does not know
floating point values. The inconvenient is that you can not reuse an
array stored in a MATLAB/Octave variable.

@end table

@node Verbatim inclusion
@section Verbatim inclusion

Pass everything contained within the @code{verbatim} block to the @code{<mod_file>.m} file.

@deffn Block verbatim ;

@descriptionhead

By default, whenever Dynare encounters code that is not understood by the parser, it is directly passed to the preprocessor output.

In order to force this behavior you can use the @code{verbatim} block. This is useful when the code you want passed to the @code{<mod_file>.m} file contains tokens recognized by the Dynare preprocessor.

@examplehead

@example
verbatim;
% Anything contained in this block will be passed
% directly to the <modfile>.m file, including comments
var = 1;
end;
@end example

@end deffn

@node Misc commands
@section Misc commands

@deffn Command set_dynare_seed (@var{INTEGER})
@deffnx Command set_dynare_seed (`default')
@deffnx Command set_dynare_seed (`clock')
@deffnx Command set_dynare_seed (`reset')
@deffnx Command set_dynare_seed (`@var{ALGORITHM}', @var{INTEGER})

Sets the seed used for random number generation. It is possible to set
a given integer value, to use a default value, or to use the clock (by
using the latter, one will therefore get different results across
different Dynare runs). The @code{reset} option serves to reset the
seed to the value set by the last @code{set_dynare_seed} command. On
MATLAB 7.8 or above, it is also possible to choose a specific
algorithm for random number generation; accepted values are
@code{mcg16807}, @code{mlfg6331_64}, @code{mrg32k3a}, @code{mt19937ar}
(the default), @code{shr3cong} and @code{swb2712}.

@end deffn

@deffn Command save_params_and_steady_state (@var{FILENAME});

For all parameters, endogenous and exogenous variables, stores
their value in a text file, using a simple name/value associative table.

@itemize

@item
for parameters, the value is taken from the last parameter
initialization

@item
for exogenous, the value is taken from the last initval block

@item
for endogenous, the value is taken from the last steady state computation
(or, if no steady state has been computed, from the last initval block)
@end itemize

Note that no variable type is stored in the file, so that the values
can be reloaded with @code{load_params_and_steady_state} in a setup where
the variable types are different.

The typical usage of this function is to compute the steady-state of a
model by calibrating the steady-state value of some endogenous
variables (which implies that some parameters must be endogeneized
during the steady-state computation).

You would then write a first @file{.mod} file which computes the
steady state and saves the result of the computation at the end of the
file, using @code{save_params_and_steady_state}.

In a second file designed to perform the actual simulations, you would
use @code{load_params_and_steady_state} just after your variable
declarations, in order to load the steady state previously computed
(including the parameters which had been endogeneized during the
steady state computation).

The need for two separate @file{.mod} files arises from the fact that
the variable declarations differ between the files for steady state
calibration and for simulation (the set of endogenous and parameters
differ between the two); this leads to different @code{var} and
@code{parameters} statements.

Also note that you can take advantage of the @code{@@#include}
directive to share the model equations between the two files
(@pxref{Macro-processing language}).

@end deffn

@anchor{load_params_and_steady_state}
@deffn Command load_params_and_steady_state (@var{FILENAME});

For all parameters, endogenous and exogenous variables, loads
their value from a file created with @code{save_params_and_steady_state}.

@itemize

@item
for parameters, their value will be initialized as if they
had been calibrated in the @file{.mod} file

@item
for endogenous and exogenous, their value will be initialized
as they would have been from an initval block
@end itemize

This function is used in conjunction with
@code{save_params_and_steady_state}; see the documentation of that
function for more information.

@end deffn

@anchor{dynare_version}
@deffn {MATLAB/Octave command} dynare_version ;

Output the version of Dynare that is currently being used (@i{i.e.}
the one that is highest on the MATLAB/Octave path).

@end deffn

@deffn {MATLAB/Octave command} write_latex_definitions ;

Writes the names, @LaTeX{} names and long names of model variables to
tables in a file named @code{<<M_.fname>>_latex_definitions.tex}. Requires the
following @LaTeX{} packages: @code{longtable}
@end deffn

@deffn {MATLAB/Octave command} write_latex_parameter_table ;

Writes the @LaTeX{} names, parameter names, and long names of model parameters to
a table in a file named @code{<<M_.fname>>_latex_parameters.tex}. The command writes the values
of the parameters currently stored. Thus, if parameters are set or changed in the steady state 
computation, the command should be called after a @code{steady}-command to make sure the 
parameters were correctly updated. The long names can be used to add parameter descriptions. Requires the
following @LaTeX{} packages: @code{longtable, booktabs}
@end deffn

@deffn {MATLAB/Octave command} write_latex_prior_table ;

Writes descriptive statistics about the prior distribution to a @LaTeX{} table
in a file named @code{<<M_.fname>>_latex_priors_table.tex}. The command writes
the prior definitions currently stored. Thus, this command must be invoked
after the @code{estimated_params} block. If priors are defined over the
measurement errors, the command must also be preceeded by the declaration of
the observed variables (with @code{varobs}). The command displays a warning if
no prior densities are defined (ML estimation) or if the declaration of the
observed variables is missing. Requires the following @LaTeX{} packages:
@code{longtable, booktabs}
@end deffn

@deffn {MATLAB/Octave command} collect_latex_files ;

Writes a @LaTeX{} file named @code{<<M_.fname>>_TeX_binder.tex} that collects all @TeX{} output generated by Dynare 
into a file. This file can be compiled using pdflatex and automatically tries to load all required packages. 
Requires the following @LaTeX{} packages: @code{breqn}, @code{psfrag},
@code{graphicx}, @code{epstopdf}, @code{longtable},  @code{booktabs},  @code{caption},
@code{float}, @code{amsmath}, @code{amsfonts}, and @code{morefloats}
@end deffn


@node The Configuration File
@chapter The Configuration File

The configuration file is used to provide Dynare with information not
related to the model (and hence not placed in the model file). At the
moment, it is only used when using Dynare to run parallel
computations.

On Linux and Mac OS X, the default location of the configuration file
is @file{$HOME/.dynare}, while on Windows it is
@file{%APPDATA%\dynare.ini} (typically @file{C:\Documents and
Settings\@var{USERNAME}\Application Data\dynare.ini} under Windows XP,
or @file{C:\Users\@var{USERNAME}\AppData\dynare.ini} under Windows
Vista/7/8). You can specify a non standard location using the
@code{conffile} option of the @code{dynare} command (@pxref{Dynare
invocation}).

The parsing of the configuration file is case-sensitive and it should
take the following form, with each option/choice pair placed on a
newline:

@example
[command0]
option0 = choice0
option1 = choice1

[command1]
option0 = choice0
option1 = choice1
@end example

The configuration file follows a few conventions (self-explanatory
conventions such as @var{USER_NAME} have been excluded for concision):

@table @var

@item COMPUTER_NAME
Indicates the valid name of a server (@i{e.g.} @code{localhost},
@code{server.cepremap.org}) or an IP address.

@item DRIVE_NAME
Indicates a valid drive name in Windows, without the trailing colon (@i{e.g.} @code{C}).

@item PATH
Indicates a valid path in the underlying operating system (@i{e.g.}
@code{/home/user/dynare/matlab/}).

@item PATH_AND_FILE
Indicates a valid path to a file in the underlying operating system
(@i{e.g.} @code{/usr/local/MATLAB/R2010b/bin/matlab}).

@item BOOLEAN
Is @code{true} or @code{false}.
@end table

@menu
* Dynare Configuration::
* Parallel Configuration::
* Windows Step-by-Step Guide::
@end menu

@node Dynare Configuration
@section Dynare Configuration

This section explains how to configure Dynare for general
processing. Currently, there is only one option available.

@deffn {Configuration block} [hooks]

@descriptionhead

The @code{[hooks]} block can be used to specify configuration options
that will be used when running Dynare.

@optionshead

@table @code

@item GlobalInitFile = @var{PATH_AND_FILE}
The location of the global initialization file to be run at the end of
@code{global_initialization.m}

@end table

@examplehead

@example
[hooks]
GlobalInitFile = /home/usern/dynare/myInitFile.m

@end example

@end deffn

@deffn {Configuration block} [paths]

@descriptionhead

The @code{[paths]} block can be used to specify paths that will be
used when running dynare.

@optionshead

@table @code

@item Include = @var{PATH}
A colon-separated path to use when searching for files to include via
@ref{@@#include}. Paths specified via @ref{-I} take priority over
paths specified here, while these paths take priority over those
specified by @ref{@@#includepath}.

@end table

@examplehead

@example
[paths]
Include = /path/to/folder/containing/modfiles:/path/to/another/folder

@end example

@end deffn

@node Parallel Configuration
@section Parallel Configuration

This section explains how to configure Dynare for parallelizing some
tasks which require very little inter-process communication.

The parallelization is done by running several MATLAB or Octave
processes, either on local or on remote machines. Communication
between master and slave processes are done through SMB on Windows and
SSH on UNIX. Input and output data, and also some short status
messages, are exchanged through network filesystems. Currently the
system works only with homogenous grids: only Windows or only Unix
machines.

The following routines are currently parallelized:

@itemize

@item
the posterior sampling algorithms when using multiple chains;

@item
the Metropolis-Hastings diagnostics;

@item
the posterior IRFs;

@item
the prior and posterior statistics;

@item
some plotting routines.

@end itemize

Note that creating the configuration file is not enough in order to
trigger parallelization of the computations: you also need to specify
the @code{parallel} option to the @code{dynare} command. For more
details, and for other options related to the parallelization engine,
@pxref{Dynare invocation}.

You also need to verify that the following requirements are met by
your cluster (which is composed of a master and of one or more
slaves):

@table @asis

@item For a Windows grid

@itemize

@item
a standard Windows network (SMB) must be in place;

@item
@uref{https://technet.microsoft.com/sysinternals/pstools.aspx,
PsTools} must be installed in the path of the master Windows machine;

@item
the Windows user on the master machine has to be user of any other
slave machine in the cluster, and that user will be used for the
remote computations.

@item Detailed step-by-step setup instructions can be found in @xref{Windows Step-by-Step Guide}.

@end itemize

@item For a UNIX grid

@itemize

@item
SSH must be installed on the master and on the slave machines;

@item
SSH keys must be installed so that the SSH connection from the master
to the slaves can be done without passwords, or using an SSH agent

@end itemize

@end table

We now turn to the description of the configuration directives. Note that comments in
the configuration file can be provided by separate lines starting with a hashtag (#).

@deffn {Configuration block} [cluster]

@descriptionhead

When working in parallel, @code{[cluster]} is required to specify the
group of computers that will be used. It is required even if you are
only invoking multiple processes on one computer.

@optionshead

@table @code

@item Name = @var{CLUSTER_NAME}
The reference name of this cluster.

@item Members = @var{NODE_NAME}[(@var{WEIGHT})] @var{NODE_NAME}[(@var{WEIGHT})] @dots{}
A list of nodes that comprise the cluster with an optional computing
weight specified for that node. The computing weight indicates how
much more powerful one node is with respect to the others (@i{e.g.}
@code{n1(2) n2(1) n3(3)}, means that @code{n1} is two times more
powerful than @code{n2} whereas @code{n3} is three times more powerful
than @code{n2}). Each node is separated by at least one space and the
weights are in parenthesis with no spaces separating them from their
node.
@end table

@examplehead

@example
[cluster]
Name = c1
Members = n1 n2 n3

[cluster]
Name = c2
Members = n1(4) n2 n3
@end example

@end deffn

@deffn {Configuration block} [node]

@descriptionhead

When working in parallel, @code{[node]} is required for every computer
that will be used. The options that are required differ, depending on
the underlying operating system and whether you are working locally or
remotely.

@optionshead

@table @code

@item Name = @var{NODE_NAME}
The reference name of this node.

@item CPUnbr = @var{INTEGER} | [@var{INTEGER}:@var{INTEGER}]
If just one integer is passed, the number of processors to use. If a
range of integers is passed, the specific processors to use (processor
counting is defined to begin at one as opposed to zero). Note that
using specific processors is only possible under Windows; under Linux
and Mac OS X, if a range is passed the same number of processors will
be used but the range will be adjusted to begin at one.

@item ComputerName = @var{COMPUTER_NAME}
The name or IP address of the node. If you want to run locally, use
@code{localhost} (case-sensitive).

@item Port = @var{INTEGER}
The port number to connect to on the node. The default is empty,
meaning that the connection will be made to the default SSH port (22).

@item UserName = @var{USER_NAME}
The username used to log into a remote system. Required for remote
runs on all platforms.

@item Password = @var{PASSWORD}
The password used to log into the remote system. Required for remote
runs originating from Windows.

@item RemoteDrive = @var{DRIVE_NAME}
The drive to be used for remote computation. Required for remote runs
originating from Windows.

@item RemoteDirectory = @var{PATH}
The directory to be used for remote computation. Required for remote
runs on all platforms.

@item DynarePath = @var{PATH}
The path to the @file{matlab} subdirectory within the Dynare
installation directory. The default is the empty string.

@item MatlabOctavePath = @var{PATH_AND_FILE}
The path to the MATLAB or Octave executable. The default value is
@code{matlab}.

@item NumberOfThreadsPerJob = @var{INTEGER}
For Windows nodes, sets the number of threads assigned to each remote MATLAB/Octave run. The default
value is @code{1}. 

@item SingleCompThread = @var{BOOLEAN}
Whether or not to disable MATLAB's native multithreading. The default
value is @code{false}. Option meaningless under Octave.

@item OperatingSystem = @var{OPERATING_SYSTEM}
The operating system associated with a node. Only necessary when
creating a cluster with nodes from different operating systems.
Possible values are @code{unix} or @code{windows}. There is no default
value.
@end table

@examplehead

@example
[node]
Name = n1
ComputerName = localhost
CPUnbr = 1

[node]
Name = n2
ComputerName = dynserv.cepremap.org
CPUnbr = 5
UserName = usern
RemoteDirectory = /home/usern/Remote
DynarePath = /home/usern/dynare/matlab
MatlabOctavePath = matlab

[node]
Name = n3
ComputerName = dynserv.dynare.org
Port = 3333
CPUnbr = [2:4]
UserName = usern
RemoteDirectory = /home/usern/Remote
DynarePath = /home/usern/dynare/matlab
MatlabOctavePath = matlab
@end example

@end deffn

@node Windows Step-by-Step Guide
@section Windows Step-by-Step Guide

This section outlines the steps necessary on most Windows systems to set up Dynare for parallel execution. 

@enumerate
@item Write a configuration file containing the options you want. A mimimum working 
    example setting up a cluster consisting of two local CPU cores that allows for @i{e.g.} running
    two Monte Carlo Markov Chains in parallel is shown below.
@item Save the configuration file somwhere. The name and file ending do not matter 
    if you are providing it with the @code{conffile} command line option. The only restrictions are that the 
    path must be a valid filename, not contain non-alpha-numeric characters, and not contain any whitespaces.
    For the configuration file to be accessible without providing an explicit path at the command line, you must save it 
    under the name @file{dynare.ini} into your user account's @code{Application Data} folder.
@item Install the @file{PSTools} from @uref{https://technet.microsoft.com/sysinternals/pstools.aspx} 
    to your system, @i{e.g.} into @file{C:\PSTools}.
@item Set the Windows System Path to the @file{PSTools}-folder (@i{e.g.} using something along the line of pressing Windows Key+Pause to 
    open the System Configuration, then go to Advanced -> Environment Variables -> Path, see also @uref{https://technet.microsoft.com/sysinternals/pstools.aspx}).
@item Restart your computer to make the path change effective.
@item Open Matlab and type into the command window 
    
    @code{!psexec}

    This executes the 
    @file{psexec.exe} of the @file{PSTools} on your system and 
    shows whether Dynare will be able to locate it. If Matlab complains at this stage, 
    you did not correctly set your Windows system path for the @file{PSTools}-folder.
@item If @file{psexec.exe} was located in the previous step, a popup will show up, asking 
    for confirmation of the license agreement. 
    Confirm this copyright notice of @file{psexec} (this needs to be done only once). 
    After this, Dynare should be ready for parallel execution.
@item Call Dynare on your mod-file invoking the @code{parallel} option and providing the path to your configuration file 
    with the @code{conffile}-option (if you did not save it as @file{%APPDATA%\dynare.ini} in step 2 
    where it should be detected automatically)
    
    @example
    dynare ls2003 parallel conffile='C:\Users\Dynare~1\parallel\conf_file.ini'
    @end example

    Please keep in mind that no whitespaces or names longer than 8 characters are allowed in the @code{conffile}-path. 
    The 8 character restriction can be circumvented
    by using the tilde Windows path notation as in the above example.
@end enumerate

@examplehead

@example
#cluster needs to always be defined first
[cluster] 
#Provide a name for the cluster
Name=Local
#declare the nodes being member of the cluster
Members=n1 

#declare nodes (they need not all be part of a cluster)
[node] 
#name of the node
Name=n1 
#name of the computer (localhost for the current machine)
ComputerName=localhost 
#cores to be included from this node
CPUnbr=[1:2]
#path to matlab.exe; on Windows, Matlab's bin folder is in the system path 
#so we only need to provide the name of the exe file
MatlabOctavePath=matlab 
#Dynare path you are using
DynarePath=C:\dynare\2016-05-10\matlab 

@end example


@node Time Series
@chapter Time Series

@menu
* Dates::
* dseries class::
@end menu


Dynare provides a  Matlab/Octave class for handling time series  data, which is
based on a class for handling dates. Dynare also provides a new type for
dates, so  that the  basic user  do not  have to  worry about  class and
methods for  dates.  Below, you  will first  find the class  and methods
used for  creating and dealing  with dates and  then the class  used for
using time series.

@node Dates
@section Dates

@menu
* dates in a mod file::
* dates class::
@end menu

@node dates in a mod file
@subsection dates in a mod file

Dynare  understands dates  in  a  mod file.  Users  can declare  annual,
quarterly, monthly or weekly dates using the following syntax:

@example
1990Y
1990Q3
1990M11
1990W49
@end example

@noindent Behind the scene, Dynare's preprocessor translates these expressions
into instantiations of the  Matlab/Octave's class @dates described
below. Basic  operations can be performed  on dates:
@table @strong

@item plus binary operator (@code{+})

An integer scalar, interpreted as a number of periods, can be added to a date. For instance, if @code{a = 1950Q1} then
@code{b = 1951Q2} and @code{b = a + 5} are identical.

@item plus unary operator (@code{+})

Increments a date by one period. @code{+1950Q1} is identical to @code{1950Q2}, @code{++++1950Q1} is identical to @code{1951Q1}.

@item minus binary operator (@code{-})

Has two functions: difference and subtraction. If the second argument
is a date, calculates the difference between the first date and the
second date (@i{e.g.} @code{1951Q2-1950Q1} is equal to @code{5}). If
the second argument is an integer @code{X}, subtracts @code{X} periods
from the date (@i{e.g.} @code{1951Q2-2} is equal to @code{1950Q4}).

@item minus unary operator (@code{-})

Subtracts one period to a date. @code{-1950Q1} is identical to @code{1949Q4}. The unary minus operator is the reciprocal of the unary plus operator, @code{+-1950Q1} is identical to @code{1950Q1}.

@item colon operator (@code{:})

Can be used to create a range of dates. For instance, @code{r = 1950Q1:1951Q1} creates a @dates object with five elements: @code{1950Q1}, @code{1950Q2}, @code{1950Q3}, @code{1950Q4} and @code{1951Q1}. By default the increment between each element is one period. This default can be changed using, for instance, the following instruction: @code{1950Q1:2:1951Q1} which will instantiate a @dates object with three elements: @code{1950Q1}, @code{1950Q3} and @code{1951Q1}.

@item horzcat operator (@code{[,]})

Concatenates @dates objects without removing repetitions. For instance @code{[1950Q1, 1950Q2]} is a a @dates object with two elements (@code{1950Q1} and @code{1950Q2}).

@item vertcat operator (@code{[;]})

Same as @code{horzcat} operator.

@item eq operator (equal, @code{==})

Tests if two @dates objects are equal. @code{+1950Q1==1950Q2} returns @code{1}, @code{1950Q1==1950Q2} returns @code{0}. If the compared objects have both @code{n>1} elements, the @code{eq} operator returns a column vector, @code{n} by @code{1}, of zeros and ones.

@item ne operator (not equal, @code{~=})

Tests if two @dates objects are not equal. @code{+1950Q1~=1950Q2}
returns @code{0} while @code{1950Q1~=1950Q2} returns @code{1}. If the
compared objects both have @code{n>1} elements, the @code{ne} operator
returns an @code{n} by @code{1} column vector of zeros and ones.

@item lt operator (less than, @code{<})

Tests if a @dates object preceeds another @dates object. For instance, @code{1950Q1<1950Q3} returns @code{1}.  If the compared objects have both @code{n>1} elements, the @code{lt} operator returns a column vector, @code{n} by @code{1}, of zeros and ones.

@item gt operator (greater than, @code{>})

Tests if a @dates object follows another @dates object. For instance, @code{1950Q1>1950Q3} returns @code{0}.  If the compared objects have both @code{n>1} elements, the @code{gt} operator returns a column vector, @code{n} by @code{1}, of zeros and ones.

@item le operator (less or equal, @code{<=})

Tests if a @dates object preceeds another @dates object or is equal to this object. For instance, @code{1950Q1<=1950Q3} returns @code{1}.  If the compared objects have both @code{n>1} elements, the @code{le} operator returns a column vector, @code{n} by @code{1}, of zeros and ones.

@item ge operator (greater or equal, @code{>=})

Tests if a @dates object follows another @dates object or is equal to this object. For instance, @code{1950Q1>=1950Q3} returns @code{0}.  If the compared objects have both @code{n>1} elements, the @code{ge} operator returns a column vector, @code{n} by @code{1}, of zeros and ones.

@end table

@noindent One can select an element, or some elements, in a @dates object as he would extract some elements from a vector in Matlab/Octave. Let @code{a = 1950Q1:1951Q1} be a @dates object, then @code{a(1)==1950Q1} returns @code{1}, @code{a(end)==1951Q1} returns @code{1} and @code{a(end-1:end)} selects the two last elements of @code{a} (by instantiating the @dates object @code{[1950Q4, 1951Q1]}).

@remarkhead
@noindent Dynare substitutes any occurrence of dates in the mod file into an instantiation of the @dates class regardless of the context. For instance, @code{d = 1950Q1;} will be translated as @code{d = dates('1950Q1');}. This automatic substitution can lead to a crash if a date is defined in a string. Typically, if the user wants to display a date:

@example
disp('Initial period is 1950Q1');
@end example

@noindent Dynare will translate this as:

@example
disp('Initial period is dates('1950Q1')');
@end example

@noindent which will lead to a crash because this expression is illegal in Matlab. For this situation, Dynare provides the @code{$} escape parameter. The following expression:

@example
disp('Initial period is $1950Q1');
@end example

@noindent will be translated as:

@example
disp('Initial period is 1950Q1');
@end example

@noindent in the generated MATLAB script.

@node dates class
@subsection dates class

The @dates class has three members:
@table @code
@anchor{dates class members}

@item freq
an integer equal to 1, 4, 12  or 52 (resp. for annual, quarterly, monthly
or weekly dates).

@item ndat
an integer scalar, the number of declared dates in the object.

@item time
a @code{ndat}*2  array of integers,  the years  are stored in  the first
column, the subperiods (1 for annual dates, 1-4 for quarterly dates, 1-12
for monthly  dates and 1-52 for  weekly dates) are stored  in the second
column.

@end table

@noindent Each member is private, one can display the content of a member but cannot change its value:

@example
>> d = dates('2009Q2');
>> d.time

ans =

        2009           2

>>
@end example

@noindent Note that it is not possible to mix frequencies in a @dates object: all the elements must have common frequency. The @dates class has five constructors:

@sp 1

@deftypefn  {dates} dates ()
@deftypefnx {dates} dates (@code{FREQ})

Returns an empty @dates object with  a given frequency (if the constructor is called with one input argument).  @code{FREQ} is a character equal to 'Y' or 'A'  for annual dates, 'Q' for quarterly dates, 'M' for monthly dates or 'W'  for weekly dates. Note that @code{FREQ} is not  case sensitive,  so that,  for instance,  'q' is  also allowed  for quarterly dates. The frequency can also be set with an integer scalar equal to 1 (annual), 4 (quarterly), 12 (monthly) or 52 (weekly). The instantiation of empty objects can be used to rename  the @dates class. For  instance, if one  only works  with quarterly dates, he can create @code{qq} as:

@example
qq = dates('Q')
@end example

@noindent and a @dates object holding the date @code{2009Q2}:

@example
d0 = qq(2009,2);
@end example

@noindent which is much simpler if @dates objects have to be defined programmatically.

@end deftypefn

@sp 1

@deftypefn {dates} dates (@code{STRING})
@deftypefnx {dates} dates (@code{STRING}, @code{STRING}, ...)

Returns a @dates object that represents a date as given by the string @code{STRING}. This string has to be interpretable as a date (only strings of the following forms are admitted: @code{'1990Y'}, @code{'1990A'}, @code{'1990Q1'}, @code{'1990M2'}, @code{'1990W5'}), the routine @code{isdate} can be used to test if a string is interpretable as a date. If more than one argument is provided, they should all be dates represented as strings, the resulting @dates object contains as many elements as arguments to the constructor.

@end deftypefn

@sp 1

@deftypefn {dates} dates (@code{DATES})
@deftypefnx {dates} dates (@code{DATES}, @code{DATES}, ...)

Returns a copy of the  @dates object @code{DATES} passed as input arguments. If more than one argument is provided, they should all be @dates objects. The number of elements in the instantiated @dates object is equal to the sum of the elements in the @dates passed as arguments to the constructor.

@end deftypefn

@sp 1

@deftypefn {dates} dates (@code{FREQ}, @code{YEAR}, @code{SUBPERIOD})

where @code{FREQ} is a single character ('Y', 'A', 'Q', 'M', 'W') or integer (1, 4, 12 or 52) specifying the frequency, @code{YEAR} and @code{SUBPERIOD} are @code{n*1} vectors of integers. Returns a @dates object with @code{n} elements. If @code{FREQ} is equal to @code{'Y', 'A'} or @code{1}, the third argument is not needed (because @code{SUBPERIOD} is necessarily a vector of ones in this case).

@end deftypefn

@sp 1

@exampleshead
@example
do1 = dates('1950Q1');
do2 = dates('1950Q2','1950Q3');
do3 = dates(do1,do2);
do4 = dates('Q',1950, 1);
@end example

@sp 1

@noindent A list of the available methods, by alphabetical order, is given below. Note that the Matlab/Octave classes do not allow in place modifications: when a method is applied to an object a new object is instantiated. For instance, to apply the method @code{multiplybytwo} to an object @code{X} we write:

@example
Y = X.multiplybytwo()
@end example

@noindent or equivalently:

@example
Y = multiplybytwo(X)
@end example

@noindent the object @code{X} is left unchanged, and the object @code{Y} is a modified copy of @code{X}.

@sp 1

@deftypefn {dates} {@var{C} = } append (@var{A}, @var{B})

Appends @dates object @var{B}, or a string that can be interpreted as a date, to the @dates object @var{A}. If @var{B} is a @dates object it is assumed that it has no more than one element.

@examplehead
@example
>> D = dates('1950Q1','1950Q2');
>> d = dates('1950Q3');
>> E = D.append(d);
>> F = D.append('1950Q3')
>> isequal(E,F)

ans =

     1
>> F
F = <dates: 1950Q1, 1950Q2, 1950Q3>
@end example

@end deftypefn

@sp 1

@deftypefn {dates} {@var{C} = } colon (@var{A}, @var{B})
@deftypefnx {dates} {@var{C} = } colon (@var{A}, @var{i}, @var{B})

Overloads the Matlab/Octave colon (:) operator. @var{A} and @var{B} are @dates objects. The optional increment @var{i} is a scalar integer (default value is @code{i=1}). This method returns a @dates object and can be used to create ranges of dates.

@examplehead
@example
>> A = dates('1950Q1');
>> B = dates('1951Q2');
>> C = A:B
C = <dates: 1950Q1, 1950Q2, 1950Q3, 1950Q4, 1951Q1>
>> D = A:2:B
D = <dates: 1950Q1, 1950Q3, 1951Q1>

@end example

@end deftypefn

@sp 1

@deftypefn{dates} {@var{B} = } double (@var{A})

Overloads the Matlab/Octave @code{double} function. @var{A} is a @dates object. The method returns a floating point representation of a @dates object, the integer and fractional parts respectively corresponding to the year and the subperiod. The fractional part is the subperiod number minus one divided by the frequency (@code{1}, @code{4}, @code{12} or @code{52}).


@examplehead
@example
>> a = dates('1950Q1'):dates('1950Q4');
>> a.double()

ans =

   1950.00
   1950.25
   1950.50
   1950.75

@end example

@end deftypefn

@sp 1

@deftypefn{dates} {@var{C} =} eq (@var{A}, @var{B})

Overloads the Matlab/Octave @code{eq} (equal, @code{==}) operator. @dates objects @var{A} and @var{B} must have the  same number of elements (say, @code{n}). The returned argument is a @code{n} by @code{1} vector of zeros and ones. The i-th element of @var{C} is equal to @code{1} if and only if the dates @code{A(i)} and @code{B(i)} are the same.

@examplehead
@example
>> A = dates('1950Q1','1951Q2');
>> B = dates('1950Q1','1950Q2');
>> A==B

ans =

     1
     0
@end example

@end deftypefn

@sp 1

@deftypefn{dates} {@var{C} =} ge (@var{A}, @var{B})

Overloads the Matlab/Octave @code{ge} (greater or equal, @code{>=}) operator. @dates objects @var{A} and @var{B} must have the  same number of elements (say, @code{n}). The returned argument is a @code{n} by @code{1} vector of zeros and ones. The i-th element of @var{C} is equal to @code{1} if and only if the date @code{A(i)} is posterior or equal to the date @code{B(i)}.

@examplehead
@example
>> A = dates('1950Q1','1951Q2');
>> B = dates('1950Q1','1950Q2');
>> A>=B

ans =

     1
     1
@end example

@end deftypefn

@sp 1

@deftypefn{dates} {@var{C} =} gt (@var{A}, @var{B})

Overloads the Matlab/Octave @code{gt} (greater than, @code{>=}) operator. @dates objects @var{A} and @var{B} must have the  same number of elements (say, @code{n}). The returned argument is a @code{n} by @code{1} vector of zeros and ones. The i-th element of @var{C} is equal to @code{1} if and only if the date @code{A(i)} is posterior to the date @code{B(i)}.

@examplehead
@example
>> A = dates('1950Q1','1951Q2');
>> B = dates('1950Q1','1950Q2');
>> A>B

ans =

     0
     1
@end example

@end deftypefn

@sp 1

@deftypefn{dates} {@var{D} =} horzcat (@var{A}, @var{B}, @var{C}, ...)

Overloads the Matlab/Octave @code{horzcat} operator. All the input arguments must be @dates objects. The returned argument is a @dates object gathering all the dates given in the input arguments (repetitions are not removed).

@examplehead
@example
>> A = dates('1950Q1');
>> B = dates('1950Q2');
>> C = [A, B];
>> C
C = <dates: 1950Q1, 1950Q2>
@end example

@end deftypefn

@sp 1

@deftypefn{dates} {@var{C} =} intersect (@var{A}, @var{B})

Overloads the Matlab/Octave @code{intersect} function. All the input arguments must be @dates objects. The returned argument is a @dates object gathering all the common dates given in the input arguments. If @var{A} and @var{B} are disjoint @dates objects, the function returns an empty @dates object. Returned dates in @dates object @var{C} are sorted by increasing order.

@examplehead
@example
>> A = dates('1950Q1'):dates('1951Q4');
>> B = dates('1951Q1'):dates('1951Q4');
>> C = intersect(A, B);
>> C
C = <dates: 1951Q1, 1951Q2, 1951Q3, 1951Q4>
@end example

@end deftypefn

@sp 1

@deftypefn{dates} {@var{C} =} setdiff (@var{A}, @var{B})

Overloads the Matlab/Octave @code{setdiff} function. All the input arguments must be @dates objects. The returned argument is a @dates object all dates present in @var{A} but not in @var{B}. If @var{A} and @var{B} are disjoint @dates objects, the function returns @var{A}. Returned dates in @dates object @var{C} are sorted by increasing order.

@examplehead
@example
>> A = dates('1950Q1'):dates('1969Q4') ;
>> B = dates('1960Q1'):dates('1969Q4') ;
>> C = dates('1970Q1'):dates('1979Q4') ;
>> d1 = setdiff(d1,d2);
>> d2 = setdiff(d1,d3);
d1 = <dates: 1950Q1, 1950Q2,  ..., 1959Q3, 1959Q4>
d2 = <dates: 1950Q1, 1950Q2,  ..., 1969Q3, 1969Q4>
@end example

@end deftypefn


@sp 1


@deftypefn{dates} {@var{B} =} isempty (@var{A})

Overloads the Matlab/Octave isempty function for @dates object.

@examplehead
@example
>> A = dates('1950Q1'):dates('1951Q4');
>> A.isempty()

ans =

     0
@end example

@end deftypefn

@sp 1

@deftypefn{dates} {@var{C} =} isequal (@var{A}, @var{B})

Overloads the Matlab/Octave @code{isequal} function for @dates objects.

@examplehead
@example
>> A = dates('1950Q1'):dates('1951Q4');
>> isequal(A,A)

ans =

     1
@end example

@end deftypefn

@sp 1

@deftypefn{dates} {@var{C} =} le (@var{A}, @var{B})

Overloads the Matlab/Octave @code{le} (less or equal, @code{<=}) operator. @dates objects @var{A} and @var{B} must have the  same number of elements (say, @code{n}). The returned argument is a @code{n} by @code{1} vector of zeros and ones. The i-th element of @var{C} is equal to @code{1} if and only if the date @code{A(i)} is not posterior to the date @code{B(i)}.

@examplehead
@example
>> A = dates('1950Q1','1951Q2');
>> B = dates('1950Q1','1950Q2');
>> A<=B

ans =

     1
     0
@end example

@end deftypefn

@sp 1

@deftypefn{dates} {@var{B} =} length (@var{A})

Overloads the Matlab/Octave @code{length}  function. Returns the number of dates in @dates object @var{A} (@var{B} is a scalar integer).

@examplehead
@example
>> A = dates('1950Q1','1951Q2');
>> A.length()

ans =

     2
@end example

@end deftypefn

@sp 1

@deftypefn{dates} {@var{C} =} lt (@var{A}, @var{B})

Overloads the Matlab/Octave @code{lt} (less than, @code{<=}) operator. @dates objects @var{A} and @var{B} must have the  same number of elements (say, @code{n}). The returned argument is a @code{n} by @code{1} vector of zeros and ones. The i-th element of @var{C} is equal to @code{1} if and only if the date @code{A(i)} preceeds the date @code{B(i)}.

@examplehead
@example
>> A = dates('1950Q1','1951Q2');
>> B = dates('1950Q1','1950Q2');
>> A<B

ans =

     0
     0
@end example

@end deftypefn

@sp 1

@deftypefn{dates} {@var{D} =} max (@var{A}, @var{B}, @var{C}, ...)

Overloads the Matlab/Octave @code{max} function. All input arguments must be @dates objects. The function returns a single element @dates object containing the greatest date.

@examplehead
@example
>> A = @{dates('1950Q2'), dates('1953Q4','1876Q2'), dates('1794Q3')@};
>> max(A@{:@})
ans = <dates: 1953Q4>
@end example

@end deftypefn

@sp 1

@deftypefn{dates} {@var{D} =} min (@var{A}, @var{B}, @var{C}, ...)

Overloads the Matlab/Octave @code{min} function. All input arguments must be @dates objects. The function returns a single element @dates object containing the smallest date.

@examplehead
@example
>> A = @{dates('1950Q2'), dates('1953Q4','1876Q2'), dates('1794Q3')@};
>> min(A@{:@})
ans = <dates: 1794Q3>
@end example

@end deftypefn

@sp 1

@deftypefn{dates} {@var{C} =} minus (@var{A}, @var{B})

Overloads the Matlab/Octave @code{minus} operator (@code{-}). If both input arguments are @dates objects, then number of periods between @var{A} and @var{B} is returned (so that @code{A+C=B}). If @var{B} is a vector of integers, the @code{minus} operator shifts the @dates object by @var{B} periods backward.

@examplehead
@example
>> d1 = dates('1950Q1','1950Q2','1960Q1');
>> d2 = dates('1950Q3','1950Q4','1960Q1');
>> ee = d2-d1

ee =

     2
     2
     0

>> d1-(-ee)
ans = <dates: 1950Q3, 1950Q4, 1960Q1>
@end example

@end deftypefn

@sp 1

@deftypefn{dates} {@var{C} =} ne (@var{A}, @var{B})

Overloads the Matlab/Octave @code{ne} (not equal, @code{~=}) operator. @dates objects @var{A} and @var{B} must have the  same number of elements (say, @code{n}) or one of the inputs must be a single element @dates object. The returned argument is a @code{n} by @code{1} vector of zeros and ones. The i-th element of @var{C} is equal to @code{1} if and only if the dates @code{A(i)} and @code{B(i)} are different.

@examplehead
@example
>> A = dates('1950Q1','1951Q2');
>> B = dates('1950Q1','1950Q2');
>> A~=B

ans =

     0
     1
@end example

@end deftypefn

@sp 1

@deftypefn{dates} {@var{C} =} plus (@var{A}, @var{B})

Overloads the Matlab/Octave @code{plus} operator (@code{+}). If both input arguments are @dates objects, then the method combines A and B without removing repetitions. If @var{B} is a vector of integers, the @code{plus} operator shifts the @dates object by @var{B} periods forward.

@examplehead
@example
>> d1 = dates('1950Q1','1950Q2')+dates('1960Q1');
>> d2 = (dates('1950Q1','1950Q2')+2)+dates('1960Q1');
>> ee = d2-d1;

ee =

     2
     2
     0

>> d1+ee
ans = <dates: 1950Q3, 1950Q4, 1960Q1>
@end example

@end deftypefn

@sp 1

@deftypefn{dates} {@var{C} =} pop (@var{A})
@deftypefnx{dates} {@var{C} =} pop (@var{A},@var{B})

Pop method for @dates class. If only one input is provided, the method removes the last element of a @dates object. If a second input argument is provided, a scalar integer between @code{1} and @code{A.length()}, the method removes element number @var{B} from @dates object @var{A}.

@examplehead
@example
>> d1 = dates('1950Q1','1950Q2');
>> d1.pop()
ans = <dates: 1950Q1>

>> d1.pop(1)
ans = <dates: 1950Q2>
@end example

@end deftypefn

@sp 1

@deftypefn{dates} {@var{B} =} sort (@var{A})

Sort method for @dates objects. Returns a @dates object with elements sorted by increasing order.

@examplehead
@example
>> dd = dates('1945Q3','1938Q4','1789Q3');
>> dd.sort()
ans = <dates: 1789Q3, 1938Q4, 1945Q3>
@end example

@end deftypefn

@sp 1

@deftypefn{dates} {@var{B} =} uminus (@var{A})

Overloads the Matlab/Octave unary minus operator. Returns a @dates object with elements shifted one period backward.

@examplehead
@example
>> dd = dates('1945Q3','1938Q4','1973Q1');
>> -dd
ans = <dates: 1945Q2, 1938Q3, 1972Q4>
@end example

@end deftypefn

@sp 1

@deftypefn{dates} {@var{D} =} union (@var{A}, @var{B}, @var{C}, ...)

Overloads the Matlab/Octave @code{union} function. Returns a @dates object with elements sorted by increasing order (repetitions are removed, to keep the repetitions use the @code{horzcat} or @code{plus} operators).

@examplehead
@example
>> d1 = dates('1945Q3','1973Q1','1938Q4');
>> d2 = dates('1973Q1','1976Q1');
>> union(d1,d2)
ans = <dates: 1938Q4, 1945Q3, 1973Q1, 1976Q1>
@end example

@end deftypefn

@sp 1

@deftypefn{dates} {@var{B} =} unique (@var{A})

Overloads the Matlab/Octave @code{unique} function. Returns a @dates object with repetitions removed (only the last occurence of a date is kept).

@examplehead
@example
>> d1 = dates('1945Q3','1973Q1','1945Q3');
>> d1.unique()
ans = <dates: 1973Q1, 1945Q3>
@end example

@end deftypefn

@sp 1

@deftypefn{dates} {@var{B} =} uplus (@var{A})

Overloads the Matlab/Octave unary plus operator. Returns a @dates object with elements shifted one period ahead.

@examplehead
@example
>> dd = dates('1945Q3','1938Q4','1973Q1');
>> +dd
ans = <dates: 1945Q4, 1939Q1, 1973Q2>
@end example

@end deftypefn


@node dseries class
@section dseries class

The Matlab/Octave @dseries class handles time series data. As any Matlab/Octave statements, this class can be used in a Dynare's mod file. A @dseries object has eight members:

@table @code
@anchor{dseries class members}

@item name
A @code{nobs}*1 cell of strings or a @code{nobs}*p character array, the names of the variables.

@item tex
 A @code{nobs}*1 cell of strings or a @code{nobs}*p character array, the tex names of the variables.

@item dates
A @dates object with @code{nobs} element, the dates of the sample.

@item data
A @code{nobs} by @code{vobs} array of doubles, the data.

@end table

@noindent @code{data}, @code{name}, @code{tex} are private members. The following constructors are available:

@deftypefn  {dseries} dseries ()
@deftypefnx {dseries} dseries (@var{INITIAL_DATE})

Instantiates an empty @dseries object, with, if defined, an initial date given by the single element @dates object @var{INITIAL_DATE}.

@end deftypefn

@sp 1

@deftypefn {dseries} dseries (@var{FILENAME}[, @var{INITIAL_DATE}])

Instantiates and populates a @dseries object with a data file specified by @var{FILENAME}, a string passed as input. Valid file types are @file{.m} file, @file{.mat} file, @file{.csv} file, and @file{.xls}/@file{.xlsx} file (Octave only supports @file{.xlsx} files and the @uref{http://octave.sourceforge.net/io/,io} package from Octave-Forge must be installed). A typical @file{.m} file will have the following form:

@example
INIT__ = '1994Q3';
NAMES__ = @{'azert';'yuiop'@};
TEX__ = @{'azert';'yuiop'@};

azert = randn(100,1);
yuiop = randn(100,1);
@end example

If a @file{.mat} file is used instead, it should provide the same informations. Note that the @code{INIT__} variable can be either a @dates object or a string which could be used to instantiate the same @dates object. If @code{INIT__} is not provided in the @file{.mat} or @file{.m} file, the initial is by default set equal to @code{dates('1Y')}. If a second input argument is passed to the constructor, @dates object @var{INITIAL_DATE}, the initial date defined in @var{FILENAME} is reset to @var{INITIAL_DATE}. This is typically usefull if @code{INIT__} is not provided in the data file.

@end deftypefn

@sp 1

@deftypefn {dseries} dseries (@var{DATA_MATRIX}[, @var{INITIAL_DATE}[, @var{LIST_OF_NAMES}[, @var{LIST_OF_TEX_NAMES}]]])
@deftypefnx {dseries} dseries (@var{DATA_MATRIX}[, @var{RANGE_OF_DATES}[, @var{LIST_OF_NAMES}[, @var{LIST_OF_TEX_NAMES}]]])

If the data is not read from a file, it can be provided via a @math{T}x@math{N} matrix as the first argument to @code{dseries}' constructor, with @math{T} representing the number of observations on @math{N} variables. The optional second argument, @var{INITIAL_DATE}, can be either a @dates object representing the period of the first observation or a string which would be used to instantiate a @dates object. Its default value is @code{dates('1Y')}. The optional third argument, @var{LIST_OF_NAMES}, is a @math{N} by @math{1} cell of strings  with one entry for each variable name. The default name associated with column @code{i} of @var{DATA_MATRIX} is @code{Variable_i}. The final argument, @var{LIST_OF_TEX_NAMES}, is a @math{N} by @math{1} cell of strings composed of the @LaTeX{} names associated with the variables. The default @LaTeX{} name associated with column @code{i} of @var{DATA_MATRIX} is @code{Variable\_i}. If the optional second input argument is a range of dates, @dates object @var{RANGE_OF_DATES}, the number of rows in the first argument must match the number of elements @var{RANGE_OF_DATES} or be equal to one (in which case the single observation is replicated).

@end deftypefn

@sp 1

@exampleshead

Various ways to create a @code{dseries} object:

@sp 1

@example In a mod file:
do1 = dseries(1999Q3);
do2 = dseries('filename.csv');
do3 = dseries([1; 2; 3], 1999Q3, @{'var123'@}, @{'var_@{123@}'@});
@end example

@sp 1

@example In a Matlab/Octave script:
>> do1 = dseries(dates('1999Q3'));
>> do2 = dseries('filename.csv');
>> do3 = dseries([1; 2; 3], dates('1999Q3'), @{'var123'@}, @{'var_@{123@}'@});
@end example

@sp 1

@noindent One can easily create subsamples from a @dseries object using the overloaded parenthesis operator. If @var{ds} is a @dseries object with @math{T} observations and @var{d} is a @dates object with @math{S<T} elements, such that @math{min(d)} is not smaller than the date associated to the first observation in @var{ds} and @math{max(d)} is not greater than the date associated to the last observation, then @code{ds(d)} instantiates a new @dseries object containing the subsample defined by @var{d}.

@noindent A list of the available methods, by alphabetical order, is given below.

@deftypefn {dseries} {@var{A} =} abs (@var{B})

Overloads the @code{abs()} function for @dseries objects. Returns the absolute value of the variables in @dseries object @var{B}.

@examplehead
@example
>> ts0 = dseries(randn(3,2),'1973Q1',@{'A1'; 'A2'@},@{'A_1'; 'A_2'@});
>> ts1 = ts0.abs();
>> ts0

ts0 is a dseries object:

       | A1       | A2
1973Q1 | -0.67284 | 1.4367
1973Q2 | -0.51222 | -0.4948
1973Q3 | 0.99791  | 0.22677

>> ts1

ts1 is a dseries object:

       | abs(A1) | abs(A2)
1973Q1 | 0.67284 | 1.4367
1973Q2 | 0.51222 | 0.4948
1973Q3 | 0.99791 | 0.22677

>> ts1.tex

ans =

    '|A_1|'
    '|A_2|'
@end example

@end deftypefn

@sp 1

@deftypefn {dseries} {[@var{A}, @var{B}] = } align (@var{A}, @var{B})

If @dseries objects @var{A} and @var{B} are defined on different time ranges, this function extends @var{A} and/or @var{B} with NaNs so that they are defined on the same time range. Note that both @dseries objects must have the same frequency.

@examplehead
@example
>> ts0 = dseries(rand(5,1),dates('2000Q1')); % 2000Q1 -> 2001Q1
>> ts1 = dseries(rand(3,1),dates('2000Q4')); % 2000Q4 -> 2001Q2
>> [ts0, ts1] = align(ts0, ts1);             % 2000Q1 -> 2001Q2
>> ts0

ts0 is a dseries object:

       | Variable_1
2000Q1 | 0.81472
2000Q2 | 0.90579
2000Q3 | 0.12699
2000Q4 | 0.91338
2001Q1 | 0.63236
2001Q2 | NaN

>> ts1

ts1 is a dseries object:

       | Variable_1
2000Q1 | NaN
2000Q2 | NaN
2000Q3 | NaN
2000Q4 | 0.66653
2001Q1 | 0.17813
2001Q2 | 0.12801
@end example

@end deftypefn

@sp 1

@deftypefn {dseries} {@var{B} = } baxter_king_filter (@var{A}, @var{hf}, @var{lf}, @var{K})

Implementation of the @cite{Baxter and King (1999)} band pass filter for @dseries objects. This filter isolates business cycle fluctuations with a period of length ranging between @var{hf} (high frequency) to @var{lf} (low frequency) using a symmetric moving average smoother with @math{2K+1} points, so that K observations at the beginning and at the end of the  sample are lost in the computation of the filter. The default value for @var{hf} is @math{6}, for @var{lf} is @math{32}, and for @var{K} is 12.

@examplehead
@example
% Simulate a component model (stochastic trend, deterministic trend, and a
% stationary autoregressive process).
e = .2*randn(200,1);
u = randn(200,1);
stochastic_trend = cumsum(e);
deterministic_trend = .1*transpose(1:200);
x = zeros(200,1);
for i=2:200
    x(i) = .75*x(i-1) + e(i);
end
y = x + stochastic_trend + deterministic_trend;

% Instantiates time series objects.
ts0 = dseries(y,'1950Q1');
ts1 = dseries(x,'1950Q1'); % stationary component.

% Apply the Baxter-King filter.
ts2 = ts0.baxter_king_filter();

% Plot the filtered time series.
plot(ts1(ts2.dates).data,'-k'); % Plot of the stationary component.
hold on
plot(ts2.data,'--r');           % Plot of the filtered y.
hold off
axis tight
id = get(gca,'XTick');
set(gca,'XTickLabel',strings(ts1.dates(id)));
@end example

@iftex
@sp 1
The previous code should produce something like:
@center
@image{dynare.plots/BaxterKingFilter,11.32cm,7cm}
@end iftex

@end deftypefn

@sp 1

@deftypefn {dseries} {@var{C} = } chain (@var{A}, @var{B})

Merge two @dseries objects along the time dimension. The two objects must have the same number of observed variables, and the initial date in @var{B} must not be posterior to the last date in @var{A}. The returned @dseries object, @var{C}, is built by extending @var{A} with the cumulated growth factors of @var{B}.

@examplehead
@example
>> ts = dseries([1; 2; 3; 4],dates(`1950Q1'))

ts is a dseries object:

       | Variable_1
1950Q1 | 1
1950Q2 | 2
1950Q3 | 3
1950Q4 | 4

>> us = dseries([3; 4; 5; 6],dates(`1950Q3'))

us is a dseries object:

       | Variable_1
1950Q3 | 3
1950Q4 | 4
1951Q1 | 5
1951Q2 | 6

>> chain(ts, us)

ans is a dseries object:

       | Variable_1
1950Q1 | 1
1950Q2 | 2
1950Q3 | 3
1950Q4 | 4
1951Q1 | 5
1951Q2 | 6

@end example

@end deftypefn

@sp 1

@deftypefn {dseries} {[@var{error_flag}, @var{message} ] = } check (@var{A})

Sanity check of @dseries object @var{A}. Returns @math{1} if there is an error, @math{0} otherwise. The second output argument is a string giving brief informations about the error.

@end deftypefn

@sp 1

@deftypefn {dseries} {@var{B} = } cumprod (@var{A}[, @var{d}[, @var{v}]])

Overloads the Matlab/Octave @code{cumprod} function for @dseries objects. The cumulated product cannot be computed if the variables in @dseries object @var{A} has @code{NaN}s. If a @dates object @var{d} is provided as a second argument, then the method computes the cumulated product with the additional constraint that the variables in the @dseries object @var{B} are equal to one in period @var{d}. If a single observation @dseries object @var{v} is provided as a third argument, the cumulated product in @var{B} is normalized such that @code{B(@var{d})} matches @var{v} (@dseries objects @var{A} and @var{v} must have the same number of variables).

@examplehead
@example
>> ts1 = dseries(2*ones(7,1));
>> ts2 = ts1.cumprod();
>> ts2

ts2 is a dseries object:

   | cumprod(Variable_1)
1Y | 2
2Y | 4
3Y | 8
4Y | 16
5Y | 32
6Y | 64
7Y | 128

>> ts3 = ts1.cumsum(dates('3Y'));
>> ts3

ts3 is a dseries object:

   | cumprod(Variable_1)
1Y | 0.25
2Y | 0.5
3Y | 1
4Y | 2
5Y | 4
6Y | 8
7Y | 16

>> ts4 = ts1.cumsum(dates('3Y'),dseries(pi));
>> ts4

ts4 is a dseries object:

   | cumprod(Variable_1)
1Y | 0.7854
2Y | 1.5708
3Y | 3.1416
4Y | 6.2832
5Y | 12.5664
6Y | 25.1327
7Y | 50.2655
@end example

@end deftypefn

@sp 1

@deftypefn {dseries} {@var{B} = } cumsum (@var{A}[, @var{d}[, @var{v}]])

Overloads the Matlab/Octave @code{cumsum} function for @dseries objects. The cumulated sum cannot be computed if the variables in @dseries object @var{A} has @code{NaN}s. If a @dates object @var{d} is provided as a second argument, then the method computes the cumulated sum with the additional constraint that the variables in the @dseries object @var{B} are zero in period @var{d}. If a single observation @dseries object @var{v} is provided as a third argument, the cumulated sum in @var{B} is such that @code{B(@var{d})} matches @var{v} (@dseries objects @var{A} and @var{v} must have the same number of variables).

@examplehead
@example
>> ts1 = dseries(ones(10,1));
>> ts2 = ts1.cumsum();
>> ts2

ts2 is a dseries object:

    | cumsum(Variable_1)
1Y  | 1
2Y  | 2
3Y  | 3
4Y  | 4
5Y  | 5
6Y  | 6
7Y  | 7
8Y  | 8
9Y  | 9
10Y | 10

>> ts3 = ts1.cumsum(dates('3Y'));
>> ts3

ts3 is a dseries object:

    | cumsum(Variable_1)
1Y  | -2
2Y  | -1
3Y  | 0
4Y  | 1
5Y  | 2
6Y  | 3
7Y  | 4
8Y  | 5
9Y  | 6
10Y | 7

>> ts4 = ts1.cumsum(dates('3Y'),dseries(pi));
>> ts4

ts4 is a dseries object:

    | cumsum(Variable_1)
1Y  | 1.1416
2Y  | 2.1416
3Y  | 3.1416
4Y  | 4.1416
5Y  | 5.1416
6Y  | 6.1416
7Y  | 7.1416
8Y  | 8.1416
9Y  | 9.1416
10Y | 10.1416
@end example

@end deftypefn

@sp 1

@deftypefn{dseries} {@var{C} =} eq (@var{A}, @var{B})

Overloads the Matlab/Octave @code{eq} (equal, @code{==}) operator. @dseries objects @var{A} and @var{B} must have the  same number of observations (say, @math{T}) and variables (@math{N}). The returned argument is a @math{T} by @math{N} matrix of zeros and ones. Element @math{(i,j)} of @var{C} is equal to @code{1} if and only if observation @math{i} for variable @math{j} in @var{A} and @var{B} are the same.

@examplehead
@example
>> ts0 = dseries(2*ones(3,1));
>> ts1 = dseries([2; 0; 2]);
>> ts0==ts1

ans =

     1
     0
     1
@end example

@end deftypefn

@sp 1

@deftypefn{dseries} {@var{B} =} exp (@var{A})

Overloads the Matlab/Octave @code{exp} function for @dseries objects.
@examplehead
@example
>> ts0 = dseries(rand(10,1));
>> ts1 = ts0.exp();
@end example

@end deftypefn

@sp 1

@deftypefn{dseries} {@var{l} =} exist (@var{A}, @var{varname})

Tests if @var{variable} exists in @dseries object @var{A}. Returns 1 (true) iff @var{variable} exists in @var{A}.

@exampleshead

@example
>> ts = dseries(randn(100,1));
>> ts.exist('Variable_1')

ans =

     1

>> ts.exist('Variable_2')

ans =

     0
@end example

@end deftypefn

@sp 1

@deftypefn{dseries} {@var{C} =} extract (@var{A}, @var{B}[, ...])

Extracts some variables from a @dseries object @var{A} and returns a @dseries object @var{C}. The input arguments following @var{A} are strings representing the variables to be selected in the new @dseries object @var{C}. To simplify the creation of sub-objects, the @dseries class overloads the curly braces (@code{D = extract (A, B, C)} is equivalent to @code{D = A@{B,C@}}) and allows implicit loops (defined between a pair of @@ symbol, see examples below) or Matlab/Octave's regular expressions (introduced by square brackets).

@exampleshead

@noindent The following selections are equivalent:
@example
>> ts0 = dseries(ones(100,10));
>> ts1 = ts0@{'Variable_1','Variable_2','Variable_3'@};
>> ts2 = ts0@{'Variable_@@1,2,3@@'@}
>> ts3 = ts0@{'Variable_[1-3]$'@}
>> isequal(ts1,ts2) && isequal(ts1,ts3)

ans =

     1
@end example

@noindent It is possible to use up to two implicit loops to select variables:
@example
names = @{'GDP_1';'GDP_2';'GDP_3'; 'GDP_4'; 'GDP_5'; 'GDP_6'; 'GDP_7'; 'GDP_8'; ...
      'GDP_9'; 'GDP_10'; 'GDP_11'; 'GDP_12'; ...
      'HICP_1';'HICP_2';'HICP_3'; 'HICP_4'; 'HICP_5'; 'HICP_6'; 'HICP_7'; 'HICP_8'; ...
      'HICP_9'; 'HICP_10'; 'HICP_11'; 'HICP_12'@};

ts0 = dseries(randn(4,24),dates('1973Q1'),names);
ts0@{'@@GDP,HICP@@_@@1,3,5@@'@}

ans is a dseries object:

       | GDP_1    | GDP_3     | GDP_5     | HICP_1   | HICP_3   | HICP_5
1973Q1 | 1.7906   | -1.6606   | -0.57716  | 0.60963  | -0.52335 | 0.26172
1973Q2 | 2.1624   | 3.0125    | 0.52563   | 0.70912  | -1.7158  | 1.7792
1973Q3 | -0.81928 | 1.5008    | 1.152     | 0.2798   | 0.88568  | 1.8927
1973Q4 | -0.03705 | -0.35899  | 0.85838   | -1.4675  | -2.1666  | -0.62032
@end example

@end deftypefn

@sp 1

@deftypefn {dseries} {@var{f} =} freq (@var{B})

Returns the frequency of the variables in @dseries object @var{B}.

@examplehead
@example
>> ts = dseries(randn(3,2),'1973Q1');
>> ts.freq

ans =

     4
@end example

@end deftypefn

@sp 1

@deftypefn{dseries} {@var{D} =} horzcat (@var{A}, @var{B}[, ...])

Overloads the @code{horzcat} Matlab/Octave's method for @dseries
objects. Returns a @dseries object @var{D} containing the variables
in @dseries objects passed as inputs: @var{A}, @var{B}, ... If the
inputs are not defined on the same time ranges, the method adds
@code{NaN}s to the variables so that the variables are redefined on
the smallest common time range. Note that the names in the @dseries
objects passed as inputs must be different and these objects must have
common frequency.

@examplehead
@example
>> ts0 = dseries(rand(5,2),'1950Q1',@{'nifnif';'noufnouf'@});
>> ts1 = dseries(rand(7,1),'1950Q3',@{'nafnaf'@});
>> ts2 = [ts0, ts1];
>> ts2

ts2 is a dseries object:

       | nifnif  | noufnouf | nafnaf
1950Q1 | 0.17404 | 0.71431  | NaN
1950Q2 | 0.62741 | 0.90704  | NaN
1950Q3 | 0.84189 | 0.21854  | 0.83666
1950Q4 | 0.51008 | 0.87096  | 0.8593
1951Q1 | 0.16576 | 0.21184  | 0.52338
1951Q2 | NaN     | NaN      | 0.47736
1951Q3 | NaN     | NaN      | 0.88988
1951Q4 | NaN     | NaN      | 0.065076
1952Q1 | NaN     | NaN      | 0.50946
@end example

@end deftypefn

@sp 1

@deftypefn {dseries} {@var{B} = } hpcycle (@var{A}[, @var{lambda}])

Extracts the cycle component from a @dseries @var{A} object using
Hodrick Prescott (1997) filter and returns a @dseries object, @var{B}. The
default value for @var{lambda}, the smoothing parameter, is
@math{1600}.

@examplehead
@example
% Simulate a component model (stochastic trend, deterministic trend, and a
% stationary autoregressive process).
e = .2*randn(200,1);
u = randn(200,1);
stochastic_trend = cumsum(e);
deterministic_trend = .1*transpose(1:200);
x = zeros(200,1);
for i=2:200
    x(i) = .75*x(i-1) + e(i);
end
y = x + stochastic_trend + deterministic_trend;

% Instantiates time series objects.
ts0 = dseries(y,'1950Q1');
ts1 = dseries(x,'1950Q1'); % stationary component.

% Apply the HP filter.
ts2 = ts0.hpcycle();

% Plot the filtered time series.
plot(ts1(ts2.dates).data,'-k'); % Plot of the stationary component.
hold on
plot(ts2.data,'--r');           % Plot of the filtered y.
hold off
axis tight
id = get(gca,'XTick');
set(gca,'XTickLabel',strings(ts.dates(id)));
@end example

@iftex
@sp 1
The previous code should produce something like:
@center
@image{dynare.plots/HPCycle,11.32cm,7cm}
@end iftex

@end deftypefn

@sp 1

@deftypefn {dseries} {@var{B} = } hptrend (@var{A}[, @var{lambda}])

Extracts the trend component from a @dseries @var{A} object using Hodrick Prescott (1997) filter and returns a @dseries object, @var{B}. Default value for @var{lambda}, the smoothing parameter, is  @math{1600}.

@examplehead
Using the same generating data process as in the previous example:
@example
ts1 = dseries(stochastic_trend + deterministic_trend,'1950Q1');
% Apply the HP filter.
ts2 = ts0.hptrend();

% Plot the filtered time series.
plot(ts1.data,'-k'); % Plot of the nonstationary components.
hold on
plot(ts2.data,'--r');           % Plot of the estimated trend.
hold off
axis tight
id = get(gca,'XTick');
set(gca,'XTickLabel',strings(ts0.dates(id)));
@end example

@iftex
@sp 1
The previous code should produce something like:
@center
@image{dynare.plots/HPTrend,11.32cm,7cm}
@end iftex

@end deftypefn

@sp 1

@deftypefn {dseries} {@var{f} =} init (@var{B})

Returns the initial date in @dseries object @var{B}.

@examplehead
@example
>> ts = dseries(randn(3,2),'1973Q1');
>> ts.init
ans = <dates: 1973Q1>
@end example

@end deftypefn

@sp 1

@deftypefn {dseries} {@var{C} = } insert (@var{A}, @var{B}, @var{I})

Inserts variables contained in @dseries object @var{B} in @dseries object @var{A} at positions specified by integer scalars in vector @var{I}, returns augmented @dseries object @var{C}. The integer scalars in @var{I} must take values between @code{1} and @code{A.length()+1} and refers to @var{A}'s column numbers. The @dseries objects @var{A} and @var{B} need not to be defined over the same time ranges, but it is assumed that they have common frequency.

@examplehead
@example
>> ts0 = dseries(ones(2,4),'1950Q1',@{'Sly'; 'Gobbo'; 'Sneaky'; 'Stealthy'@});
>> ts1 = dseries(pi*ones(2,1),'1950Q1',@{'Noddy'@});
>> ts2 = ts0.insert(ts1,3)

ts2 is a dseries object:

       | Sly | Gobbo | Noddy  | Sneaky | Stealthy
1950Q1 | 1   | 1     | 3.1416 | 1      | 1
1950Q2 | 1   | 1     | 3.1416 | 1      | 1

>> ts3 = dseries([pi*ones(2,1) sqrt(pi)*ones(2,1)],'1950Q1',@{'Noddy';'Tessie Bear'@});
>> ts4 = ts0.insert(ts1,[3, 4])

ts4 is a dseries object:

       | Sly | Gobbo | Noddy  | Sneaky | Tessie Bear | Stealthy
1950Q1 | 1   | 1     | 3.1416 | 1      | 1.7725      | 1
1950Q2 | 1   | 1     | 3.1416 | 1      | 1.7725      | 1
@end example

@end deftypefn

@sp 1

@deftypefn {dseries} {@var{B} = } isempty (@var{A})

Overloads the Matlab/octave's @code{isempty} function. Returns @code{1} if @dseries object @var{A} is empty, @code{0} otherwise.

@end deftypefn

@sp 1

@deftypefn {dseries} {@var{C} = } isequal (@var{A},@var{B})

Overloads the Matlab/octave's @code{isequal} function. Returns @code{1} if @dseries objects @var{A} and @code{B} are identical, @code{0} otherwise.

@end deftypefn

@sp 1

@deftypefn {dseries} {@var{B} = } lag (@var{A}[, @var{p}])

Returns lagged time series. Default value of @var{p}, the number of lags, is @code{1}.

@exampleshead

@example
>> ts0 = dseries(transpose(1:4),'1950Q1')

ts0 is a dseries object:

       | Variable_1
1950Q1 | 1
1950Q2 | 2
1950Q3 | 3
1950Q4 | 4

>> ts1 = ts0.lag()

ts1 is a dseries object:

       | lag(Variable_1,1)
1950Q1 | NaN
1950Q2 | 1
1950Q3 | 2
1950Q4 | 3

>> ts2 = ts0.lag(2)

ts2 is a dseries object:

       | lag(Variable_1,2)
1950Q1 | NaN
1950Q2 | NaN
1950Q3 | 1
1950Q4 | 2
@end example

@noindent @dseries class overloads the parenthesis so that @code{ts.lag(p)} can be written more compactly as @code{ts(-p)}. For instance:

@example
>> ts0.lag(1)

ans is a dseries object:

       | lag(Variable_1,1)
1950Q1 | NaN
1950Q2 | 1
1950Q3 | 2
1950Q4 | 3
@end example

@noindent or alternatively:

@example
>> ts0(-1)

ans is a dseries object:

       | lag(Variable_1,1)
1950Q1 | NaN
1950Q2 | 1
1950Q3 | 2
1950Q4 | 3
@end example

@end deftypefn

@sp 1

@deftypefn {dseries} {@var{l} =} last (@var{B})

Returns the last date in @dseries object @var{B}.

@examplehead
@example
>> ts = dseries(randn(3,2),'1973Q1');
>> ts.last
ans = <dates: 1973Q3>
@end example

@end deftypefn

@sp 1

@deftypefn {dseries} {@var{B} = } lead (@var{A}[, @var{p}])

Returns leaded time series. Default value of @var{p}, the number of leads, is @code{1}. As for the @code{lag} method, the @dseries class overloads the parenthesis so that @code{ts.lead(p)} is equivalent to @code{ts(p)}.

@examplehead

@example
>> ts0 = dseries(transpose(1:4),'1950Q1');
>> ts1 = ts0.lead()

ts1 is a dseries object:

       | lead(Variable_1,1)
1950Q1 | 2
1950Q2 | 3
1950Q3 | 4
1950Q4 | NaN

>> ts2 = ts0(2)

ts2 is a dseries object:

       | lead(Variable_1,2)
1950Q1 | 3
1950Q2 | 4
1950Q3 | NaN
1950Q4 | NaN
@end example

@end deftypefn

@noindent @remarkhead

@noindent The overloading of the parenthesis for @dseries objects, allows to easily create new @dseries objects by copying/pasting equations declared in the @code{model} block. For instance, if an Euler equation is defined in the @code{model} block:

@example
model;
    ...
    1/C - beta/C(1)*(exp(A(1))*K^(alpha-1)+1-delta) ;
    ...
end;
@end example

@noindent and if variables @var{C}, @var{A} and @var{K} are defined as @dseries objects, then by writting:

@example
Residuals = 1/C - beta/C(1)*(exp(A(1))*K^(alpha-1)+1-delta) ;
@end example

@noindent outside of the @code{model} block, we create a new @dseries object, called @code{Residuals}, for the residuals of the Euler equation (the conditional expectation of the equation defined in the @code{model} block is zero, but the residuals are non zero).

@sp 1

@deftypefn{dseries} {@var{B} =} log (@var{A})

Overloads the Matlab/Octave @code{log} function for @dseries objects.
@examplehead
@example
>> ts0 = dseries(rand(10,1));
>> ts1 = ts0.log();
@end example

@end deftypefn

@sp 1

@deftypefn{dseries} {@var{C} =} merge (@var{A}, @var{B})

Merges two @dseries objects @var{A} and @var{B} in @dseries object @var{C}. Objects @var{A} and @var{B} need to have common frequency but can be defined on different time ranges. If a variable, say @code{x}, is defined both in @dseries objects @var{A} and @var{B}, then the merge will select the variable @code{x} as defined in the second input argument, @var{B}.

@examplehead
@example
>> ts0 = dseries(rand(3,2),'1950Q1',@{'A1';'A2'@})

ts0 is a dseries object:

       | A1       | A2
1950Q1 | 0.42448  | 0.92477
1950Q2 | 0.60726  | 0.64208
1950Q3 | 0.070764 | 0.1045

>> ts1 = dseries(rand(3,1),'1950Q2',@{'A1'@})

ts1 is a dseries object:

       | A1
1950Q2 | 0.70023
1950Q3 | 0.3958
1950Q4 | 0.084905

>> merge(ts0,ts1)

ans is a dseries object:

       | A1       | A2
1950Q1 | NaN      | 0.92477
1950Q2 | 0.70023  | 0.64208
1950Q3 | 0.3958   | 0.1045
1950Q4 | 0.084905 | NaN

>> merge(ts1,ts0)

ans is a dseries object:

       | A1       | A2
1950Q1 | 0.42448  | 0.92477
1950Q2 | 0.60726  | 0.64208
1950Q3 | 0.070764 | 0.1045
1950Q4 | NaN      | NaN
@end example

@end deftypefn

@sp 1

@deftypefn{dseries} {@var{C} =} minus (@var{A}, @var{B})

Overloads the @code{minus} (@code{-}) operator for @dseries objects,
element by element subtraction. If both @var{A} and @var{B}
are @dseries objects, they do not need to be defined over the same
time ranges. If @var{A} and @var{B} are @dseries objects with
@math{T_A} and @math{T_B} observations and @math{N_A} and @math{N_B}
variables, then @math{N_A} must be equal to @math{N_B} or @math{1} and
@math{N_B} must be equal to @math{N_A} or @math{1}. If @math{T_A=T_B},
@code{isequal(A.init,B.init)} returns 1 and @math{N_A=N_B}, then the
@code{minus} operator will compute for each couple @math{(t,n)}, with
@math{1\le t\le T_A} and @math{1\le n\le N_A},
@code{C.data(t,n)=A.data(t,n)-B.data(t,n)}. If @math{N_B} is equal to
@math{1} and @math{N_A>1}, the smaller @dseries object (@var{B}) is
``broadcast'' across the larger @dseries (@var{A}) so that they have
compatible shapes, the @code{minus} operator will subtract the
variable defined in @var{B} from each variable in @var{A}. If @var{B}
is a double scalar, then the method @code{minus} will subtract
@var{B} from all the observations/variables in @var{A}. If @var{B} is
a row vector of length @math{N_A}, then the @code{minus} method will
subtract @code{B(i)} from all the observations of variable @code{i},
for @math{i=1,...,N_A}. If @var{B} is a column vector of length
@math{T_A}, then the @code{minus} method will subtract @code{B} from
all the variables.

@examplehead
@example
>> ts0 = dseries(rand(3,2));
>> ts1 = ts0@{'Variable_2'@};
>> ts0-ts1

ans is a dseries object:

   | minus(Variable_1,Variable_2) | minus(Variable_2,Variable_2)
1Y | -0.48853                     | 0
2Y | -0.50535                     | 0
3Y | -0.32063                     | 0

>> ts1

ts1 is a dseries object:

   | Variable_2
1Y | 0.703
2Y | 0.75415
3Y | 0.54729

>> ts1-ts1.data(1)

ans is a dseries object:

   | minus(Variable_2,0.703)
1Y | 0
2Y | 0.051148
3Y | -0.15572

>> ts1.data(1)-ts1

ans is a dseries object:

   | minus(0.703,Variable_2)
1Y | 0
2Y | -0.051148
3Y | 0.15572
@end example

@end deftypefn

@sp 1

@deftypefn{dseries} {@var{C} =} mpower (@var{A}, @var{B})

Overloads the @code{mpower} (@code{^}) operator for @dseries objects and computes element-by-element power. @var{A} is a @dseries object with @code{N} variables and @code{T} observations. If @var{B} is a real scalar, then @code{mpower(@var{A},@var{B})} returns a @dseries object @var{C} with @code{C.data(t,n)=A.data(t,n)^C}. If @var{B} is a @dseries object with @code{N} variables and @code{T} observations then @code{mpower(@var{A},@var{B})} returns a @dseries object @var{C} with @code{C.data(t,n)=A.data(t,n)^C.data(t,n)}.

@examplehead
@example
>> ts0 = dseries(transpose(1:3));
>> ts1 = ts0^2

ts1 is a dseries object:

   | power(Variable_1,2)
1Y | 1
2Y | 4
3Y | 9

>> ts2 = ts0^ts0

ts2 is a dseries object:

   | power(Variable_1,Variable_1)
1Y | 1
2Y | 4
3Y | 27
@end example

@end deftypefn

@sp 1

@deftypefn{dseries} {@var{C} =} mrdivide (@var{A}, @var{B})

Overloads the @code{mrdivide} (@code{/}) operator for @dseries
objects, element by element division (like the @code{./} Matlab/Octave
operator). If both @var{A} and @var{B} are @dseries objects, they do
not need to be defined over the same time ranges. If @var{A} and
@var{B} are @dseries objects with @math{T_A} and @math{T_B}
observations and @math{N_A} and @math{N_B} variables, then @math{N_A}
must be equal to @math{N_B} or @math{1} and @math{N_B} must be equal
to @math{N_A} or @math{1}. If @math{T_A=T_B},
@code{isequal(A.init,B.init)} returns 1 and @math{N_A=N_B}, then the
@code{mrdivide} operator will compute for each couple @math{(t,n)},
with @math{1\le t\le T_A} and @math{1\le n\le N_A},
@code{C.data(t,n)=A.data(t,n)/B.data(t,n)}. If @math{N_B} is equal to
@math{1} and @math{N_A>1}, the smaller @dseries object (@var{B}) is
``broadcast'' across the larger @dseries (@var{A}) so that they have
compatible shapes. In this case the @code{mrdivides} operator will
divide each variable defined in @var{A} by the variable in @var{B},
observation per observation. If @var{B} is a double scalar, then
@code{mrdivide} will divide all the observations/variables in @var{A}
by @var{B}. If @var{B} is a row vector of length @math{N_A}, then
@code{mrdivide} will divide all the observations of variable @code{i}
by @code{B(i)}, for @math{i=1,...,N_A}. If @var{B} is a column vector
of length @math{T_A}, then @code{mrdivide} will perform a division of
all the variables by @code{B}, element by element.

@examplehead
@example
>> ts0 = dseries(rand(3,2))

ts0 is a dseries object:

   | Variable_1 | Variable_2
1Y | 0.72918    | 0.90307
2Y | 0.93756    | 0.21819
3Y | 0.51725    | 0.87322

>> ts1 = ts0@{'Variable_2'@};
>> ts0/ts1

ans is a dseries object:

   | divide(Variable_1,Variable_2) | divide(Variable_2,Variable_2)
1Y | 0.80745                       | 1
2Y | 4.2969                        | 1
3Y | 0.59235                       | 1
@end example

@end deftypefn

@sp 1

@deftypefn{dseries} {@var{C} =} mtimes (@var{A}, @var{B})

Overloads the @code{mtimes} (@code{*}) operator for @dseries objects
and the Hadammard product (the @code{.*} Matlab/Octave operator). If
both @var{A} and @var{B} are @dseries objects, they do not need to be
defined over the same time ranges. If @var{A} and @var{B} are @dseries
objects with @math{T_A} and @math{T_B} observations and @math{N_A} and
@math{N_B} variables, then @math{N_A} must be equal to @math{N_B} or
@math{1} and @math{N_B} must be equal to @math{N_A} or @math{1}. If
@math{T_A=T_B}, @code{isequal(A.init,B.init)} returns 1 and
@math{N_A=N_B}, then the @code{mtimes} operator will compute for each
couple @math{(t,n)}, with @math{1\le t\le T_A} and @math{1\le n\le N_A},
@code{C.data(t,n)=A.data(t,n)*B.data(t,n)}. If @math{N_B} is equal to
@math{1} and @math{N_A>1}, the smaller @dseries object (@var{B}) is
``broadcast'' across the larger @dseries (@var{A}) so that they have
compatible shapes, @code{mtimes} operator will multiply each variable
defined in @var{A} by the variable in @var{B}, observation per
observation. If @var{B} is a double scalar, then the method
@code{mtimes} will multiply all the observations/variables in @var{A}
by @var{B}. If @var{B} is a row vector of length @math{N_A}, then the
@code{mtimes} method will multiply all the observations of variable
@code{i} by @code{B(i)}, for @math{i=1,...,N_A}. If @var{B} is a
column vector of length @math{T_A}, then the @code{mtimes} method will
perform a multiplication of all the variables by @code{B}, element by
element.

@end deftypefn

@sp 1

@deftypefn{dseries} {@var{C} =} ne (@var{A}, @var{B})

Overloads the Matlab/Octave @code{ne} (equal, @code{~=}) operator. @dseries objects @var{A} and @var{B} must have the  same number of observations (say, @math{T}) and variables (@math{N}). The returned argument is a @math{T} by @math{N} matrix of zeros and ones. Element @math{(i,j)} of @var{C} is equal to @code{1} if and only if observation @math{i} for variable @math{j} in @var{A} and @var{B} are not equal.

@examplehead
@example
>> ts0 = dseries(2*ones(3,1));
>> ts1 = dseries([2; 0; 2]);
>> ts0~=ts1

ans =

     0
     1
     0
@end example

@end deftypefn

@sp 1

@deftypefn{dseries} {@var{B} =} nobs (@var{A})

Returns the number of observations in @dseries object @var{A}.

@examplehead
@example
>> ts0 = dseries(randn(10));
>> ts0.nobs

ans =

    10
@end example

@end deftypefn

@sp 1

@deftypefn{dseries} {@var{h} =} plot (@var{A})
@deftypefnx{dseries} {@var{h} =} plot (@var{A}, @var{B})
@deftypefnx{dseries} {@var{h} =} plot (@var{A}[, ...])
@deftypefnx{dseries} {@var{h} =} plot (@var{A}, @var{B}[, ...])

Overloads Matlab/Octave's @code{plot} function for @dseries objects. Returns a Matlab/Octave plot handle, that can be used to modify the properties of the plotted time series. If only one @dseries object, @var{A}, is passed as argument, then the @code{plot} function will put the associated dates on the x-abscissa. If this @dseries object contains only one variable, additional arguments can be passed to modify the properties of the plot (as one would do with the Matlab/Octave's version of the @code{plot} function). If @dseries object @var{A} contains more than one variable, it is not possible to pass these additional arguments and the properties of the plotted time series must be modify using the returned plot handle and the Matlab/Octave @code{set} function (see example below). If two @dseries objects, @var{A} and @var{B}, are passed as input arguments, the @code{plot} function will plot the variables in @var{A} against the variables in @var{B} (the number of variables in each object must be the same otherwise an error is issued). Again, if each object contains only one variable additional arguments can be passed to modify the properties of the plotted time series, otherwise the Matlab/Octave @code{set} command has to be used.

@exampleshead

@noindent Define a @dseries object with two variables (named by default @code{Variable_1} and @code{Variable_2}):

@example
>> ts = dseries(randn(100,2),'1950Q1');
@end example

@noindent The following command will plot the first variable in @code{ts}

@example
>> plot(ts@{'Variable_1'@},'-k','linewidth',2);
@end example

@noindent The next command will draw all the variables in @code{ts} on the same figure:

@example
>> h = plot(ts);
@end example

@noindent If one wants to modify the properties of the plotted time series (line style, colours, ...), the @code{set} function can be used (see Matlab's documentation):

@example
>> set(h(1),'-k','linewidth',2);
>> set(h(2),'--r');
@end example

@noindent The follwing command will plot @code{Variable_1} against @code{exp(Variable_1)}:

@example
>> plot(ts@{'Variable_1'@},ts@{'Variable_1'@}.exp(),'ok');
@end example

@noindent Again, the properties can also be modified using the returned plot handle and the @code{set} function:

@example
>> h = plot(ts, ts.exp());
>> set(h(1),'ok');
>> set(h(2),'+r');
@end example

@end deftypefn

@sp 1

@deftypefn{dseries} {@var{C} =} plus (@var{A}, @var{B})

Overloads the @code{plus} (@code{+}) operator for @dseries objects,
element by element addition. If both @var{A} and @var{B} are @dseries
objects, they do not need to be defined over the same time ranges. If
@var{A} and @var{B} are @dseries objects with @math{T_A} and @math{T_B}
observations and @math{N_A} and @math{N_B} variables, then @math{N_A}
must be equal to @math{N_B} or @math{1} and @math{N_B} must be equal
to @math{N_A} or @math{1}. If @math{T_A=T_B},
@code{isequal(A.init,B.init)} returns 1 and @math{N_A=N_B}, then the
@code{plus} operator will compute for each couple @math{(t,n)}, with
@math{1\le t\le T_A} and @math{1\le n\le N_A},
@code{C.data(t,n)=A.data(t,n)+B.data(t,n)}. If @math{N_B} is equal to
@math{1} and @math{N_A>1}, the smaller @dseries object (@var{B}) is
``broadcast'' across the larger @dseries (@var{A}) so that they have
compatible shapes, the @code{plus} operator will add the variable
defined in @var{B} to each variable in @var{A}. If @var{B} is a double
scalar, then the method @code{plus} will add @var{B} to all the
observations/variables in @var{A}. If @var{B} is a row vector of
length @math{N_A}, then the @code{plus} method will add @code{B(i)} to
all the observations of variable @code{i}, for @math{i=1,...,N_A}. If
@var{B} is a column vector of length @math{T_A}, then the @code{plus}
method will add @code{B} to all the variables.

@end deftypefn

@sp 1

@deftypefn{dseries} {@var{C} =} pop (@var{A}[, @var{B}])

Removes variable @var{B} from @dseries object @var{A}. By default, if the second argument is not provided, the last variable is removed.

@examplehead
@example
>> ts0 = dseries(ones(3,3));
>> ts1 = ts0.pop('Variable_2');

ts1 is a dseries object:

   | Variable_1 | Variable_3
1Y | 1          | 1
2Y | 1          | 1
3Y | 1          | 1
@end example

@end deftypefn

@sp 1

@deftypefn{dseries} {@var{B} =} qdiff (@var{A})
@deftypefnx{dseries} {@var{B} =} qgrowth (@var{A})

Computes quarterly differences or growth rates.

@examplehead
@example
>> ts0 = dseries(transpose(1:4),'1950Q1');
>> ts1 = ts0.qdiff()

ts1 is a dseries object:

       | qdiff(Variable_1)
1950Q1 | NaN
1950Q2 | 1
1950Q3 | 1
1950Q4 | 1

>> ts0 = dseries(transpose(1:6),'1950M1');
>> ts1 = ts0.qdiff()

ts1 is a dseries object:

        | qdiff(Variable_1)
1950M1  | NaN
1950M2  | NaN
1950M3  | NaN
1950M4  | 3
1950M5  | 3
1950M6  | 3
@end example

@end deftypefn

@sp 1

@deftypefn{dseries} {@var{C} =} remove (@var{A}, @var{B})

Alias for the @code{pop} method with two arguments. Removes variable @var{B} from @dseries object @var{A}.

@examplehead
@example
>> ts0 = dseries(ones(3,3));
>> ts1 = ts0.remove('Variable_2');

ts1 is a dseries object:

   | Variable_1 | Variable_3
1Y | 1          | 1
2Y | 1          | 1
3Y | 1          | 1
@end example

@sp 1

A shorter syntax is available: @code{remove(ts,'Variable_2')} is
equivalent to @code{ts@{'Variable_2'@} = []} (@code{[]} can be replaced
by any empty object). This alternative syntax is usefull if more than
one variable has to be removed. For instance:
@example
ts@{'Variable_@@2,3,4@@'@} = [];
@end example
will remove @code{Variable_2}, @code{Variable_3} and @code{Variable_4}
from @dseries object @code{ts} (if these variables exist). Regular
expressions cannot be used but implicit loops can.

@end deftypefn

@sp 1

@deftypefn{dseries} {@var{B} =} rename (@var{A},@var{oldname},@var{newname})

Rename variable @var{oldname} to @var{newname} in @dseries object
@var{A}. Returns a @dseries object.

@examplehead
@example
>> ts0 = dseries(ones(2,2));
>> ts1 = ts0.rename('Variable_1','Stinkly')

ts1 is a dseries object:

   | Stinkly | Variable_2
1Y | 1       | 1
2Y | 1       | 1
@end example

@end deftypefn

@sp 1

@deftypefn{dseries} {@var{B} =} rename (@var{A},@var{newname})

Replace the names in @var{A} with those passed in the cell string array
@var{newname}. @var{newname} must have the same number of cells as @var{A} has
@var{dseries}. Returns a @dseries object.

@examplehead
@example
>> ts0 = dseries(ones(2,3));
>> ts1 = ts0.rename(@{'Tree','Worst','President'@})

ts1 is a dseries object:

   | Bush | Worst | President
1Y | 1    | 1     | 1
2Y | 1    | 1     | 1
@end example

@end deftypefn

@sp 1

@deftypefn{dseries} save (@var{A}, @var{basename}[, @var{format}])

Overloads the Matlab/Octave @code{save} function and saves @dseries
object @var{A} to disk. Possible formats are @code{csv} (this is the
default), @code{m} (Matlab/Octave script), and @code{mat} (Matlab
binary data file). The name of the file without extension is specified
by @var{basename}.

@examplehead
@example
>> ts0 = dseries(ones(2,2));
>> ts0.save('ts0');
@end example

@noindent The last command will create a file @code{ts0.csv} with the following content:

@example
,Variable_1,Variable_2
1Y,               1,               1
2Y,               1,               1
@end example

@noindent To create a Matlab/octave script, the following command:

@example
>> ts0.save('ts0','m');
@end example

@noindent will produce a file @code{ts0.m} with the following content:

@example
% File created on 14-Nov-2013 12:08:52.

FREQ__ = 1;
INIT__ = ' 1Y';

NAMES__ = @{'Variable_1'; 'Variable_2'@};
TEX__ = @{'Variable_@{1@}'; 'Variable_@{2@}'@};

Variable_1 = [
              1
              1];

Variable_2 = [
              1
              1];
@end example

@noindent The generated (@code{csv}, @code{m}, or @code{mat}) files can be loaded when instantiating a @dseries object as explained above.

@end deftypefn

@sp 1

@deftypefn{dseries} {@var{B} =} set_names (@var{A}, @var{s1}, @var{s2}, ...)

Renames variables in @dseries object @var{A} and returns a @dseries
object @var{B} with new names @var{s1}, @var{s2}, @var{s3}, ... The
number of input arguments after the first one (@dseries object
@var{A}) must be equal to @code{A.vobs} (the number of variables in
@var{A}). @var{s1} will be the name of the first variable in @var{B},
@var{s2} the name of the second variable in @var{B}, and so on.

@examplehead
@example
>> ts0 = dseries(ones(1,3));
>> ts1 = ts0.set_names('Barbibul',[],'Barbouille')

ts1 is a dseries object:

   | Barbibul | Variable_2 | Barbouille
1Y | 1        | 1          | 1
@end example

@end deftypefn

@sp 1

@deftypefn{dseries} {[@var{T}, @var{N} ] = } size (@var{A}[, @var{dim}])

Overloads the Matlab/Octave's @code{size} function. Returns the number of observations in @dseries object @var{A} (@emph{ie} @code{A.nobs}) and the number of variables (@emph{ie} @code{A.vobs}). If a second input argument is passed, the @code{size} function returns the number of observations if @code{dim=1} or the number of variables if @code{dim=2} (for all other values of @var{dim} an error is issued).

@examplehead
@example
>> ts0 = dseries(ones(1,3));
>> ts0.size()

ans =

     1     3
@end example

@end deftypefn

@sp 1

@anchor{tex_rename}
@deftypefn{dseries} {@var{B} =} tex_rename (@var{A}, @var{name}, @var{newtexname})

Redefines the tex name of variable @var{name} to @var{newtexname}
in @dseries object @var{A}. Returns a @dseries object.

@end deftypefn

@sp 1

@deftypefn{dseries} {@var{B} =} tex_rename (@var{A}, @var{newtexname})

Redefines the tex names of the @var{A} to those contained in
@var{newtexname}. Here, @var{newtexname} is a cell string array with the same
number of entries as variables in @var{A}

@end deftypefn

@sp 1

@deftypefn{dseries} {@var{B} =} uminus (@var{A})

Overloads @code{uminus} (@code{-}, unary minus) for @dseries object.

@examplehead
@example
>> ts0 = dseries(1)

ts0 is a dseries object:

   | Variable_1
1Y | 1

>> ts1 = -ts0

ts1 is a dseries object:

   | -Variable_1
1Y | -1
@end example

@end deftypefn

@sp 1

@deftypefn{dseries} {@var{D} =} vertcat (@var{A}, @var{B}[, ...])

Overloads the @code{vertcat} Matlab/Octave method for @dseries
objects. This method is used to append more observations to a @dseries
object. Returns a @dseries object @var{D} containing the variables
in @dseries objects passed as inputs. All the input arguments must
be @dseries objects with the same variables defined on @emph{different
time ranges}.

@examplehead
@example
>> ts0 = dseries(rand(2,2),'1950Q1',@{'nifnif';'noufnouf'@});
>> ts1 = dseries(rand(2,2),'1950Q3',@{'nifnif';'noufnouf'@});
>> ts2 = [ts0; ts1]

ts2 is a dseries object:

       | nifnif   | noufnouf
1950Q1 | 0.82558  | 0.31852
1950Q2 | 0.78996  | 0.53406
1950Q3 | 0.089951 | 0.13629
1950Q4 | 0.11171  | 0.67865
@end example

@end deftypefn

@sp 1

@deftypefn{dseries} {@var{B} =} vobs (@var{A})

Returns the number of variables in @dseries object @var{A}.

@examplehead
@example
>> ts0 = dseries(randn(10,2));
>> ts0.vobs

ans =

    2
@end example

@end deftypefn

@sp 1

@deftypefn{dseries} {@var{B} =} ydiff (@var{A})
@deftypefnx{dseries} {@var{B} =} ygrowth (@var{A})

Computes yearly differences or growth rates.

@end deftypefn

@sp 1

@node Reporting
@chapter Reporting

Dynare provides a simple interface for creating @LaTeX{} reports, comprised of
@LaTeX{} tables and @code{PGFPLOTS/Ti}@i{k}@code{Z} graphs. You can use the
report as created through Dynare or pick out the pieces (tables and graphs) you
want for inclusion in your own paper. Though Dynare provides a subset of
options available through @code{PGFPLOTS/Ti}@i{k}@code{Z}, you can easily
modify the graphs created by Dynare using the options available in the
@code{PGFPLOTS/Ti}@i{k}@code{Z} manual. You can either do this manually or by
passing the options to @ref{miscTikzAxisOptions}, @ref{miscTikzAxisOptions}, or
@ref{graphMiscTikzAddPlotOptions}.

Reports are created and modified by calling methods on class
objects. The objects are hierarchical, with the following order (from
highest to lowest): @code{Report, Page, Section, Graph/Table/Vspace,
Series}. For simplicity of syntax, we abstract away from these
classes, allowing you to operate directly on a @code{Report} object,
while maintaining the names of these classes in the @code{Report}
Class methods you will use.

The report is created sequentially, command by command, hence the
order of the commands matters. When an object of a certain hierarchy
is inserted, all methods will function on that object until an object
of equal or greater hierarchy is added. Hence, once you add a
@code{Page} to the report, every time you add a @code{Section} object,
it will be added to this @code{Page} until another @code{Page} is
added to the report (via @ref{addPage}). This will become more clear
with the example at the end of the section.

Options to the methods are passed differently than those to Dynare
commands. They take the form of named options to Matlab functions
where the arguments come in pairs (@i{e.g.}
@code{function_name(`option_1_name', `option_1_value',
`option_2_name', `option_2_value', ...)}, where @code{option_X_name}
is the name of the option while @code{option_X_value} is the value
assigned to that option). The ordering of the option pairs matters
only in the unusual case when an option is provided twice (probably
erroneously). In this case, the last value passed is the one that is
used.

Below, you will see a list of methods available for the Report class and
a clarifying example.

@defmethod Report report compiler, showDate, fileName, header, margin, marginUnit, orientation, paper, showOutput, title
Instantiates a @code{Report} object.
@optionshead
@table @code
@anchor{compiler}
@item compiler, @var{FILENAME}
The full path to the @LaTeX{} compiler on your system. If this option
is not provided, Dynare will try to find the appropriate program to
compile @LaTeX{} on your system. Default is system dependent: Windows:
the result of @code{findtexmf --file-type=exe pdflatex}, Mac OS X and
Linux: the result of @code{which pdflatex}

@item showDate, @code{BOOLEAN}
Display the date and time when the report was compiled. Default:
@code{true}

@anchor{filename}
@item fileName, @var{FILENAME}
The file name to use when saving this report. Default:
@code{report.tex}

@item header, @var{STRING}
The valid @LaTeX{} code to be included in the report before
@code{\begin@{document@}}. Default: @code{empty}

@item margin, @var{DOUBLE}
The margin size. Default: @code{2.5}

@item marginUnit, `cm' | `in'
Units associated with the margin. Default: @code{`cm'}

@anchor{orientation}
@item orientation, `landscape' | `portrait'
Paper orientation: Default: @code{`portrait'}

@anchor{paper}
@item paper, `a4' | `letter'
Paper size. Default: @code{`a4'}

@anchor{showOutput}
@item showOutput, @code{BOOLEAN}
Print report creation progress to screen. Shows you the page number as it is
created and as it is written. This is useful to see where a potential error
occurs in report creation. Default: @code{true}

@item title, @code{STRING}
Report Title. Default: @code{none}
@end table
@end defmethod

@anchor{addPage}
@defmethod Report addPage footnote, latex, orientation, pageDirName, paper, title, titleFormat, titleTruncate
Adds a @code{Page} to the @code{Report}.
@optionshead
@table @code
@item footnote, @code{STRING}
A footnote to be included at the bottom of this page. Default: @code{none}

@anchor{latex}
@item latex, @code{STRING}
The valid @LaTeX{} code to be used for this page. Alows the user to create a
page to be included in the report by passing @LaTeX{} code directly. If this
option is passed, the page itself will be saved in the @ref{pageDirName}
directory in the form @code{page_X.tex} where @code{X} refers to the page
number. Default @code{empty}

@item orientation, `landscape' | `portrait'
@xref{orientation}.

@anchor{pageDirName}
@item pageDirName, @code{STRING}
The name of the folder in which to store this page. Only used when the
@ref{latex} command is passed. Default: @code{tmpRepDir}

@item paper, `a4' | `letter'
@xref{paper}.

@anchor{title}
@item title, @code{STRING} | @code{CELL_ARRAY_STRINGS}
With one entry (a @code{STRING}), the title of the page. With more than one
entry (a @code{CELL_ARRAY_STRINGS}), the title and subtitle(s) of the
page. Values passed must be valid @LaTeX{} code (@i{e.g.,} `%' must be
`\%'). Default: @code{none}

@anchor{titleFormat}
@item titleFormat, @code{STRING} | @code{CELL_ARRAY_STRINGS}
A string representing the valid @LaTeX{} markup to use on @ref{title}. The
number of cell array entries must be equal to that of the @ref{title} option if
you do not want to use the default value for the title (and
subtitles). Default: @code{\large\bfseries}

@item titleTruncate, @code{INTEGER}
Useful when automatically generating page titles that may become too
long, @code{titleTruncate} can be used to truncate a title (and
subsequent subtitles) when they pass the specified number of
characters. Default: @code{off}

@end table
@end defmethod

@defmethod Report addSection cols, height
Adds a @code{Section} to a @code{Page}.
@optionshead
@table @code
@item cols, @code{INTEGER}
The number of columns in the section. Default: @code{1}

@item height, @code{STRING}
A string to be used with the @code{\sectionheight} @LaTeX{}
command. Default: @code{`!'}
@end table
@end defmethod

@anchor{addGraph}
@defmethod Report addGraph axisShape, data, graphDirName, graphName, graphSize, height, showGrid, showLegend, legendAt, showLegendBox, legendLocation, legendOrientation, legendFontSize, miscTikzAxisOptions, miscTikzPictureOptions, seriesToUse, shade, shadeColor, shadeOpacity, tickFontSize, title, titleFontSize, titleFormat, width, writeCSV, xlabel, ylabel, xAxisTight, xrange, xTicks, xTickLabels, xTickLabelAnchor, xTickLabelRotation, yAxisTight, yTickLabelFixed, yTickLabelPrecision, yTickLabelScaled, yTickLabelZeroFill, yrange, showZeroline, zeroLineColor
Adds a @code{Graph} to a @code{Section}.
@optionshead
@table @code
@anchor{data}
@item data, @code{dseries}
The @code{dseries} that provides the data for the graph. Default:
@code{none}

@item axisShape, @code{`box'} | @code{`L'}
The shape the axis should have. @code{`box'} means that there is an axis line
to the left, right, bottom, and top of the graphed line(s). @code{`L'} means
that there is an axis to the left and bottom of the graphed line(s). Default:
@code{`box'}

@anchor{graphDirName}
@item graphDirName, @code{STRING}
The name of the folder in which to store this figure. Default:
@code{tmpRepDir}

@anchor{graphName}
@item graphName, @code{STRING}
The name to use when saving this figure. Default: something of the
form @code{graph_pg1_sec2_row1_col3.tex}

@item height, @code{DOUBLE}
The height of the graph, in inches. Default: @code{4.5}

@item showGrid, @code{BOOLEAN}
Whether or not to display the major grid on the graph. Default:
@code{true}

@anchor{showLegend}
@item showLegend, @code{BOOLEAN}
Whether or not to display the legend. NB: Unless you use the
@ref{graphLegendName} option, the name displayed in the legend is the
@code{tex} name associated with the @code{dseries}. You can modify this
@code{tex} name by using @ref{tex_rename}. Default: @code{false}

@item legendAt, @code{NUMERICAL_VECTOR}
The coordinates for the legend location. If this option is passed, it
overrides the @ref{legendLocation} option. Must be of size 2. Default:
@code{empty}.

@item showLegendBox, @code{BOOLEAN}
Whether or not to display a box around the legend. Default:
@code{false}

@anchor{legendLocation}
@item legendLocation, @code{`south west'} | @code{`south east'} | @code{`north west'} | @code{`north east'} | @code{`outer north east'}
Where to place the legend in the graph. Default: @code{`south east'}

@item legendOrientation, `vertical' | `horizontal'
Orientation of the legend. Default: @code{`horizontal'}

@item legendFontSize, @code{`tiny'} | @code{`scriptsize'} | @code{`footnotesize'} | @code{`small'} | @code{`normalsize'} | @code{`large'} | @code{`Large'} | @code{`LARGE'} | @code{`huge'} | @code{`Huge'}
The font size for legend entries. Default: @code{tiny}

@anchor{miscTikzAxisOptions}
@item miscTikzAxisOptions, @code{STRING}
If you are comfortable with @code{PGFPLOTS/Ti}@i{k}@code{Z}, you can use this
option to pass arguments directly to the @code{PGFPLOTS/Ti}@i{k}@code{Z}
@code{axis} environment command. Specifically to be used for desired
@code{PGFPLOTS/Ti}@i{k}@code{Z} options that have not been incorporated into
Dynare Reproting. Default: @code{empty}

@anchor{miscTikzPictureOptions}
@item miscTikzPictureOptions, @code{STRING}
If you are comfortable with @code{PGFPLOTS/Ti}@i{k}@code{Z}, you can use this
option to pass arguments directly to the @code{PGFPLOTS/Ti}@i{k}@code{Z}
@code{tikzpicture} environment command. (@i{e.g.,} to scale the graph in the x
and y dimensions, you can pass following to this option: @code{`xscale=2.5,
yscale=0.5'}). Specifically to be used for desired
@code{PGFPLOTS/Ti}@i{k}@code{Z} options that have not been incorporated into
Dynare Reproting. Default: @code{empty}

@anchor{seriesToUse}
@item seriesToUse, @code{CELL_ARRAY_STRINGS}
The names of the series contained in the @code{dseries} provided to
the @ref{data} option. If empty, use all series provided to
@ref{data} option. Default: @code{empty}

@anchor{shade}
@item shade, @code{dates}
The date range showing the portion of the graph that should be
shaded. Default: @code{none}

@anchor{shadeColor}
@item shadeColor, @code{STRING}
The color to use in the shaded portion of the graph. All valid color strings defined for use by @code{PGFPLOTS/Ti}@i{k}@code{Z} are valid. A list of defined colors is: @code{`red'}, @code{`green'}, @code{`blue'}, @code{`cyan'}, @code{`magenta'}, @code{`yellow'}, @code{`black'}, @code{`gray'}, @code{`white'}, @code{`darkgray'}, @code{`lightgray'}, @code{`brown'}, @code{`lime'}, @code{`olive'}, @code{`orange'}, @code{`pink'}, @code{`purple'}, @code{`teal'}, and @code{`violet'}. Furthermore, You can use combinations of these colors. For example, if you wanted a color that is @math{20\%} green and @math{80\%} purple, you could pass the string @code{`green!20!purple'}. You can also use RGB colors, following the syntax: @code{`rgb,255:red,231;green,84;blue,121'} which corresponds to the RGB color @code{(231;84;121)}. More examples are available in the section 4.7.5 of the @code{PGFPLOTS/Ti}@i{k}@code{Z} manual, revision 1.10. Default: @code{`green'}

@item shadeOpacity, @code{DOUBLE}
The opacity of the shaded area, must be in @math{[0,100]}. Default: @code{20}

@item tickFontSize, , @code{`tiny'} | @code{`scriptsize'} | @code{`footnotesize'} | @code{`small'} | @code{`normalsize'} | @code{`large'} | @code{`Large'} | @code{`LARGE'} | @code{`huge'} | @code{`Huge'}
The font size for x- and y-axis tick labels. Default: @code{normalsize}

@anchor{graph.title}
@item title, @code{STRING} | @code{CELL_ARRAY_STRINGS}
Same as @ref{title}, just for graphs.

@item titleFontSize, @code{`tiny'} | @code{`scriptsize'} | @code{`footnotesize'} | @code{`small'} | @code{`normalsize'} | @code{`large'} | @code{`Large'} | @code{`LARGE'} | @code{`huge'} | @code{`Huge'}
The font size for title. Default: @code{normalsize}

@item titleFormat, @code{STRING}
The format to use for @ref{graph.title,,the graph title}. Unlike
@ref{titleFormat}, due to a constraint of TikZ, this format applies to
the title and subtitles. Default: @code{TikZ default}

@item width, @code{DOUBLE}
The width of the graph, in inches. Default: @code{6.0}

@item writeCSV, @code{BOOLEAN}
Whether or not to write a CSV file with only the plotted data. The file will be
saved in the directory specified by @ref{graphDirName} with the same base name
as specified by @ref{graphName} with the ending @code{.csv}. Default:
@code{false}

@item xlabel, @code{STRING}
The x-axis label. Default: @code{none}

@item ylabel, @code{STRING}
The y-axis label. Default: @code{none}

@item xAxisTight, @code{BOOLEAN}
Use a tight x axis. If false, uses @code{PGFPLOTS/Ti}@i{k}@code{Z}
@code{enlarge x limits} to choose appropriate axis size. Default: @code{true}

@item xrange, @code{dates}
The boundary on the x-axis to display in the graph. Default: all

@anchor{xTicks}
@item xTicks, @code{NUMERICAL_VECTOR}
Used only in conjunction with @ref{xTickLabels}, this option denotes
the numerical position of the label along the x-axis. The positions
begin at @math{1}. Default: the indices associated with the first and
last dates of the @code{dseries} and, if passed, the index associated
with the first date of the @ref{shade} option.

@anchor{xTickLabels}
@item xTickLabels, @code{CELL_ARRAY_STRINGS} | `ALL'
The labels to be mapped to the ticks provided by
@ref{xTicks}. Default: the first and last dates of the @code{dseries}
and, if passed, the date first date of the @ref{shade} option.

@item xTickLabelAnchor, @code{STRING}
Where to anchor the x tick label. Default: @code{`south'}

@item xTickLabelRotation, @code{DOUBLE}
The amount to rotate the x tick labels by. Default: @code{0}

@item yAxisTight, @code{BOOLEAN}
Use a tight y axis. If false, uses @code{PGFPLOTS/Ti}@i{k}@code{Z}
@code{enlarge y limits} to choose appropriate axis size. Default: @code{false}

@item yrange, @code{NUMERICAL_VECTOR}
The boundary on the y-axis to display in the graph, represented as a
@code{NUMERICAL_VECTOR} of size @math{2}, with the first entry less
than the second entry. Default: all

@item yTickLabelFixed, @code{BOOLEAN}
Round the y tick labels to a fixed number of decimal places, given by
@ref{yTickLabelPrecision}. Default: @code{true}

@anchor{yTickLabelPrecision}
@item yTickLabelPrecision, @code{INTEGER}
The precision with which to report the yTickLabel. Default: @code{1}

@item yTickLabelScaled, @code{BOOLEAN}
Determines whether or not there is a common scaling factor for the y
axis. Default: @code{true}

@item yTickLabelZeroFill, @code{BOOLEAN}
Whether or not to fill missing precision spots with zeros. Default: @code{true}

@anchor{showZeroLine}
@item showZeroline, @code{BOOLEAN}
Display a solid black line at @math{y = 0}. Default: @code{false}

@item zeroLineColor, @code{STRING}
The color to use for the zero line. Only used if @ref{showZeroLine} is
true. See the explanation in @ref{shadeColor} for how to use colors with
reports. Default: @code{`black'}

@end table
@end defmethod

@defmethod Report addTable data, highlightRows, showHlines, precision, range, seriesToUse, tableDirName, tableName, title, titleFormat, vlineAfter, vlineAfterEndOfPeriod, showVlines, writeCSV
Adds a @code{Table} to a @code{Section}.
@optionshead
@table @code

@item data, @code{dseries}
@xref{data}.

@item highlightRows, @code{CELL_ARRAY_STRINGS}
A cell array containing the colors to use for row highlighting. See
@ref{shadeColor} for how to use colors with reports. Highlighting for a
specific row can be overridden by using the @ref{tableRowColor} option to
@ref{addSeries}. Default: @code{empty}

@item showHlines, @code{BOOLEAN}
Whether or not to show horizontal lines separating the rows. Default: @code{false}

@anchor{precision}
@item precision, @code{INTEGER}
The number of decimal places to report in the table data. Default: @code{1}

@item range, @code{dates}
The date range of the data to be displayed. Default: @code{all}

@item seriesToUse, @code{CELL_ARRAY_STRINGS}
@xref{seriesToUse}.

@anchor{tableDirName}
@item tableDirName, @code{STRING}
The name of the folder in which to store this table. Default:
@code{tmpRepDir}

@anchor{tableName}
@item tableName, @code{STRING}
The name to use when saving this table. Default: something of the
form @code{table_pg1_sec2_row1_col3.tex}

@item title, @code{STRING}
Same as @ref{title}, just for tables.

@item titleFormat, @code{STRING}
Same as @ref{titleFormat}, just for tables. Default: @code{\large}.

@item vlineAfter, @code{dates} | @code{CELL_ARRAY_DATES}
Show a vertical line after the specified date (or dates if a cell
array of dates is passed). Default: @code{empty}

@item vlineAfterEndOfPeriod, @code{BOOLEAN}
Show a vertical line after the end of every period (@i{i.e.} after
every year, after the fourth quarter, etc.). Default: @code{false}

@item showVlines, @code{BOOLEAN}
Whether or not to show vertical lines separating the columns. Default: @code{false}

@item writeCSV, @code{BOOLEAN}
Whether or not to write a CSV file containing the data displayed in the
table. The file will be saved in the directory specified by @ref{tableDirName}
with the same base name as specified by @ref{tableName} with the ending
@code{.csv}. Default: @code{false}

@end table
@end defmethod

@anchor{addSeries}
@defmethod Report addSeries data, graphBar, graphBarColor, graphBarFillColor, graphBarWidth, graphFanShadeColor, graphFanShadeOpacity, graphHline, graphLegendName, graphLineColor, graphLineStyle, graphLineWidth, graphMarker, graphMarkerEdgeColor, graphMarkerFaceColor, graphMarkerSize, graphMiscTikzAddPlotOptions, graphShowInLegend, graphVline, tableDataRhs, tableRowColor, tableRowIndent, tableShowMarkers, tableAlignRight, tableNaNSymb, tableNegColor, tablePrecision, tablePosColor, tableSubSectionHeader, zeroTol
Adds a @code{Series} to a @code{Graph} or a @code{Table}. NB: Options specific
to graphs begin with `@code{graph}' while options specific to tables begin with
`@code{table}'.
@optionshead
@table @code

@item data, @code{dseries}
@xref{data}.

@anchor{graphBar}
@item graphBar, @code{BOOLEAN}
Whether or not to display this series as a bar graph as oppsed to the
default of displaying it as a line graph. Default: @code{false}

@anchor{graphFanShadeColor}
@item graphFanShadeColor, @code{STRING}
The shading color to use between a series and the previously-added
series in a graph. Useful for making fan charts. Default: @code{empty}

@item graphFanShadeOpacity, @code{INTEGER}
The opacity of the color passed in @ref{graphFanShadeColor}. Default:
@code{50}

@item graphBarColor, @code{STRING}
The outline color of each bar in the bar graph. Only active if
@ref{graphBar} is passed. Default: @code{`black'}

@item graphBarFillColor, @code{STRING}
The fill color of each bar in the bar graph. Only active if
@ref{graphBar} is passed. Default: @code{`black'}

@item graphBarWidth, @code{DOUBLE}
The width of each bar in the bar graph. Only active if @ref{graphBar}
is passed. Default: @code{2}

@item graphHline, @code{DOUBLE}
Use this option to draw a horizontal line at the given value. Default:
@code{empty}

@anchor{graphLegendName}
@item graphLegendName, @code{STRING}
The name to display in the legend for this series, passed as valid @LaTeX{}
(@i{e.g.,} @code{GDP_@{US@}}, @code{$\alpha$},
@code{\color@{red@}GDP\color@{black@}}). Will be displayed only if the
@ref{data} and @ref{showLegend} options have been passed. Default: the
@code{tex} name of the series

@item graphLineColor, @code{STRING}
Color to use for the series in a graph. See the explanation in @ref{shadeColor}
for how to use colors with reports. Default: @code{`black'}

@item graphLineStyle, @code{`none'} | @code{`solid'} | @code{`dotted'} | @code{`densely dotted'} | @code{`loosely dotted'} | @code{`dashed'} | @code{`densely dashed'} | @code{`loosely dashed'} | @code{`dashdotted'} | @code{`densely dashdotted'} | @code{`loosely dashdotted'} | @code{`dashdotdotted'} | @code{`densely dashdotdotted'} | @code{`loosely dashdotdotted'}
Line style for this series in a graph. Default: @code{`solid'}

@item graphLineWidth @code{DOUBLE}
Line width for this series in a graph. Default: @code{0.5}

@item graphMarker, @code{`x'} | @code{`+'} | @code{`-'} | @code{`|'} | @code{`o'} | @code{`asterisk'} | @code{`star'} | @code{`10-pointed star'} | @code{`oplus'} | @code{`oplus*'} | @code{`otimes'} | @code{`otimes*'} | @code{`square'} | @code{`square*'} | @code{`triangle'} | @code{`triangle*'} | @code{`diamond'} | @code{`diamond*'} | @code{`halfdiamond*'} | @code{`halfsquare*'} | @code{`halfsquare right*'} | @code{`halfsquare left*'} | @code{`Mercedes star'} | @code{`Mercedes star flipped'} | @code{`halfcircle'} | @code{`halfcircle*'} | @code{`pentagon'} | @code{`pentagon star'}
The Marker to use on this series in a graph. Default: @code{none}

@item graphMarkerEdgeColor, @code{STRING}
The edge color of the graph marker. See the explanation in @ref{shadeColor} for
how to use colors with reports. Default: @code{graphLineColor}

@item graphMarkerFaceColor, @code{STRING}
The face color of the graph marker. See the explanation in @ref{shadeColor} for
how to use colors with reports. Default: @code{graphLineColor}

@item graphMarkerSize, @code{DOUBLE}
The size of the graph marker. Default: @code{1}

@anchor{graphMiscTikzAddPlotOptions}
@item graphMiscTikzAddPlotOptions, @code{STRING}
If you are comfortable with @code{PGFPLOTS/Ti}@i{k}@code{Z}, you can use this
option to pass arguments directly to the @code{PGFPLOTS/Ti}@i{k}@code{Z}
@code{addPlots} command. (@i{e.g.,} Instead of passing the marker options
above, you can pass a string such as the following to this option:
@code{`mark=halfcircle*,mark options=@{rotate=90,scale=3@}'}). Specifically to be
used for desired @code{PGFPLOTS/Ti}@i{k}@code{Z} options that have not been
incorporated into Dynare Reproting. Default: @code{empty}

@item graphShowInLegend, @code{BOOLEAN}
Whether or not to show this series in the legend, given that the
@ref{showLegend} option was passed to @ref{addGraph}. Default: @code{true}

@item graphVline, @code{dates}
Use this option to draw a vertical line at a given date. Default: @code{empty}

@item tableDataRhs, @code{dseries}
A series to be added to the right of the current series. Usefull for
displaying aggregate data for a series. @i{e.g} if the series is
quarterly @code{tableDataRhs} could point to the yearly averages of
the quarterly series. This would cause quarterly data to be displayed
followed by annual data. Default: @code{empty}

@anchor{tableRowColor}
@item tableRowColor, @code{STRING}
The color that you want the row to be. Predefined values include
@code{LightCyan} and @code{Gray}. Default: @code{white}.

@item tableRowIndent, @code{INTEGER}
The number of times to indent the name of the series in the
table. Used to create subgroups of series. Default: @code{0}

@item tableShowMarkers, @code{BOOLEAN}
In a Table, if @code{true}, surround each cell with brackets and color
it according to @ref{tableNegColor} and @ref{tablePosColor}. No effect
for graphs. Default: @code{false}

@item tableAlignRight, @code{BOOLEAN}
Whether or not to align the series name to the right of the
cell. Default: @code{false}

@item tableMarkerLimit, @code{DOUBLE}
For values less than @math{-1*@code{tableMarkerLimit}}, mark the cell
with the color denoted by @ref{tableNegColor}. For those greater than
@code{tableMarkerLimit}, mark the cell with the color denoted by
@ref{tablePosColor}. Default: @code{1e-4}

@item tableNaNSymb, @code{STRING}
Replace @code{NaN} values with the text in this option. Default: @code{NaN}

@anchor{tableNegColor}
@item tableNegColor, @code{LATEX_COLOR}
The color to use when marking Table data that is less than
zero. Default: @code{`red'}

@item tablePrecision, @code{INTEGER}
The number of decimal places to report in the table data. Default: the value set by @ref{precision}

@anchor{tablePosColor}
@item tablePosColor, @code{LATEX_COLOR}
The color to use when marking Table data that is greater than
zero. Default: @code{`blue'}

@item tableSubSectionHeader, @code{STRING}
A header for a subsection of the table. No data will be associated
with it. It is equivalent to adding an empty series with a
name. Default: @code{''}

@item zeroTol, @code{DOUBLE}
The zero tolerance. Anything smaller than @code{zeroTol} and larger than
@code{-zeroTol} will be set to zero before being graphed or written to the
table. Default: @math{1e-6}

@end table
@end defmethod

@defmethod Report addParagraph balancedCols, cols, heading, indent, text
Adds a @code{Paragraph} to a @code{Section}. NB: The @code{Section} can only be
comprised of @code{Paragraphs} and must only have 1 column.
@optionshead
@table @code

@item balancedCols, @code{BOOLEAN}
Determines whether the text is spread out evenly across the columns when the
@code{Paragraph} has more than one column. Default: @code{true}

@item cols, @code{INTEGER}
The number of columns for the @code{Paragraph}. Default: @code{1}

@item heading, @code{STRING}
The heading for the Paragraph (like a section heading). The string must be
valid @LaTeX{} code. Default: @code{empty}

@item indent, @code{BOOLEAN}
Whether or not to indent the paragraph. Default: @code{true}

@item text, @code{STRING}
The paragraph itself. The string must be valid @LaTeX{} code. Default:
@code{empty}

@end table
@end defmethod

@defmethod Report addVspace hline, number
Adds a @code{Vspace} (vertical space) to a @code{Section}.
@optionshead
@table @code
@item hline, @code{INTEGER}
The number of horizontal lines to be inserted. Default: @code{0}

@item number, @code{INTEGER}
The number of new lines to be inserted. Default: @code{1}
@end table
@end defmethod

@anchor{write}
@defmethod Report write
Writes the @LaTeX{} representation of this @code{Report}, saving it to
the file specified by @ref{filename}.
@end defmethod

@defmethod Report compile compiler, showOutput, showReport
Compiles the report written by @ref{write} into a @code{pdf} file. If
the report has not already been written (determined by the existence
of the file specified by @ref{filename}, @ref{write} is called.
optionshead
@table @code

@item compiler, @code{FILENAME}
Like @ref{compiler}, except will not overwrite the value of
@code{compiler} contained in the report object. Hence, passing the
value here is useful for using different @LaTeX{} compilers or just
for passing the value at the last minute.

@item showOutput, @code{BOOLEAN}
Print the compiler output to the screen. Useful for debugging your code as the
@LaTeX{} compiler hangs if there is a problem. Default: the value of
@ref{showOutput}

@item showReport, @code{BOOLEAN}
Open the compiled report (works on Windows and OS X on Matlab). Default:
@code{true}

@end table
@end defmethod

@examplehead

The following code creates a one page report. The first part of the
page contains two graphs displayed across two columns and one
row. The bottom of the page displays a centered table.
@example
%% Create dseries
dsq = dseries(`quarterly.csv');
dsa = dseries(`annual.csv');
dsca = dseries(`annual_control.csv');

%% Report
rep = report();

%% Page 1
rep = rep.addPage(`title', @{`My Page Title', `My Page Subtitle'@}, ...
                  `titleFormat', @{`\large\bfseries', `\large'@});

% Section 1
rep = rep.addSection(`cols', 2);
rep = rep.addGraph(`title', `Graph (1,1)', `showLegend', true, ...
                   `xrange', dates(`2007q1'):dates(`2013q4'), ...
                   `shade', dates(`2012q2'):dates(`2013q4'));
rep = rep.addSeries(`data', dsq@{`SERIES1'@}, `graphLineColor', `blue', ...
                    `graphLineWidth', 1);
rep = rep.addSeries(`data', dsq@{`SERIES2'@}, `graphLineColor', `green', ...
                    `graphLineStyle', '--', `graphLineWidth', 1.5);
rep = rep.addGraph(`title', `Graph (1,2)', `showLegend', true, ...
                   `xrange', dates(`2007q1'):dates(`2013q4'), ...
                   `shade', dates(`2012q2'):dates(`2013q4'));
rep = rep.addSeries(`data', dsq@{`SERIES3'@}, `graphLineColor', `blue', ...
                    `graphLineWidth', 1);
rep = rep.addSeries(`data', dsq@{`SERIES4'@}, `graphLineColor', `green', ...
                    `graphLineStyle', '--', `graphLineWidth', 1.5);

% Section 2
rep = rep.addSection();
rep = rep.addTable(`title', `Table 1', ...
                   `range', dates(`2012Y'):dates(`2014Y'));
shortNames = @{`US', `EU'@};
longNames  = @{`United States', `Euro Area'@};
for i=1:length(shortNames)
    rep = rep.addSeries(`data', dsa@{[`GDP_' shortNames@{i@}]@});
    delta = dsa@{[`GDP_' shortNames@{i@}]@}-dsca@{[`GDP_' shortNames@{i@}]@};
    delta = delta.tex_rename(`$\Delta$');
    rep = rep.addSeries(`data', delta, ...
                        `tableShowMarkers', true, ...
                        `tableAlignRight', true);
end

%% Write & Compile Report
rep.write();
rep.compile();
@end example


@node Examples
@chapter Examples

Dynare comes with a database of example @file{.mod} files, which are
designed to show a broad range of Dynare features, and are taken from
academic papers for most of them. You should have these files in the
@file{examples} subdirectory of your distribution.

Here is a short list of the examples included. For a more complete
description, please refer to the comments inside the files themselves.

@table @file

@item ramst.mod
An elementary real business cycle (RBC) model, simulated in a
deterministic setup.

@item example1.mod
@itemx example2.mod
Two examples of a small RBC model in a stochastic setup, presented in
@cite{Collard (2001)} (see the file @file{guide.pdf} which comes with
Dynare).

@item example3.mod
A small RBC model in a stochastic setup, presented in
@cite{Collard (2001)}. The steady state is solved analytically using the  @code{steady_state_model} block (@pxref{steady_state_model}).

@item fs2000.mod
A cash in advance model, estimated by @cite{Schorfheide (2000)}. The file shows how to use Dynare for estimation.

@item fs2000_nonstationary.mod
The same model than @file{fs2000.mod}, but written in non-stationary
form. Detrending of the equations is done by Dynare.

@item bkk.mod
Multi-country RBC model with time to build, presented in @cite{Backus,
Kehoe and Kydland (1992)}. The file shows how to use Dynare's macro-processor.

@item agtrend.mod
Small open economy RBC model with shocks to the growth trend, presented
in @cite{Aguiar and Gopinath (2004)}.

@item NK_baseline.mod
Baseline New Keynesian Model estimated in @cite{Fernández-Villaverde (2010)}. It demonstrates how to use an explicit steady state file to update parameters and call a numerical solver.

@end table

@node Dynare misc commands
@chapter Dynare misc commands

@anchor{prior_function}
@deffn Command prior_function(@var{OPTIONS}) ;

Executes a user-defined function on parameter draws from the prior
distribution. Dynare returns the results of the computations for all draws in an
@math{ndraws} by @math{n} cell array named @var{oo_.prior_function_results}.

@optionshead

@table @code

@anchor{prior_function_function}
@item function = @var{FUNCTION_NAME}
The function must have the following header @code{output_cell =
FILENAME(xparam1,M_,options_,oo_,estim_params_,bayestopt_,dataset_,dataset_info)},
providing read-only access to all Dynare structures. The only output argument
allowed is a @math{1} by @math{n} cell array, which allows for storing any type of
output/computations. This option is required.

@anchor{prior_function_sampling_draws}
@item sampling_draws = @var{INTEGER}
Number of draws used for sampling. Default: 500.

@end table

@end deffn

@deffn Command posterior_function(@var{OPTIONS}) ;

Same as the @ref{prior_function} command but for the posterior
distribution. Results returned in @var{oo_.posterior_function_results}

@optionshead

@table @code

@item function = @var{FUNCTION_NAME}
@xref{prior_function_function}.

@item sampling_draws = @var{INTEGER}
@xref{prior_function_sampling_draws}.

@end table

@end deffn

@anchor{generate_trace_plots}
@deffn Command generate_trace_plots(@var{CHAIN_NUMBER}) ;

Generates trace plots of the MCMC draws for all estimated parameters and the posterior density in the specified Markov Chain @code{CHAIN_NUMBER}.

@end deffn

@anchor{internals}
@deffn {MATLAB/Octave command} internals @var{FLAG} @var{ROUTINENAME}[.m]|@var{MODFILENAME}

Depending on the value of @var{FLAG}, the @code{internals} command can be used to run unitary tests specific to a Matlab/Octave routine (if available), to display documentation about a Matlab/Octave routine, or to extract some informations about the state of Dynare.

@flagshead

@table @code

@item --test
Performs the unitary test associated to  @var{ROUTINENAME} (if this routine exists and if the matalab/octave @code{m}
file has unitary test sections).
@examplehead
@example
>> internals --test ROUTINENAME
@end example
if @code{routine.m} is  not in the current directory, the  full path has
to be given:
@example
>> internals --test ../matlab/fr/ROUTINENAME
@end example

@item --info
Prints  on screen  the internal  documentation of  @var{ROUTINENAME} (if
this  routine  exists  and  if  this  routine  has  a  texinfo  internal
documentation header). The path to @var{ROUTINENAME} has to be provided,
if the routine is not in the current directory.
@examplehead
@example
>> internals --doc ../matlab/fr/ROUTINENAME
@end example
At this time, will work properly for only a small number of routines. At
the top of the (available)  Matlab/Octave routines a commented block for
the internal documentation  is written in the  GNU texinfo documentation
format.   This   block   is    processed   by   calling   texinfo   from
MATLAB. Consequently, texinfo has to be installed on your machine.

@item --display-mh-history
Displays information about the previously saved MCMC draws generated by a mod file named @var{MODFILENAME}. This file must be in the current directory.
@examplehead
@example
>> internals --display-mh-history MODFILENAME
@end example

@item --load-mh-history
Loads into the Matlab/Octave's workspace informations  about the previously saved MCMC draws generated by a mod file named @var{MODFILENAME}.
@examplehead
@example
>> internals --load-mh-history MODFILENAME
@end example
This will create a structure called @code{mcmc_informations} (in the workspace) with the following fields:
@table @code
@item Nblck
The number of MCMC chains.
@item InitialParameters
A @code{Nblck*n}, where @code{n} is the number of estimated parameters, array of doubles. Initial state of the MCMC.
@item LastParameters
A @code{Nblck*n}, where @code{n} is the number of estimated parameters, array of doubles. Current state of the MCMC.
@item InitialLogPost
A @code{Nblck*1} array of doubles. Initial value of the posterior kernel.
@item LastLogPost
A @code{Nblck*1} array of doubles. Current value of the posterior kernel.
@item InitialSeeds
A @code{1*Nblck} structure array. Initial state of the random number generator.
@item LastSeeds
A @code{1*Nblck} structure array. Current  state of the random number generator.
@item AcceptanceRatio
A @code{1*Nblck} array of doubles. Current acceptance ratios.
@end table

@end table

@end deffn


@deffn {MATLAB/Octave command line} prior [options[, ...]];

Prints various informations about the prior distribution depending on
the options. If no options are provided, the command returns the list
of available options. Following options are available:

@table @code

@item table
Prints a table describing the marginal prior distributions (mean, mode,
std., lower and upper bounds, HPD interval).

@item moments
Computes and displays first and second order moments of the endogenous
variables at the prior mode (considering the linearized version of the
model).

@item optimize
Optimizes the prior density (starting from a random initial guess). The
parameters such that the steady state does not exist or does not satisfy
the Blanchard and Kahn conditions are penalized, as they would be when
maximizing the posterior density. If a significant proportion of the
prior mass is defined over such regions, the optimization algorithm may
fail to converge to the true solution (the prior mode). 

@item simulate
Computes the effective prior mass using a Monte-Carlo. Ideally the
effective prior mass should be equal to 1, otherwise problems may arise
when maximising the posterior density and model comparison based
on marginal densities may be unfair. When comparing models, say @math{A}
and @math{B}, the marginal densities, @math{m_A} and @math{m_B}, should
be corrected for the estimated effective prior mass @math{p_A\neq p_B
\leq 1} so that the prior mass of the compared models are identical.

@item plot
Plots the marginal prior density.

@end table

@end deffn

@node Bibliography
@chapter Bibliography

@itemize

@item
Abramowitz, Milton and Irene A. Stegun (1964): ``Handbook of Mathematical Functions'', Courier Dover Publications

@item
Adjemian, Stéphane, Matthieu Darracq Parriès and Stéphane Moyen (2008): ``Towards a monetary policy evaluation framework'',
@i{European Central Bank Working Paper}, 942

@item
Aguiar, Mark and Gopinath, Gita (2004): ``Emerging Market Business
Cycles: The Cycle is the Trend,'' @i{NBER Working Paper}, 10734

@item
Amisano, Gianni and Tristani, Oreste (2010): ``Euro area inflation persistence in an estimated nonlinear DSGE model'', @i{Journal of Economic Dynamics and Control}, 34(10), 1837--1858

@item
Andreasen, Martin M., Jesús Fernández-Villaverde, and Juan Rubio-Ramírez (2013): ``The Pruned State-Space System for Non-Linear DSGE Models: Theory and Empirical Applications,'' @i{NBER Working Paper}, 18983

@item
Andrews, Donald W.K (1991): ``Heteroskedasticity and autocorrelation consistent covariance matrix estimation'', 
@i{Econometrica}, 59(3), 817--858

@item
Backus, David K., Patrick J. Kehoe, and Finn E. Kydland (1992):
``International Real Business Cycles,'' @i{Journal of Political
Economy}, 100(4), 745--775

@item
Baxter, Marianne and Robert G. King (1999):
``Measuring Business Cycles: Approximate Band-pass Filters for Economic Time Series,'' 
@i{Review of Economics and Statistics}, 81(4), 575--593

@item
Boucekkine, Raouf (1995): ``An alternative methodology for solving
nonlinear forward-looking models,'' @i{Journal of Economic Dynamics
and Control}, 19, 711--734

@item
Brooks,  Stephen P.,  and Andrew  Gelman (1998):  ``General methods  for
monitoring  convergence   of  iterative  simulations,''   @i{Journal  of
computational and graphical statistics}, 7, pp. 434--455

@item
Cardoso, Margarida F., R. L. Salcedo and S. Feyo de Azevedo (1996): ``The simplex simulated annealing approach to continuous non-linear optimization,'' @i{Computers chem. Engng}, 20(9), 1065-1080

@item
Chib, Siddhartha and Srikanth Ramamurthy (2010):
``Tailored randomized block MCMC methods with application to DSGE models,'' 
@i{Journal of Econometrics}, 155, 19--38

@item
Christiano, Lawrence J., Mathias Trabandt and Karl Walentin (2011):
``Introducing financial frictions and unemployment into a small open
economy model,'' @i{Journal of Economic Dynamics and Control}, 35(12),
1999--2041

@item
Christoffel, Kai, G@"unter Coenen and Anders Warne (2010):
``Forecasting with DSGE models,'' @i{ECB Working Paper Series}, 1185

@item
Collard, Fabrice (2001): ``Stochastic simulations with Dynare: A practical guide''

@item
Collard, Fabrice and Michel Juillard (2001a): ``Accuracy of stochastic
perturbation methods: The case of asset pricing models,'' @i{Journal
of Economic Dynamics and Control}, 25, 979--999

@item
Collard, Fabrice and Michel Juillard (2001b): ``A Higher-Order Taylor
Expansion Approach to Simulation of Stochastic Forward-Looking Models
with an Application to a Non-Linear Phillips Curve,'' @i{Computational
Economics}, 17, 125--139

@item
Corona, Angelo,  M. Marchesi, Claudio Martini, and Sandro Ridella (1987):
``Minimizing multimodal functions of continuous variables with the ``simulated annealing'' algorithm'',
@i{ACM Transactions on Mathematical Software}, 13(3), 262--280

@item
Del Negro, Marco and Franck Schorfheide (2004): ``Priors from General Equilibrium Models for VARs'',
@i{International Economic Review}, 45(2), 643--673

@item
Dennis, Richard (2007): ``Optimal Policy In Rational Expectations
Models: New Solution Algorithms,'' @i{Macroeconomic Dynamics}, 11(1),
31--55

@item
Durbin, J. and S. J. Koopman (2012), @i{Time Series Analysis by State
Space Methods}, Second Revised Edition, Oxford University Press

@item
Fair, Ray and John Taylor (1983): ``Solution and Maximum Likelihood
Estimation of Dynamic Nonlinear Rational Expectation Models,''
@i{Econometrica}, 51, 1169--1185

@item
Fernández-Villaverde, Jesús and Juan Rubio-Ramírez (2004): ``Comparing
Dynamic Equilibrium Economies to Data: A Bayesian Approach,''
@i{Journal of Econometrics}, 123, 153--187

@item
Fernández-Villaverde, Jesús and Juan Rubio-Ramírez (2005): ``Estimating
Dynamic Equilibrium Economies: Linear versus Nonlinear Likelihood,''
@i{Journal of Applied Econometrics}, 20, 891--910

@item
Fernández-Villaverde, Jesús (2010): ``The econometrics of DSGE models,''
@i{SERIEs}, 1, 3--49

@item
Ferris, Michael C. and Todd S. Munson (1999): ``Interfaces to PATH 3.0: Design, Implementation and Usage'',
@i{Computational Optimization and Applications}, 12(1), 207--227

@item
Geweke, John (1992): ``Evaluating the accuracy of sampling-based approaches
to the calculation of posterior moments,'' in J.O. Berger, J.M. Bernardo,
A.P. Dawid, and A.F.M. Smith (eds.) Proceedings of the Fourth Valencia
International Meeting on Bayesian Statistics, pp. 169--194, Oxford University Press

@item
Geweke, John (1999): ``Using simulation methods for Bayesian econometric models:
Inference, development and communication,'' @i{Econometric Reviews}, 18(1), 1--73

@item
Giordani, Paolo, Michael Pitt, and Robert Kohn (2011): ``Bayesian Inference for Time Series State Space Models''
in: @i{The Oxford Handbook of Bayesian Econometrics}, ed. by John Geweke, Gary Koop, and Herman van Dijk,
Oxford University Press, 61--124

@item 
Goffe, William L., Gary D. Ferrier, and John Rogers (1994): ``Global Optimization 
of Statistical Functions with Simulated Annealing,'' @i{Journal of Econometrics}, 60(1/2), 
65--100

@item
Hansen, Nikolaus and Stefan Kern (2004): ``Evaluating the CMA Evolution Strategy 
on Multimodal Test Functions''. In: @i{Eighth International Conference on Parallel 
Problem Solving from Nature PPSN VIII, Proceedings}, Berlin: Springer, 282--291 

@item
Harvey, Andrew C. and Garry D.A. Phillips (1979): ``Maximum likelihood estimation of 
regression models with autoregressive-moving average disturbances,''
@i{Biometrika}, 66(1), 49--58

@item
Herbst, Edward (2015):
``Using the ``Chandrasekhar Recursions'' for Likelihood Evaluation of DSGE
Models,'' @i{Computational Economics}, 45(4), 693--705.

@item
Ireland, Peter (2004): ``A Method for Taking Models to the Data,''
@i{Journal of Economic Dynamics and Control}, 28, 1205--26

@item
Iskrev, Nikolay (2010): ``Local identification in DSGE models,''
@i{Journal of Monetary Economics}, 57(2), 189--202

@item
Judd, Kenneth (1996): ``Approximation, Perturbation, and Projection
Methods in Economic Analysis'', in @i{Handbook of Computational
Economics}, ed. by Hans Amman, David Kendrick, and John Rust, North
Holland Press, 511--585

@item
Juillard, Michel (1996): ``Dynare: A program for the resolution and
simulation of dynamic models with forward variables through the use of
a relaxation algorithm,'' CEPREMAP, @i{Couverture Orange}, 9602

@item
Kim, Jinill and Sunghyun Kim (2003): ``Spurious welfare reversals in 
international business cycle models,'' @i{Journal of International
Economics}, 60, 471--500

@item
Kanzow, Christian and Stefania Petra (2004): ``On a semismooth least squares formulation of
complementarity problems with gap reduction,'' @i{Optimization Methods and Software},19 507--525

@item
Kim, Jinill, Sunghyun Kim, Ernst Schaumburg, and Christopher A. Sims
(2008): ``Calculating and using second-order accurate solutions of
discrete time dynamic equilibrium models,'' @i{Journal of Economic
Dynamics and Control}, 32(11), 3397--3414

@item
Koop, Gary (2003), @i{Bayesian Econometrics}, John Wiley & Sons

@item
Koopman, S. J. and J. Durbin (2000): ``Fast Filtering and Smoothing for 
Multivariate State Space Models,'' @i{Journal of Time
Series Analysis}, 21(3), 281--296

@item
Koopman, S. J. and J. Durbin (2003): ``Filtering and Smoothing of
State Vector for Diffuse State Space Models,'' @i{Journal of Time
Series Analysis}, 24(1), 85--98

@item 
Kuntsevich, Alexei V. and  Franz Kappel (1997): ``SolvOpt - The solver 
for local nonlinear optimization problems (version 1.1, Matlab, C, FORTRAN)'', 
University of Graz, Graz, Austria

@item
Laffargue, Jean-Pierre (1990): ``Résolution d'un modèle
macroéconomique avec anticipations rationnelles'', @i{Annales
d'Économie et Statistique}, 17, 97--119

@item
Liu, Jane and Mike West (2001): ``Combined parameter and state estimation in simulation-based filtering'', in @i{Sequential Monte Carlo Methods in Practice}, Eds. Doucet, Freitas and Gordon, Springer Verlag

@item
Lubik, Thomas and Frank Schorfheide (2007): ``Do Central Banks Respond
to Exchange Rate Movements? A Structural Investigation,'' @i{Journal
of Monetary Economics}, 54(4), 1069--1087

@item
Mancini-Griffoli, Tommaso (2007): ``Dynare User Guide: An introduction
to the solution and estimation of DSGE models''

@item
Murray, Lawrence M., Emlyn M. Jones and John Parslow (2013): ``On Disturbance State-Space Models and the Particle Marginal
Metropolis-Hastings Sampler'', @i{SIAM/ASA Journal on Uncertainty Quantification}, 1, 494–521.

@item
Pearlman, Joseph, David Currie, and Paul Levine (1986): ``Rational
expectations models with partial information,'' @i{Economic
Modelling}, 3(2), 90--105

@item
Planas, Christophe, Marco Ratto and Alessandro Rossi (2015): ``Slice sampling in Bayesian estimation
of DSGE models''

@item
Pfeifer, Johannes (2013): ``A Guide to Specifying Observation Equations for the Estimation of DSGE Models''

@item
Pfeifer, Johannes (2014): ``An Introduction to Graphs in Dynare''

@item
Rabanal, Pau and Juan Rubio-Ramirez (2003): ``Comparing New Keynesian
Models of the Business Cycle: A Bayesian Approach,'' Federal Reserve
of Atlanta, @i{Working Paper Series}, 2003-30.

@item
Raftery, Adrien E. and Steven Lewis (1992): ``How many iterations in the Gibbs sampler?,''  in @i{Bayesian Statistics, Vol. 4}, 
ed. J.O. Berger, J.M. Bernardo, A.P. Dawid, and A.F.M. Smith, Clarendon Press: Oxford, pp. 763-773.   

@item
Ratto, Marco (2008): ``Analysing DSGE models with global sensitivity
analysis'', @i{Computational Economics}, 31, 115--139

@item
Schorfheide, Frank (2000): ``Loss Function-based evaluation of DSGE
models,'' @i{Journal of Applied Econometrics}, 15(6), 645--670

@item
Schmitt-Grohé, Stephanie and Martin Uríbe (2004): ``Solving Dynamic
General Equilibrium Models Using a Second-Order Approximation to the
Policy Function,'' @i{Journal of Economic Dynamics and Control},
28(4), 755--775

@item
Schnabel, Robert B. and Elizabeth Eskow (1990): ``A new modified Cholesky algorithm,'' 
@i{SIAM Journal of Scientific and Statistical Computing}, 11, 1136--1158

@item
Sims, Christopher A., Daniel F. Waggoner and Tao Zha (2008): ``Methods for
inference in large multiple-equation Markov-switching models,''
@i{Journal of Econometrics}, 146, 255--274

@item
Skoeld, Martin and Gareth O. Roberts (2003): ``Density Estimation for the
Metropolis-Hastings Algorithm,'' @i{Scandinavian Journal of Statistics}, 30, 699--718

@item
Smets, Frank and Rafael Wouters (2003): ``An Estimated Dynamic
Stochastic General Equilibrium Model of the Euro Area,'' @i{Journal of
the European Economic Association}, 1(5), 1123--1175

@item
Stock, James H. and Mark W. Watson (1999). ``Forecasting Inflation,'', @i{Journal of Monetary
Economics}, 44(2), 293--335.

@item
Uhlig, Harald (2001): ``A Toolkit for Analysing Nonlinear Dynamic Stochastic Models Easily,''
in @i{Computational Methods for the Study of Dynamic
Economies}, Eds. Ramon Marimon and Andrew Scott, Oxford University Press, 30--61

@item
Villemot, Sébastien (2011): ``Solving rational expectations models at
first order: what Dynare does,'' @i{Dynare Working Papers}, 2,
CEPREMAP


@end itemize

@node Command and Function Index
@unnumbered Command and Function Index

@printindex fn

@node Variable Index
@unnumbered Variable Index

@printindex vr

@bye
