You are on page 1of 27

Matlab Toolkit for Simulating

Dynamic Stochastic General Equilibrium Models


Haruki Seitani*
August 2013

Abstract
Behavior of a dynamic stochastic general equilibrium model can be best
understood by working out an approximated solution. A set of Matlab codes is
designed for 1) log-linearizing equilibrium conditions around a steady-state, 2) solving
the system of expectational difference equations by applying eigenvalue decomposition,
and 3) simulating the model by calculating impulse-response functions and generating
artificial time series data. Taking a typical real business cycle model as an example, it is
shown how a calibrated model provides an insight into refinement of business cycle
theory.

Economic and Social Research Institute, Cabinet Office, Government of Japan. Opinions
expressed here are the authors alone and do not represent the views of the organization.

1. Introduction
As Campbell (1994) advocates, behavior of a dynamic stochastic general
equilibrium (DSGE) model can be best understood by working out an approximated
solution. In the DSGE analysis, it has become a common exercise to log-linearly
approximate equilibrium conditions derived from dynamic optimization of economic
agents around a deterministic steady state. Such approximated equilibrium conditions
typically take a form of a system of first-order expectational difference equations.
Solution to the approximated system governs development of economic states and
economic agents decisions functional on those states. Behavior of a DSGE model can
then be investigated by simulating the approximated model with artificially generated
data.
This Matlab toolkit linearizes equilibrium conditions around a steady state and
finds a set of policy functions and laws of motion of state variables as a solution to a
system of first-order expectational difference equations. Once policy functions are
obtained, one can simulate the model by giving it exogenous stochastic shocks to state
variables. The toolkit calculates response of the model economy to such a shock and
compares variation and correlation among aggregate economic variables.
A typical real business cycle (RBC) model is taken as an example of DSGE
models here not because it provides a better explanation of actual economic activities
but because it has been a work-force of development of almost all DSGE approach to
business-cycle analyses.
Many authors have already provided this sort of guidance and toolkits and the
present deliverable is entirely based on the contributions of the predecessors1. Thus this
paper does neither offer any original insights nor provide complete treatment of
alternative solution techniques. The purpose of it is to serve as a quick reference that
relates economic theory, guide for mathematical technique, its application, and literature
in a succinct manner.

2. Real Business Cycle Model


2.1. Setup of the Model
The model is based on a perfectly competitive economy populated by identical
infinitely-lived households and firms, so that their economic choices reduce to decisions
made by a single representative agent.
1

See Hartley, Hoover, and Salyer (1998), Uhlig (1999), Kato (2002). Dejong and Dave (2011)
compare various alternative solution techniques.

-1-

Households own and lease capital stock, k t , and sell labor (measured by hours
worked), lt , to firms respectively at the rental rate of capital and real wage rate. They
allocate their income into purchases of consumption goods, ct , and capital goods, it ,
and their time into labor and leisure so that their lifetime expected utility is maximized.
Their preferences are represented by an identical utility function as follows:

E 0 t U ct , 1 lt E 0 t ln ct ln 1 lt , 0 1 . (1)
t 0

t 0

Capital stock owned by households depreciates at a constant rate, .


Firms have an access to a constant-returns-to-scale production technology that is
subject to random technology shocks; specifically the production technology takes the
Cobb-Douglas type functional form and the technology shocks follow a first-order
autoregressive process (AR(1)) with a log-normally distributed disturbance.
yt zt f k t , lt zt k t lt1 ,
zt 1 zt exp t 1 ,

t N 0 , z .

(2)
(3)

2.2. Deriving the Equilibrium Conditions


Since the economic structure above satisfies complete markets, price-taking
behavior, convexity of a production set, and convexity and local nonsatiation of
preferences, the fundamental theorems of welfare economics is applicable; a Pareto
optimal allocation coincides with a competitive equilibrium.2

The Pareto optimum is the solution to the following social-planners problem:

Max E0 t ln ct ln 1 lt ,
t 0

subject to ct it zt k t lt1 yt ,
and k t 1 k t 1 it .
This infinite horizon problem can be solved by exploiting its recursive structure; the
2

See Cooley and Prescott (1994).

-2-

social planners problem is recast as the following dynamic programming:


V k t , zt Max ln ct ln 1 lt E t V kt 1 , zt 1 ,
ct , kt 1 , lt

subject to ct kt 1 zt kt lt1 kt 1 ,
where V denotes the optimized value function, or in this context the indirect utility
function of the household.
A solution to this problem has to satisfy the necessary conditions and aggregate
resource constraint below.
zt 1 kt lt

.
ct
1 lt

(4)

1
Et
zt 1 k t11 lt11 1 .
ct
ct 1

