GEconpy
A collection of tools for working with DSGE models in python, inspired by the R package gEcon
Install / Use
/learn @jessegrabowski/GEconpyREADME
gEconpy
A collection of tools for working with DSGE models in python, inspired by the fantastic R package gEcon, http://gecon.r-forge.r-project.org/.
Like gEcon, gEconpy solves first order conditions automatically, helping the researcher avoid math errors while facilitating rapid prototyping of models. By working in the optimization problem space rather than the FoC space, modifications to the model are much simpler. Adding an additional term to the utility function, for example, requires modifying only 2-3 lines of code, whereas in FoC space it may require re-solving the entire model by hand.
gEconpy uses the GCN file originally created for the gEcon package. gEcon GCN files are fully compatible with gEconpy, and includes all the great features of GCN files, including:
- Automatically solve first order conditions
- Users can include steady-state values in equations without explictly solving for them by hand first!
- Users can declare "calibrated parameters", requesting a parameter value be found to induce a specific steady-state relationship
New features, which are not backwards compatible to R, also exist:
- Specify parameters as functions of other parameters
- Declare a partial steady state to help the optimizer more quickly find a solution
- Or, declare the entire analytic steady state, and skip the optimizer!
- Add priors to parameters, including a wide range of distributions and functions on distributions
gEconpy is still in an unfinished alpha state, but I encourage anyone interested in DSGE modeling to give it a try and and report any bugs you might find.
Contributing
Contributions from anyone are welcome, regardless of previous experience. Please check the Issues tab for open issues, or to create a new issue.
Syntax Highlighting
gEconpy includes a TextMate grammar bundle for syntax highlighting of GCN files in VS Code, PyCharm, Sublime Text, and other editors. The bundle is located in the gcn.tmbundle directory. See the documentation for installation instructions.
Representing a DSGE Model
Like the R package gEcon, gEconpy uses .GCN files to represent a DSGE model. A GCN file is divided into blocks, each of which represents an optimization problem. Here the household block from a Real Business Cycle (RBC) model:
block HOUSEHOLD
{
definitions
{
u[] = C[] ^ (1 - sigma_C) / (1 - sigma_C) -
L[] ^ (1 + sigma_L) / (1 + sigma_L);
};
controls
{
C[], L[], I[], K[];
};
objective
{
U[] = u[] + beta * E[][U[1]];
};
constraints
{
C[] + I[] = r[] * K[-1] + w[] * L[] : lambda[];
K[] = (1 - delta) * K[-1] + I[] : q[];
};
calibration
{
# Fixed parameters
delta = 0.02;
# Parameters to estimate
beta ~ maxent(Beta(), lower=0.95, upper=0.999, mass=0.99) = 0.99;
sigma_C ~ Truncated(Normal(mu=1.5, sigma=0.1), lower=1.0) = 1.5;
sigma_L ~ Truncated(Nornal(mu=2.0, sigma=0.1), lower=1.0) = 2.0;
};
};
Basic Basics
A .GCN file uses an easy-to-read syntax. Whitespace is not meaningful - lines are terminated with a ";", so long equations can be split into multiple lines for readability. There are no reserved keywords* to avoid -- feel free to write beta instead of betta!
Model variables are written with a name followed by square brackets, as in U[]. The square brackets give the time index the variable enters with. Following Dynare conventions, capital stock K[-1] enters with a lag, while all other variables enter in the present. Expectations are denoted by wrapping variables with E[], as in E[U[1]] for expected utility at t+1. So I lied, there are a couple reserved keywords (hence the asterisk). Finally, you can refer directly to steady-state values as K[ss].
Parameters are written exactly as variables, except they have no square brackets [].
Anatomy of a Block
Blocks are divided into five components: definitions, controls, objective, constraints, identities, shocks, and, calibration. In this block, we see five of the seven. The blocks have the following functions:
definitionscontains equations that are not stored in the model. Instead, they are immediately substituted into all equations within the same block. In this example, a definition is used for the instantaneous utility function. It will be immediately substituted into the Bellman equation written in theobjectiveblock.controlsare the variables under the agent's control. The objective function represented by the block will be solved by forming a Lagrange function and taking derivatives with respect to the controls.- The
objectiveblock contains only a single equation, and gives the function an agent will try to maximize over an infinite time horizon. In this case, the agent has a CRRA utility function. constraintsgive the resource constraints that the agent's maximization must respect. All constraints are given their own Lagrange multipiers.identitiesare equations that are not part of an optimization problem, but that are a part of the model. Unlike equations defined in thedefinitionsblock,identitiesare saved in the model's system of equations.shocksare where the user defines exogenous shocks, as invarexoin Dynare.- The
calibrationblock where free parameters, calibrated parameters, and parameter prior distributions are defined.
Parameter Values and Priors
All parameters must be given values. In the household block above, all parameters are given a value directly. beta and delta are set fixed, while sigma_C and sigma_L are given priors and starting values. The ~ operator denotes a Prior, while = denotes a fixed value. All parameters must have a fixed value -- this is used as the "default" value when building and solving the model. Priors, on the other hand, are optional.
To represent priors, gEconpy uses the preliz package. All priors should follow preliz names and parameterization. For a full list, see their example gallery. Notice that:
- Distributions are capitalized, as in
Normal,Beta,Gamma. For those with multiple words, use camel-case (e.g.InverseGamma) - Parameters are given as keyword arguments, as in
Normal(mu=0, sigma=1). - You are allowed to use preliz transformations on distributions, including
Truncated,Censored,Hurdle, andMixture. For example,Truncated(Normal(mu=0, sigma=1), lower=0)is a truncated normal distribution with a lower bound of 0. - You can also directly call
maxentto parameterize a distribution by an HDI range and probability mass within that range. For example,beta ~ maxent(Beta(), lower=0.95, upper=0.99, mass=0.99)finds the beta distribution with 99% of its mass between 0.95 and 0.99, and which is otherwise maximally uninformative.
As an alternative to setting a parameter value directly, the user can declare a parameter to be calibrated. To do this, give a steady-state relationship that the parameter should be calibrated to ensure is true. The following GCN code block for the firm's optimization problem shows how this is done:
block FIRM
{
controls
{
K[-1], L[];
};
objective
{
@minimize
TC[] = r[] * K[-1] + w[] * L[];
};
constraints
{
Y[] = A[] * K[-1] ^ alpha * L[] ^ (1 - alpha) : mc[];
};
identities
{
# Perfect competition
mc[] = 1;
};
calibration
{
L[ss] / K[ss] = 0.36 -> alpha;
};
};
The alpha parameter is set so that in the steady state, the ratio of labor to capital is 0.36. On the back end, gEconpy will use an optimizer to find a value of alpha that satisfies the user's condition. Note that calibrated parameters cannot have prior distributions!
Lagrange Multipliers and First Order Conditions
As mentioned, all constraints will automatically have a Lagrange multiplier assigned to them. The user name these multipliers himself by putting a colon ":" after an equation, followed by a variable to be used for that Lagrange multiplier. From the code above:
C[] + I[] = r[] * K[-1] + w[] * L[] : lambda[];
K[] = (1 - delta) * K[-1] + I[] : q[];
The multiplier associated with the budget constraint has been given the variable lambda[], as is usual in the literature. The law of motion of capital has been given the variable q[]. If the user wanted, she could use these variables in further computations within the block, for example Q[] = q[] / lambda[], Tobin's Q, could be added in the identities block.
Internally, first order conditions are solved by first making all substitutions from definitions, then forming the following Lagrangian function:
L = objective.RHS - lm1 * (control_1.LHS - control_1.RHS) - lm2 * (control_2.LHS - control_2.RHS) ... - lm_k * (control_k.LHS - control_k.RHS)
When the objective carries the @minimize tag, the objective RHS is negated before forming the Lagrangian, converting the minimization into an equivalent maximization.
Next, the derivative of this Lagrangian is taken with respect to all control variables and all lagrange multipliers. Derivatives are are computed "though time" using TimeAwareSymbols, an extension of a normal Sympy symbol. For a control variable x, the total derivative over time is built up as dL[]/dx[] + beta * dL[+1]/dx + beta * beta * dL[+2]/dx[] ....
The result of this unrolling and taking derivatives process are the first order conditions (FoC). All model FoCs, along with objectives, constraints, and identities, are saved into the system of equations that represents the model.
Excluding
Related Skills
node-connect
352.5kDiagnose OpenClaw node connection and pairing failures for Android, iOS, and macOS companion apps
frontend-design
111.3kCreate distinctive, production-grade frontend interfaces with high design quality. Use this skill when the user asks to build web components, pages, or applications. Generates creative, polished code that avoids generic AI aesthetics.
openai-whisper-api
352.5kTranscribe audio via OpenAI Audio Transcriptions API (Whisper).
qqbot-media
352.5kQQBot 富媒体收发能力。使用 <qqmedia> 标签,系统根据文件扩展名自动识别类型(图片/语音/视频/文件)。