(5)

kt 1 zt k t lt1 kt 1 ct .

(6)

The first equation that relates the current variables to each other is called
intratemporal optimality condition. It implies that the marginal rate of substitution
between labor and consumption has to equal the marginal product of labor. The second
equation that connects the current and one-period ahead variables is called
intertemporal optimality condition. The left-hand side of the equation represents the
marginal utility loss of investing in capital while the right-hand side represents the
expected marginal utility gain from it; these costs and benefits have to be equalized at
the optimum. These intra- and intertemporal optimality conditions, together with the
resource constraint and the dynamic low of motion for the technology shock, govern the
equilibrium behavior of the model economy.

3. Approximation and Solution


Since the solution to the social planners problem exists and is unique (Prescott
1986) but is NOT analytical, approximation helps us make the model operational. One
of the widely exercised methods is to take a log-linear approximation of the equilibrium
-3-

conditions around the steady-state values of consumption, capital, labor, and


technology3.
3.1. Steady State of the Economy

A steady state equilibrium for the model economy is one in which the
technology shock is assumed to be constant: zt 1 , t , and the values of capital, labor,
and consumption are constant: k t k , lt l , c c , t . The steady-state values of
capital, labor, and consumption are solution to the following equations obtained by
imposing these conditions on the necessary conditions for the optimality.

1 k
c

y
1 k 1 l 1 .

k
k k l 1 c y c .
1

(7)
(8)
(9)

3.2. Log-Linear Approximation of the Equilibrium Conditions

Recall that the first-order Taylor series expansion of a function f x around a


point x takes the following form.
f x f x f x x x .

Taking natural logarithmic of x and noting that x exp ln x , natural logarithmic of


f x can be approximated as follows.

ln f x ln f x

f x x
ln x ln x ,
f x

f x
f x x x

ln .
ln
f x
x
f x

(10)

Suppose that x deviates from x by only a small number, . Then,


3

Log-linearization can be justified as a good approximation as far as


the stochastic behavior of the model does not push the economy too far from the steady-state
behavior. It is also possible to approximate the model at higher order; for example, Schmitt-Groh
and Uribe (2004) analyze a solution to second-order approximated conditions.

-4-

x
x

ln ln
x .
ln 1 ~
x
x
x x
Thus ln x

can be interpreted as percentage deviation of x from x , ~x . Note


also that f x x f x is the elasticity of f x with respect to x . Thus equation
(10) represents percentage deviation of f x from f x due to the deviation of x .
x

This can easily be generalized to multivariate cases:


f x1 , , xn

ln
f x1 , , xn

i 1

x
xi
f x1 , , xn
ln i

f x1 , , xn xi
xi

(11)

Applying this technique to the equilibrium conditions from (4) to (6) and the process of
technology shocks, (3), delivers the following log-linearly approximated counterparts.
1) Intratemporal Optimality Condition
~
~
~
lt ~zt k t lt c~t .

(12)

2) Intertemporal Optimality Condition


c~t Et c~t 1

k 1 l 1
k 1l 1 1

Et ~zt 1

1k 1 l 1
~
1 k 1 l 1
~
E
k

E t lt 1
t t 1
1 1
1 1
k l 1
k l 1

(13)

~
~
y
E t c~t 1 E t ~zt 1 1 Et k t 1 1 E t lt 1 .
k
The last expression uses the steady-state equilibrium condition:

k 1 l 1

y
, and
k

-5-

k 1 l 1 1

3) Aggregate Resource Constraint


~
E t k t 1

k l 1
k l 1
~
~z
kt
t
1
1
k l k 1 c
k l k 1 c

1 k l 1
l 1 k 1 c

~
lt

k l

~
~ c
y
~zt k t 1 lt c~t
k
k

c
c~t
k 1 c

(14)

The final line of the equation results from the steady-state relationships:

k l 1 y , and
k l 1 k 1 c k .
4) Technology Shock Process
~z ~z
t 1
t
t 1 .
Taking expectations of both sides of the last equation,

Et ~
zt 1 ~zt .

Let Yt c~t

~ ~
lt kt

(15)

~z . Then the equilibrium conditions can be written as a system


t

of first-order expectational difference equations:


A Yt B Et Yt 1 ,

where

-6-

(16)

1
1
A c

k
0

1
0
1 y
k
0

, B

1
0
y
k

y
k
0

1 y

1 y

k
0
0

k
1
0

0
0

k
0
1

Premultiplying both sides of equation (16) by A 1 yields:

Yt A 1 B Et Yt1 .

(17)

3.3. Solving the Approximated Model


The trouble with solving the system of equations is that terms related to other
variables appear one another in each individual equation. It would be much easier to
solve if only we were able to transform these equations so that they are decoupled
each other.
This indeed possible by applying eigenvalue decomposition to A 1 B .
Yt A 1 B E t Yt 1 Q Q 1 E t Yt 1

(18)

where is a diagonal matrix whose diagonal entries are eigenvalue of A 1 B , and


. Then,
Q is a matrix whose columns are the associated eigenvectors4. Let Q 1 Y Y
t

E Y

Y
t
t
t 1

c~t
~
lt
~
kt
~
zt

1 0

0 2

0 0

0 0

0
0

3
0

0
0

Et c~t 1
~
Et l t 1
~
Et kt 1
E ~z
t

t 1

Thus the transformation successfully decouples the equations.


4

This technique of changing variables is discussed in Chapter 23 of Simon and Blume (1994).

-7-

Notice that the system of equations generally involves both control (or jump)
and state (or predetermined) variables. In this case, there are two control variables, ct
and lt , and two state variables, kt and zt . Suppose that in a general case Yt
consists of n control variables, X t , and m state variables, S t :
X
Yt t .
St

Let Q ij1 and i be partitioned matrices of Q 1 and whose numbers of rows and
columns are respectively conformable to those of X and S .
1
Q11
1
Q 21

1
X t X
Q12

1
Q 22 S t O

O
S


X
t X

St O


X
O
t 1
E

S t S t 1

1
Q11
1
Q 21

Q12
Et
1
Q 22

X t 1
S .
t 1

(19)

Notice that equation (19) implies:


1
X
E t t T X

O
S t T


1
S


X
t
.
S
t

Existence and uniqueness of stable rational expectations solutions require that all
eigenvalues contained in S have to be greater than unity so that
lim S1 O ,
T

while those contained in X have to be smaller than unity (Blanchard and Kahn
1980)..

-8-

(20)

1) Solution to Control Variables


It directly follows from equation (19) that:

Et X
t T X

Xt .

Provided that the Blanchard-Kahn condition is satisfied, since all eigenvalues in X is

not to explode that:


greater than one, it has to be true in order for E X
t

t T

O Q 1 X Q 1 S O .
X
t
11
t
12 t

This leads to the solution to control variables:

1
X t Q 11

1
Q 12
S t PX S t .

(21)

2) Solution to State Variables


It also follows from equation (19) that:

E t S t 1 S1 S t

1
1
Q 211 Et X t 1 Q 22
E t S t 1 S1 Q 21
X t 1 Q 221 S t 1

Substituting (21) into above equation,

1
22

Q 211 PX E t S t 1 S1 Q 221 Q 211 PX S t

Then the solution to state variables is given by:

E t S t 1 Q 221 Q 211 PX

S1 Q 221 Q 211 PX S t PS S t .

3.4. Matlab Codes


-9-

(22)

This subsection explains some key lines of Matlab codes written in the toolkit.
The complete lines are provided in Appendix. The codes draw a direct line with those in
Kato (2002).
3.4.1. Linearization Part
In Matlab, linearization of equilibrium conditions is implemented by taking
Jacobian of the system of equations from (3) to (6) and evaluating it at the steady-state
values:
%---- Differentiation ----%
J = jacobian ( eqcon,xx ) ;
%---- Evaluation at the Steady State ----%
cc = CS ;
ca = CS ;
lc = LS ;
la = LS ;
kc = KS ;
ka = KS ;
zc = Z ;
za = Z ;
coef = eval ( J ) ;

3.4.2. Solution Part


The Matlab

function

named

bksolve

returns

PX , PS , n , m

by

implementing the eigenvalue decomposition:


[ Q, L ] = eig (inv(A)*B) ;

Then the eigenvalue matrix L is vectorized and sorted in ascending order; columns of
the matrix Q, eigenvectors associated with eigenvalues, are also rearranged in line with
the same order:
L = diag ( L ) ;
[ L, order ] = sort ( diag ( L ), ascending ) ;

- 10 -

Q = Q ( : , order) ;

The following lines count the number of control and state variables in the system, n and
m.
n = 0;
for i = 1:length ( L )
if abs ( L ( i ) ) < 1.0000
n = n + 1;
end
end
m = length ( L )

- n;

Then the inverse matrix of Q is partitioned into four blocks while L is divided into
stable and unstable roots.
%--- Partition Matrices ---%
QI11 = QI(1:n, 1:n);
QI21 = QI(n+1:m+n, 1:n);
QI12 = QI(1:n, n+1:m+n);
QI22 = QI(n+1:m+n, n+1:m+n);
%--- Extracting Stable Roots ---%
L1 = L ( 1:n, : ) ;
L2 = L ( n+1:m+n, : ) ;
LS = diag ( L2 ) ;

The rest of the code calculates PX and PS according to formulae (21) and (22) (see
Appendix).

4. Simulation with a Calibrated Model


Once one obtains the approximated solution to a model, she can exercise a
quantitative analysis by assigning numerical values to parameters. The strategy for
finding numerical parameter values is called calibration.
- 11 -

By imposing restriction on the mapping between theory and data, calibration


enables us to measure the distance between an artificial model economy and its actual
counterpart in that it identify in which dimensions the former succeeds or fails in
matching with the latter. Results of the exercise serve as guidance about refinements of
the theoretical model or improvements in the measurements of the actual economy
(Cooley 1997).5
4.1. Parametarization
Cooley (1997) provides some rules for good calibration. According to them,
it is important to set parameter values so that the behavior of the model economy
matches features of the measured data such that one cannot abstract from. In the
context of the RBC model here, parameter values should be chosen so that the Kaldors
stylized facts of economic growth are mimicked, for the underlying structure of the
model is the neoclassical growth framework. Also, some information about individual
choices over time such as total hours worked could be useful for setting parameter
values related to preference specifications.
The parameter values employed here are:

0.99 ,

2.0 , 0.36 , 0.025 , 0.95 , z 0.007 .

These parameter values imply the following steady-state values, which are broadly
consistent with the post-war U.S. experience:

c 0.83 , l 0.30 , k 10.9 , y 1.11

4.2. Impulse-Response Function


Then one can investigate propagation and amplification mechanisms of the model
economy by looking at impulse-response functions. Figure 1 displays the behavior of
output, consumption, investment, hours worked, and labor productivity in response to a
unitary shock to technology. As can be seen in the figure, consumption shows the
smallest response among them. This is due to the optimizing behavior of households
who have risk-averse preferences and thus want to smooth their consumption. The other
side of the same coin is the response of investment, which is the largest among all
5

This is an advantage of calibration exercise over classical statistical inference. Since the
distribution theory for a standard statistical test of a model is derived under the null hypothesis, it is
unlikely to provide much information about how to proceed if the test rejects the model.

- 12 -

variables. Turning eyes to behavior of labor, one can see that hours worked show a
positive response to the technology shock but it is not greater than that of output. This is
an outcome of interaction between income- and substitution effects. While the former
effect induces the household to reduce labor supply, the latter gives incentive for
working more. Since the latter dominates the former, the net effect is positive.
While these results are intuitively comprehensible, it has been pointed out that the
impulse-response functions of the RBC model have properties inconsistent with their
empirical counterparts in some dimensions. For example, the calibrated model
predicts positive comovement among output, hours worked, and labor productivity in
response to a positive technology shock. However, Gal (1999) points out that an
empirical impulse-response function estimated by a vector autoregression (VAR) shows
a negative response of hours-worked. In addition, while Cogley and Nason (1995)
report that a trend reverting component of U.S. output has a hump-shaped
moving-average representation, the theoretical impulse-response of output does not
show any such a property; it peaks at the first period in which the shock hits the
economy.

Figure 1
Impulse Response to a Unitary Technology Shock
4.5

Output
Consumption
Investment
Hours-worked
Labor Productivity

% Deviation from Steady State

4
3.5
3
2.5
2
1.5
1
0.5
0
0

10

15
Horizon

- 13 -

20

4.3. Simulated Second Moments


Another common simulation exercise is second moment comparison between
artificial data and their actual counterparts. Figure 2 shows an artificial time paths for
consumption, output, and investment, which are detrended by the Hodrick-Prescott filter.
It confirms that investment fluctuates more volatilely than output while consumption is
smoother than output, as is also true in actual data.
But at the same time, a careful look at precise statistics sheds lights on some
defects about the model. Table 1 reports the standard deviations of simulated series of
output, consumption, investment, hours worked, and labor productivity, and correlations
among them, comparing with actual data. It should be noted that 1) the calibrated model
predict considerably less volatile output than actually observed, 2) the predicted hours
worked is also less volatile than actual, and 3) it generates a strong comovement
between hours-worked and labor productivity, which has not been observed in the U.S.
experience (Hansen and Wright 1992) .
These failures mainly results from the fact that the model economy relies solely
on a single technology shock to generate fluctuation; not only the driving force of
business cycle is underestimated but also the behavior of the labor market is too much
simplified. That is, wage (=productivity) and hours worked in the model fluctuate in
response to shifts in labor demand only, which is triggered by technology shocks. A
strong positive correlation between them represents a stable upward sloping labor
supply curve traced out by a labor demand curve shifting over time. This calibration
exercise suggests that the model should take account of other impulse factors which
have multifaceted influence on a labor market. Hansen and Wright (1992) introduce a
shock to home production technology and stochastic government expenditure as a
demand shock. They both affect the households choice on participation in labor market
so that labor supply curve shifts. Hansen and Wright demonstrate that the correlation
between hours and productivity is mitigated under the environment in which both labor
supply and demand are shifting incessantly.

- 14 -

Figure 2
Simulated Time Series Data

0.25

Output
Consumption
Investment

% Deviation from Steady State

0.2
0.15
0.1
0.05
0
-0.05
-0.1
-0.15

50

100

150

Time Period

Table 1

Second Moments of Simulated and Actual US Data

Standard Error

Simulated
Actual

Output
Consumption
y
c / y
0.0135
0.31
0.0192
0.45

Investment
i / y
3.12
2.78

Hours
Productivity
l / y
w / y
0.51
0.50
0.78-0.96
0.45-0.57

Investment

Hours

Correlation with Output


Output
Simulated
Actual

1.00
1.00

Consumption
0.90
0.71

0.99
0.73

Productivity

0.98
0.82-0.90

0.98
0.31-0.63

Standard Error and Correlation between Hours-worked and Labor Productivity


Hours
Correlation
l / w
Simulated
1.02
0.92
Actual
1.37-2.15
-0.14-0.07
* Simulated moments are the sample means of statistics computed for 300 times simulations with 150 periods.
* Actual data are reported in Hansen and Wright (1992). Sample period is 1947:1-1991:3. Statistics related to hours
and productivity take different figures depending on which of two sources of data (household survey or
establishment survey) is used.

- 15 -

5. Summary
A DSGE framework provides a foundation for a logically coherent analysis on
how stochastic shocks are amplified and propagated through optimizing behavior of
economic agents. Since equilibrium conditions in a DSGE model generally take
non-linear forms, approximation would be helpful for making them easy to handle.
A common exercise is to log-linearly approximate intra- and intertemporal
optimal conditions around a steady state. A resulting approximated version of the model
takes a form of a system of first-order expectational difference equations, which can be
solved relying on eigenvalue decomposition.
This paper illustrated how the technique works by taking a typical RBC model for
an instance. Calibration of the model reveals that the RBC theory succeeds in
explaining some features of an actual economy but fails in other important dimensions
such as behavior of the labor market. The results of the quantitative exercise points to a
direction in which the theory should proceed in order to reach better understanding of
business cycle phenomena.

- 16 -

Reference
Blanchard, Oliver J., and Charles M. Kahn. The Solution of Linear Difference Models
under Rational Expectations. Econometrica, Vol. 48, No. 5, 1980, 1305-1311.
Campbell, John Y. Inspecting the Mechanism: An Analytical Approach to the
Stochastic Growth Model. Journal of Monetary Economics, Vol. 33, Issue 3,
1994, 463-506.
Cogley, Timothy, and James M. Nason. Output Dynamics in Real-Business-Cycle
Models. American Economic Review, Vol. 85, No. 3, 1995, 492-511.
Cooley, Tomas F. Calibrated Models. Oxford Review of Economic Policy, Vol. 13,
Issue 3, 1997, 55-69.
_________., and Edward C. Prescott. Economic Growth and Business Cycles. Tomas
F. Cooley ed., Frontiers of Business Cycle Research, Princeton University Press,
Princeton, New Jersey, 1994, 1-38.
Dejong, David N., and Chetan Dave. Structural Macroeconometrics: second edition,
Princeton University Press, Princeton, New Jersey, 2011.
Gal, Jordi. Technology, Employment, and the Business Cycle: Do Technology Shocks
Explain Aggregate Fluctuations? American Economic Review, Vol. 89, No. 1,
1999, 249-271.
Hansen, Gary D., and Randall Wright. The Labor Market in Real Business Cycle
Theory. Federal Reserve Bank of Minneapolis Quarterly Review, Vol. 16, No. 2,
1992, 2-12.
Hartley, James E., Kevin D. Hoover, and Kevin D. Salyer. A Users Guide to Solving
Real Business Cycle Models. Real Business Cycles, A Reader, Routledge,
London and New York, 1998, 43-54.
Kato, Ryo. A User Guide for Matlab Code for An RBC Model Solution and
Simulation. mimeo, 2002.
Schmitt-Groh, Stephanie and Martin Uribe. Solving Dynamic General Equilibrium
Models Using a Second-Order Approximation to the Policy Function. Journal of
Economic Dynamics and Control, Vol. 28, Issue 4, 2004, 755-775.
Prescott, Edward C. Theory Ahead of Business Cycle Measurement.
Carnegie-Rochester Conference Series on Public Policy, Vol. 25, autumn, 1986,
11-44.
Simon, Carl P., and Lawrence Blume. Mathematics for Economists. W. W. Norton &
Company, London and New York, 1994.
Uhlig, Harrold. A Toolkit for Analysing Non-linear Dynamic Stochastic Models
- 17 -

Easily. R. Marimon and A. Scott eds. Computational Methods for the Study of
Dynamic Economies, Oxford and New York, Oxford University Press, 1999,
30-61.

- 18 -

Appendix: Matlab Code for Simulating a DSGE Model


A-1: Main Program modelsim.m
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Basic Real Business Cycle Model
%%
%%
Matlab Code Written by Haruki Seitani
%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
clear all
%==================================================%
%
Initialization: Model Settings
%
%==================================================%
%--- Deep Parmeter Values ---%
alpha
= 0.36 ; % Capital Income Share
beta
= 0.99; % Subjective Discount rate
delta
= 0.025; % Capital Depreciation Rate
Psi
= 2.0 ; % Marginal Disutility of Labor
Z
= 1.0 ; % Mean of Aggregate Technology
sigma_z
= 0.007; % Standard Deviation of Technology
rho
= 0.95 ; % Autocorrelation of Technology Shocks
%--- Variales ---%
syms cc lc kc zc ca la ka za;
xx = [ca la ka za cc lc kc zc];
% Variables with "a" / "c" denote forward/current variables, respectively
% 1) Control Variables
%
c : Consumpton
%
l : Hours-worked
% 2) State Variables
%
k : Capital
%
z : Technology
varname = char('Consumption', 'Hours-worked', 'Capital', 'Technology');
%--- Simulation Settings ---%
% 1) Impulse-Response Analysis
h = 24; % Horizons of Impulse-Response Function
hit = 2; % Period in which an innovation occurs
imp = varname(4,:); % Variable hit by an innovation
SI = [0, 1]'; % Innovation Vector
% 2) 2nd Moments
mcreps = 300; %
ssize = 150;
%
disc = 300;
%
vars = 5;
%
%
lambda = 1600; %

Comparison
# of Monte-Carlo Simulation
Size of simulated time series
First "disc" observations will be discarded.
# of variables among which 2nd moments are analyzed
5 variables: y, c, i, l, y/l
Smoothing parameter of HP filter

disp('%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%')
disp('
Toolkit for a Standard RBC Model
')
disp('%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%')

- 19 -

disp('Welcome!')
disp('This is a toolkit for solving and simulating an approximated DSGE model.')
disp('
')
disp('First of all, the steady state of the model economy will be calculated.' )
disp('Hit any key when ready......')
pause;
%==================================================%
%
Calculation of the Steady State
%
%==================================================%
disp('=========================================')
disp('
Steady State
')
disp('=========================================')
disp('
K/Y
CS
KS
LS
YS
KY
CY
LS
KS
YS
IS
CS

=
=
=
=
=
=
=

= [CS, LS, KS, Z];

IS')

1/((1-beta*(1-delta))/(alpha*beta*Z));
1-delta*KY;
1/(1+Psi/((1-alpha)/CY));
LS*(alpha*beta*Z/(1-(beta*(1-delta))))^(1/(1-alpha));
Z*(KS^alpha)*(LS^(1-alpha));
delta*KS;
YS - IS;

disp([KY, CS, KS, LS, YS, IS]);


disp('Then the equilibrium conditions are linearized around the steady state,')
disp('and the solution to the approximated system will be found.')
disp('Hit any key when ready......')
pause;
%===================================================%
%
Equilibrium Conditions
%
%===================================================%
%---- Intratemporal Optimality Condition ----%
intra = Psi/(1-lc) - (1-alpha)*zc*((kc/lc)^(alpha))*(1/cc);
%---- Intertemporal Optimality Condition ----%
inter
= beta*(alpha*za*(la/ka)^(1-alpha) + (1-delta))*(1/ca) - (1/cc);
%---- Resource Constraint ----%
resource = zc*(kc^alpha)*(lc^(1-alpha)) + (1-delta)*kc - cc - ka;
%---- Dynamics of Technology Shock ----%
tech
= za - zc^rho;
%---- Optimal Conditions ----%
eqcon = [intra; inter ; resource; tech ];

- 20 -

%===================================================%
%
Linearization and Solving the Model
%
%===================================================%
%---- Differentiation ----%
J = jacobian(eqcon,xx);
%---cc =
ca =
kc =
ka =
lc =
la =
zc =
za =

Evaluation at the Steady State ----%


CS;
CS;
KS;
KS;
LS;
LS;
Z;
Z;

coef = eval(J);
SS = [ s ; s ; s ; s];
%---- Solving the Model ----%
[PX, PS, n, m] = bksolve(SS,s,coef);
%===================================================%
%
Impulse-Response Function
%
%===================================================%
disp('Next, responses to a technology shock are to be displayed.')
disp('Hit any key when ready......')
disp('
')
pause;
SC = SI; % SI will initially be used as the current state vector
% SC will be revised recursively.
S = zeros(h, m);

%
%

Simulated state variables


which will be revised as the simulation proceeds.
% Shock occurs in s-th period; matrix S is revised from 6th

for i = hit:h
row.
SA = PS*SC ; % New state vector
S(i,:) = SA'; % Revise i-th row of state matrix
SC = S(i,:)' ; % Use revised i-th row of state matrix
% as state vector in next period.
end

S(hit,:) = SI;
% Simulated endogenous & exogenous state variables
X = (PX*S')'; % Simulated jump variables
Y = [X, S];
ct
lt
kt
zt

=
=
=
=

Y(:,
Y(:,
Y(:,
Y(:,

1);
2);
3);
4);

- 21 -

yt = Y(:, 4) + alpha*Y(:, 3) + (1-alpha)*Y(:, 2); % Output


it = (YS/IS)*yt - (CS/IS)*Y(:, 1); % Investment
wt = yt - Y(:,2); % Marginal Product of Labor
%---- Graphics ----%
t = 1:length(yt);
set(gca, 'Fontsize', 12);
plot(t, yt,'k-', t, ct,'m--+', t, it,'r-.o', t, lt,'b:s', t, wt,'c:*',...
'Linewidth', 1.5, 'Markersize', 4.5');
axis([0,h,0,Inf]);
xlabel('Horizon');
ylabel('% Deviation from Steady State');
title('Impulse Response to a Unitary Technology Shock', 'Fontsize', 14);
legend('Output',
'Consumption',
'Investment',
'Hours-worked',
'Labor
Productivity');
%===================================================%
%
2nd Moments of Simulated Time Series
%
%===================================================%
disp('Finally, the model will be simulated to show 2nd moments of artificial time
series.')
disp('Hit any key when ready......')
pause;
sstd =
sstdy =
scorr =
scorrpl

zeros(mcreps,vars);
zeros(mcreps,vars);
zeros(mcreps,vars);
= zeros(mcreps, 2);

for i = 1:mcreps
%--- Generating Shock Variables ---%
eps = zeros(ssize+disc, m);
shock = sigma_z*randn(ssize+disc,1);
eps(:, 2) = shock;
%--- Generating State Variables ---%
SI = [0 0]';
Sc = SI;
S = zeros(ssize+disc, m);
for j = 1:ssize+disc
Sa = PS*Sc+(eps(j,:))' ;
S(j,:) = Sa';
Sc = S(j,:)' ;
end
S(1,:) = SI;
%--- Generating Control Variables ---%
X = (PX*S')';
Y = [X, S];
kt = Y(disc+1:disc+ssize, 3);
zt = Y(disc+1:disc+ssize, 4);
ct = Y(disc+1:disc+ssize, 1);

- 22 -

lt
yt
it
wt

=
=
=
=

Y(disc+1:disc+ssize, 2);
zt + alpha*kt + (1-alpha)*lt;
(YS/IS)*yt - (CS/IS)*ct;
yt - lt;

simy = [yt, ct, it, lt, wt];


%--- Hodrick-Prescott Filter ---%
simy = hpfilter(simy, lambda)*simy;
%--- Second Moments of Simulated Series ---%
sstd(i,:) = std(simy);
sstdy(i,:) = sstd(i,:)/sstd(i,1);
correlations = corrcoef(simy);
scorr(i,:) = correlations(1,:);
scorrpl(i,:) = [sstd(i,4)/sstd(i,5), correlations(4,5)];
end
%--- Monte-Carlo Average of Simulated Moments ---%
disp('=========================================')
disp(' Second Moments of Simulated Series
')
disp('=========================================')
disp('
')
disp('--- S.D. of y, c, i, l, y/l ---')
MCSTD = mean(sstd);
disp(MCSTD);
disp('--- S.D. Relative to y ---')
MCSTDY = mean(sstdy);
disp(MCSTDY);
disp('--- Correlation with y ---')
MCCORR = mean(scorr);
disp(MCCORR);
disp('--- S.D.(l vs y/l) & Corr. b/w l and y/l ---')
MCCORRPL = mean(scorrpl);
disp(MCCORRPL);
%--- Graphics ---%
t = 1:length(yt);
set(gca, 'Fontsize', 12);
plot(t, yt,'k-', t, ct,'m:+', t, it,'r-.o',...
'Linewidth', 1.0, 'Markersize', 3.0');
xlabel('Time Period');
ylabel('% Deviation from Steady State');
title('Simulated Time Series Data', 'Fontsize', 14);
legend('Output', 'Consumption', 'Investment');

- 23 -

A-2: Difference Equations Solver bksolve.m


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Solving First-Order Difference Equations
%%
%%
by Blanchard and Kahn(1980)'s Method
%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [PX, PS, n, m] = bksolve(SS,s,coef)
%==============================================%
%
Coefficient Matrices
%
%==============================================%
%---- Coefficients Associated with Current Variables ----%
A = [ coef(:, 1+size(coef,2)/2:size(coef,2))].*SS ;
%---- Coefficients Associated with Forward Variables ----%
B = [ -coef(:, 1:size(coef,2)/2)].*SS ;
% NOTE
% A*Y(t) = B*Y(t+1)
%
Y(t) = inv(A)*B*Y(t+1)
%==============================================%
%
Eigenvalue Decomposition
%
%==============================================%
%--- Eigenvalue Decomposition ---%
[Q,L] = eig(inv(A)*B); % columns of Q : eigenvectors
% diagonal matrix L : eigenvalues
% Q*L*inv(Q) = inv(A)*B
%--- Reordering Eigenvalues and Eigenvectors ---%
disp('=========================================')
disp('
Eigenvelues
')
disp('=========================================')
L = diag(L); % vectorize eigenvalues
disp(L);
[L, order] = sort(abs(L), 'ascend');
% sort eigenvalues in ascending order
Q = Q(:, order); % reorder eigenvectors associated with their eigenvalues
QI = inv(Q);
% Q-inverse
%--- # of Eigenvalues Inside/Outside a Unit Circle ---%
% 1) # of Control Variables X(t)
n = 0;
for i = 1:length(L)
if abs(L(i)) < 1.00000
n = n + 1;
end
end
% 2) # of State Variables S(t)
m = length(L)-n;

- 24 -

%--QI11
QI21
QI12
QI22

Partition Matrices ---%


= QI(1:n, 1:n);
= QI(n+1:m+n, 1:n);
= QI(1:n, n+1:m+n);
= QI(n+1:m+n, n+1:m+n);

%--L1 =
L2 =
VL =

Extracting Stable Roots ---%


L(1:n, :);
L(n+1:m+n, :);
diag(L(n+1:n+m,:));

%==============================================%
%
Solution to the System
%
%==============================================%
%--- Solution to Control Variables ---%
disp('==========================================')
disp(' Coefficient Matrix for Control Variables ')
disp('==========================================')
PX = -inv(QI11)*QI12;
disp(PX);
% QI11*X(t) + QI12*S(t) = 0
% X(t) = -inv(QI11)*QI12*S(t)
%--- Solution to State Variables ---%
disp('==========================================')
disp(' Coefficient Matrix for State Variables ')
disp('==========================================')
PS = inv(QI22+QI21*PX)*inv(VL)*(QI22+QI21*PX);
PS = real(PS);
disp(PS);

- 25 -

A-3: Hodrick-Prescott Filter hpfilter.m


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Hodrick-Prescott Filter
%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [hp_y]=hpfilter(y,lambda);
%--- Input Arguments --% lambda: smoothing parameter
% y: original series
%
% NOTE
% lambda = 100 for yearly data
% lambda = 1600 for quarterly data
% lambda = 14400 for monthly data
% are commonly used.
%
%--- Output --% hp_y: filtering matrix
%
% NOTE
% hp_y*y = y_hpfiltered
if size(y,1)<size(y,2);
y=y';
end
t
a
b
c
d
d

= size(y,1);
= 6*lambda+1;
= -4*lambda;
= lambda;
= [c,b,a];
= ones(t,1)*d;

m = diag(d(:,3))+diag(d(1:t-1,2),1)+diag(d(1:t-1,2),-1);
m = m+diag(d(1:t-2,1),2)+diag(d(1:t-2,1),-2);
m(1,1) = 1+lambda;
m(1,2) = -2*lambda;
m(2,1) = -2*lambda;
m(2,2) = 5*lambda+1;
m(t-1,t-1) = 5*lambda+1;
m(t-1,t) = -2*lambda;
m(t,t-1) = -2*lambda;
m(t,t) = 1+lambda;
hp_y = eye(t)-inv(m);

- 26 -

You might also like