Title: | Simulate Stock-Flow Consistent Models |
Version: | 0.2.1 |
Description: | Routines to write, simulate, and validate stock-flow consistent (SFC) models. The accounting structure of SFC models are described in Godley and Lavoie (2007, ISBN:978-1-137-08599-3). The algorithms implemented to solve the models (Gauss-Seidel and Broyden) are described in Kinsella and O'Shea (2010) <doi:10.2139/ssrn.1729205> and Peressini and Sullivan (1988, ISBN:0-387-96614-5). |
License: | MIT + file LICENSE |
Encoding: | UTF-8 |
RoxygenNote: | 7.1.1 |
URL: | https://github.com/joaomacalos/sfcr |
BugReports: | https://github.com/joaomacalos/sfcr/issues |
Imports: | dplyr (≥ 1.0.2), expm (≥ 0.999.5), forcats (≥ 0.5.0), igraph (≥ 1.2.6), kableExtra (≥ 1.3.1), magrittr (≥ 1.5), purrr (≥ 0.3.4), Rdpack (≥ 2.1), rootSolve (≥ 1.8.2.1), rlang (≥ 0.4.7), tibble (≥ 3.0.3), tidyr (≥ 1.1.2), tidyselect (≥ 1.1.0), stringr (≥ 1.4.0), utils, vctrs (≥ 0.3.5), Rcpp (≥ 1.0.5) |
Suggests: | ggraph, ggplot2, grDevices, knitr, pkgdown, rmarkdown, RColorBrewer, testthat (≥ 2.3.2), tidygraph, tidyverse, networkD3 |
VignetteBuilder: | knitr |
RdMacros: | Rdpack |
LinkingTo: | Rcpp, RcppArmadillo |
NeedsCompilation: | yes |
Packaged: | 2021-10-11 07:46:08 UTC; JouJo |
Author: | Joao Macalos |
Maintainer: | Joao Macalos <joaomacalos@gmail.com> |
Repository: | CRAN |
Date/Publication: | 2021-10-11 08:00:02 UTC |
Pipe operator
Description
See magrittr::%>%
for details.
Usage
lhs %>% rhs
Abort if duplicated variables
Description
Abort if duplicated variables
Usage
.abort_if_dup(dups)
Arguments
dups |
name(s) of offending variables |
Author(s)
João Macalós
Abort if typo on the codes of columns
Description
Abort if typo on the codes of columns
Usage
.abort_typo_code(nms)
Arguments
nms |
Incorrect codes detected |
Author(s)
João Macalós
Abort if column validation is not fulfilled
Description
Abort if column validation is not fulfilled
Usage
.abort_water_leakc(c2names, which)
Arguments
c2names |
Names of offending columns |
which |
Balance-sheet or transactions-flow matrix? |
Author(s)
João Macalós
Abort if row validation is not fulfilled
Description
Abort if row validation is not fulfilled
Usage
.abort_water_leakr(r2names, which)
Arguments
r2names |
Names of offending rows |
which |
Balance-sheet or transactions-flow matrix? |
Author(s)
João Macalós
Find dependencies and order the equations
Description
Find dependencies and order the equations
Usage
.add_time2(x)
Arguments
x |
A vector to modify |
Author(s)
João Macalós
Find dependencies and order the equations
Description
Find dependencies and order the equations
Usage
.add_time_stamps(eq_as_tb)
Arguments
eq_as_tb |
A tibble generated with |
Author(s)
João Macalós
Check if all values in x are equal
Description
Check if all values in x are equal
Usage
.all_equal(x, tol)
Arguments
x |
A numeric vector |
tol |
Tolerance to declare equality |
Author(s)
João Macalós
Take arguments and make them a row of a tibble
Description
Take arguments and make them a row of a tibble
Usage
.args_to_row(arg, tb)
Arguments
arg |
The arguments to transform |
tb |
The Tibble that will receive the rows |
Author(s)
João Macalós
Broyden solver algorithm
Description
Broyden solver algorithm
Usage
.broyden_solver(.x0, .fn, max_ite, tol)
Arguments
.x0 |
Vector with initial guess for x. |
.fn |
A function containing the system of equations. |
max_ite |
Maximum number of iterations allowed |
tol |
A numeric value indicating the accepted tolerance to declare convergence. |
Note
Check https://www.math.usm.edu/lambers/mat419/lecture11.pdf for a quick reference on the algorithm.
Author(s)
João Macalós
Check shocks for length consistency and warn about risks of using exogenous series
Description
This function makes two checks:
Usage
.check_external_consistency(external, periods = periods)
Arguments
external |
An .eq_as_tb() tibble with external variables. |
periods |
The periods of the baseline model. |
Details
The exogenous variable is a constant that is repeated over time;
The exogenous variable has exactly the same length as the shock.
Furthermore, it throws a warning that using exogenous series in a shock can lead to unexpected behavior if the length of the shock is not the same as the periods in the scenario.
Author(s)
João Macalós
Check shocks for length consistency and warn about risks of using exogenous series
Description
This function executes two checks and issues one warning.
Usage
.check_shock_consistency(shock, periods = periods)
Arguments
shock |
A sfcr_shock object |
Details
First, it checks that the start of the shock is not negative and that the end of the shock is not bigger than the number of periods in the scenario.
Secondly, it checks for consistency on the length of the shocks added to the scenario. Only two types of exogenous variables are allowed:
The exogenous variable is a constant that is repeated over time;
The exogenous variable has exactly the same length as the shock.
Furthermore, it throws a warning that using exogenous series in a shock can lead to unexpected behavior if the length of the shock is not the same as the periods in the scenario.
Author(s)
João Macalós
Check that symmetry condition is valid and fulfill missing entries
Description
Check that symmetry condition is valid and fulfill missing entries
Usage
.check_symmetry(m)
Arguments
m |
A square matrix |
Author(s)
João Macalós
Split the formulae into a tibble
with the left-hand side and
right-hand side as columns
Description
Split the formulae into a tibble
with the left-hand side and
right-hand side as columns
Usage
.eq_as_tb(equations)
Arguments
equations |
list of equations |
Author(s)
João Macalós
Extend a baseline matrix
Description
This function is called if a scenario is to be created that just continues with the baseline specification. It is useful to create a benchmark model to compare new scenarios.
Usage
.extend_baseline_matrix(baseline, periods)
Arguments
baseline |
A baseline model |
periods |
The total number of periods to run the model |
Author(s)
João Macalós
Fill all possible rows and columns and validate
Description
Fill all possible rows and columns and validate
Usage
.fill_rows_and_cols(m)
Arguments
m |
A square matrix |
Author(s)
João Macalós
Find blocks of independent equations (wrapper around igraph
functions)
Description
Find blocks of independent equations (wrapper around igraph
functions)
Usage
.find_blocks(adj)
Arguments
adj |
Adjacency matrix |
Author(s)
João Macalós
Find names for display matrix
Description
Clean cells to display in latex format
Usage
.find_names(matrix)
Arguments
matrix |
A balance-sheet or transactions-flow matrix |
Author(s)
João Macalós
Get numeric matrix for evaluation from balance-sheet or transactions-flow matrices
Description
Get numeric matrix for evaluation from balance-sheet or transactions-flow matrices
Usage
.get_matrix(mtrx, bl1, bl2)
Arguments
mtrx |
Balance-sheet or transactions-flow matrix |
bl1 |
calls from baseline model |
bl2 |
external from baseline model |
Author(s)
João Macalós
Check if two values are equal
Description
Check if two values are equal
Usage
.is_equal(x, y, tol)
Arguments
x , y |
numeric values |
tol |
Tolerance to declare equality |
Author(s)
João Macalós
Make the underlying matrix that will be modified in place by the solvers
Description
Make the underlying matrix that will be modified in place by the solvers
Usage
.make_matrix(equations, external, periods, initial = NULL)
Arguments
equations |
Prepared equations. |
external |
Exogenous and parameters as tibble. |
periods |
Total number of rows. |
initial |
Initial values, if supplied. |
Author(s)
João Macalós
Prep equations for Broyden and Newton solvers
Description
Prep equations for Broyden and Newton solvers
Usage
.prep_broyden(.block)
Arguments
.block |
Blocks of equations |
Author(s)
João Macalós
Re-wrote the equations with the correct matrix syntax that will be used to evaluate the expressions inside the Gauss Seidel algorithm
Description
Re-wrote the equations with the correct matrix syntax that will be used to evaluate the expressions inside the Gauss Seidel algorithm
Usage
.prep_equations(ordered_eqs, external)
Arguments
ordered_eqs |
ordered equations after passing through |
external |
Tibble of exogenous values and parameters, already separated with
|
Author(s)
João Macalós
Pattern replacement var
Description
Pattern replacement var
Usage
.pvar(x)
Arguments
x |
vector of variables |
Author(s)
João Macalós
Pattern replacement lag
Description
Pattern replacement lag
Usage
.pvarlag(x)
Arguments
x |
vector of variables |
Author(s)
João Macalós
Find cyclical nodes
Description
Find cyclical nodes
Usage
.return_loops(m)
Arguments
m |
adjacency matrix |
Note
See Networks: an introduction from M.E.J. Newman, 2010, p. 136-139 for a reference on this algorithm.
Scan columns to fill whenever there's only one value missing.
Description
Scan columns to fill whenever there's only one value missing.
Usage
.scan_cols(m)
Arguments
m |
A square matrix |
Author(s)
João Macalós
Scan rows to fill whenever there's only one value missing.
Description
Scan rows to fill whenever there's only one value missing.
Usage
.scan_rows(m)
Arguments
m |
A square matrix |
Author(s)
João Macalós
Broyden solver wrapper
Description
Broyden solver wrapper
Usage
.sfcr_broyden(m, equations, periods, max_ite, tol)
Arguments
m |
The initialized matrix obtained with |
equations |
Prepared equations with |
periods |
Total number of rows (periods) in the model. |
max_ite |
Maximum number of iterations allowed per block per period. |
tol |
Tolerance accepted to determine convergence. |
Details
This function implements the Broyden method to solve the cyclical blocks of equations.
Author(s)
João Macalós
Check for missing endogenous variables
Description
Check for missing endogenous variables
Usage
.sfcr_eqs_check(m, equations)
Arguments
m |
The initialized matrix obtained with |
equations |
Prepared equations with |
Author(s)
João Macalós
Find adjacency matrix for a system of equations
Description
Find adjacency matrix for a system of equations
Usage
.sfcr_find_adjacency(equations)
Arguments
equations |
A system of equations already time stamped |
Author(s)
João Macalós
Place the equations in the correct order for estimation
Description
Place the equations in the correct order for estimation
Usage
.sfcr_find_order(equations)
Arguments
equations |
Equations supplied by the user. |
Details
Create an adjacency matrix and apply
.find_blocks()
function to identify the blocks
of independent equations.
Author(s)
João Macalós
Gauss Seidel algorithm
Description
Gauss Seidel algorithm
Usage
.sfcr_gauss_seidel(m, equations, periods, max_ite, tol)
Arguments
m |
The initialized matrix obtained with |
equations |
Prepared equations with |
periods |
Total number of rows (periods) in the model. |
max_ite |
Maximum number of iterations allowed per block per period. |
tol |
Tolerance accepted to determine convergence. |
Details
This algorithm simulates the model by recursion by using nested for loops. At each round of iteration, the values calculated are compared to the previous values. If the difference is below a tolerance value set by the user, the round of calculations have converged and the algorithm jump to the next block of equations.
The algorithm modifies a matrix in place to optimize its performance.
Author(s)
João Macalós
Make matrix for scenario calculations
Description
Make matrix for scenario calculations
Usage
.sfcr_make_scenario_matrix(baseline, scenario, periods)
Arguments
baseline |
a model calculated with the |
scenario |
a List holding the different scenarios |
periods |
The total number of periods in the model |
Details
This function generates the base matrix that is going to be modified in place by the different solvers.
Author(s)
João Macalós
Newton-Raphson solver implemented with rootSolve::multiroot()
Description
Newton-Raphson solver implemented with rootSolve::multiroot()
Usage
.sfcr_newton(m, equations, periods, max_ite, tol, ...)
Arguments
m |
The initialized matrix obtained with |
equations |
Prepared equations with |
periods |
Total number of rows (periods) in the model. |
max_ite |
Maximum number of iterations allowed per block per period. |
tol |
Tolerance accepted to determine convergence. |
... |
Extra parameters to pass to |
Details
This function implements the Newton-Raphson method to solve the cyclical
blocks of equations. It relies on the multiroot()
function from rootSolve
.
Author(s)
João Macalós
Transform entries into latex style
Description
Transform entries into latex style
Usage
.to_latex_style(matrix, nms)
Arguments
matrix |
a balance-sheet or transactions-flow matrix |
nms |
Cleaned names with |
Author(s)
João Macalós
Validate a balance-sheet or transactions-flow matrix on the simulated data
Description
Validate a balance-sheet or transactions-flow matrix on the simulated data
Usage
.validate_matrix(mtrx, m, which = "tfm", tol, rtol = FALSE)
Arguments
mtrx |
A balance-sheet or transactions-flow matrix |
m |
A baseline model in matrix format – get from attributes or with
|
which |
A balance-sheet or a transactions-flow matrix? |
tol |
Tolerance for convergence |
rtol |
Relative tolerance? |
Author(s)
João Macalós
Check that the portfolio matrix respect the horizontal and vertical adding-up constraints
Description
Check that the portfolio matrix respect the horizontal and vertical adding-up constraints
Usage
.validate_scan(m, which)
Arguments
m |
A square matrix |
which |
Rows or columns? |
Author(s)
João Macalós
Abort if not
Description
Abort if not
Usage
abortifnot(cnd, message = NULL)
Arguments
cnd |
Condition to be evaluated. |
message |
Message to display if condition is false. |
Author(s)
João Macalós
sfcr_mlt constructor
Description
sfcr_mlt constructor
Usage
new_sfcr_mlt(multis, fixed)
Arguments
multis |
A list with multiple |
fixed |
The fixed argument |
Author(s)
João Macalós
sfcr_mlt_set constructor
Description
sfcr_mlt_set constructor
Usage
new_sfcr_mlt_set(x, original)
Arguments
x |
A expanded list of sfcr_set's |
original |
the original sfcr_set |
Author(s)
João Macalós
sfcr_mlt_shock constructor
Description
sfcr_mlt_shock constructor
Usage
new_sfcr_mlt_shock(x, original)
Arguments
x |
A expanded list of sfcr_shock's |
original |
the original sfcr_shock |
Author(s)
João Macalós
sfcr_set constructor
Description
sfcr_set constructor
Usage
new_sfcr_set(list)
Arguments
list |
A list |
Author(s)
João Macalós
new_sfcr_tbl constructor
Description
new_sfcr_tbl constructor
Usage
new_sfcr_tbl(tbl, matrix, calls, external)
Arguments
tbl |
A tibble |
matrix |
a Matrix |
calls |
Calls tibble |
external |
Vector with external names |
Author(s)
João Macalós
Simulate the baseline scenario of a stock-flow consistent model
Description
The sfcr_baseline()
function is used to simulate a SFC model.
Usage
sfcr_baseline(
equations,
external,
periods,
initial = NULL,
hidden = NULL,
max_iter = 350,
.hidden_tol = 0.1,
tol = 1e-08,
method = "Broyden",
rhtol = FALSE,
...
)
Arguments
equations |
A |
external , initial |
A |
periods |
A number specifying the total number of periods of the model to be simulated. |
Named object that identify the two variables that make the hidden equality
in the SFC model, e.g., | |
max_iter |
Maximum iterations allowed per period. |
Error tolerance to accept the equality of the hidden equation. Defaults to 1.
In growth models, computational errors might buildup in the hidden equation, which renders any absolute
comparison inadequate. For such models, please turn | |
tol |
Tolerance accepted to determine convergence. |
method |
The method to use to find a solution. Defaults to "Broyden". |
rhtol |
A logical argument that defines whether the a relative measure is used to evaluate
the hidden equation or not. Defaults to |
... |
Extra arguments to pass to |
Details
The output of a sfcr_baseline()
is a sfcr_tbl
. The only difference between
a sfcr_tbl
and a standard tbl_df
is that the former has two extra attributes:
matrix
and call
. The matrix
attribute, for example, can be accessed by
calling attributes(sfcr_sim_object)$matrix
.
It is possible to see, in the matrix, the number of iterations required to calculate each
block of equations in the model.
The call
attribute shows the blocks of equations and preserve the call that are used
internally.
The equations
, exogenous
, and parameters
arguments must be written
with the R formula syntax, i.e., the left-hand side of each item is separated to the
right-hand side by a twiddle. Variables that represent lags of endogenous or exogenous
variables must be followed by [-1]
. See examples for details on the syntax.
Before solving the system of equations, two consecutive depth-first searches identify
and order the blocks of independent equations in the system. The system is then solved
sequentially, i.e., the variables that depend only on lagged or exogenous values are evaluated
first, and then the variables that depends on these variables, etc. The solving algorithms
are only applied to the blocks of mutually dependent equations. The great igraph
package is used to implement the two consecutive depth-first searches.
Methods:
The sfcr
package provides three algorithms to solve the blocks of cyclical equations:
the Gauss-Seidel algorithm, the Broyden algorithm, and the Newton-Raphson algorithm. The
default method is "Broyden" as it tends to be fastest one.
See (Kinsella and OShea 2010) for details on the Gauss-Seidel algorithm and (Peressini et al. 1988) for details on the Broyden and Newton-Raphson algorithms.
The "Broyden" algorithm uses the rootSolve::jacobian.full()
function to get the
initial Jacobian matrix, and compiled code from RcppArmadillo
to invert the
jacobians. See also https://www.math.usm.edu/lambers/mat419/lecture11.pdf.
The Gauss Seidel algorithm is implemented as described by (Kinsella and OShea 2010).
Finally, the "Newton" method uses the rootSolve::multiroot()
function to solve the system.
Hidden equation:
One of the defining aspects of a SFC model is its water tight accounting. One way
to check whether the model was correctly defined is to see if the hidden (redundant)
equation is satisfied after the model is simulated. In stationary models, an absolute
comparison should suffice as the model converges to a stationary state. However,
growth models converge to a stable growth rate where stocks are perpetually increasing.
It is inadequate to use a absolute comparison in such models. In these cases, the
rhtol
argument ("relative hidden tolerance") must be set to TRUE
in order
to perform a relative comparison. The relative comparison evaluates the numerical
discrepancy in the hidden equation as a ratio of one of its elements. For example,
if hidden = c("Bbs" = "Bbd")
, the hidden equation will be evaluated according to
the following steps:
-
d = (Bbs - Bbd)
-
isTRUE(d/Bbs < .hidden_tol)
In general, the .hidden_tol
argument should be set to a small number (e.g. 1e-6).
The function will check that this proportion remains the same for all simulated periods.
Value
A sfcr_tbl
.
Author(s)
João Macalós, joaomacalos@gmail.com
References
Kinsella S, OShea T (2010). “Solution and Simulation of Large Stock Flow Consistent Monetary Production Models via the Gauss Seidel Algorithm.” SSRN Electronic Journal. doi: 10.2139/ssrn.1729205, https://doi.org/10.2139/ssrn.1729205. Peressini AL, Sullivan FE, Uhl JJ (1988). The Mathematics of Nonlinear Programming. Springer-Verlag, Berlin, Heidelberg. ISBN 0387966145.
Examples
eqs <- sfcr_set(
TXs ~ TXd,
YD ~ W * Ns - TXs,
Cd ~ alpha1 * YD + alpha2 * Hh[-1],
Hh ~ YD - Cd + Hh[-1],
Ns ~ Nd,
Nd ~ Y / W,
Cs ~ Cd,
Gs ~ Gd,
Y ~ Cs + Gs,
TXd ~ theta * W * Ns,
Hs ~ Gd - TXd + Hs[-1]
)
external <- sfcr_set(Gd ~ 20, W ~ 1, alpha1 ~ 0.6, alpha2 ~ 0.4, theta ~ 0.2)
# Periods is set to 10 to run faster. A usual model should run at
# least 50 periods to find a steady state
sfcr_baseline(equations = eqs, external = external, periods = 10)
Create a tbl_graph
object blocks and cycles information
Description
Create a tbl_graph
object blocks and cycles information
Usage
sfcr_dag_blocks(equations)
Arguments
equations |
A |
Details
This function creates a tbl_graph
with information about
the blocks and cycles attached to it. This object can then be used to
plot the DAG of the model.
Value
A tbl_graph
Author(s)
João Macalós, joaomacalos@gmail.com
Plot the DAG with blocks and cycles information
Description
Plot the DAG with blocks and cycles information
Usage
sfcr_dag_blocks_plot(equations, title = NULL, size = 10)
Arguments
equations |
A |
title |
Title of the plot. |
size |
Size of the points. |
Details
This function creates a tbl_graph
with information about
the cycles attached to it. This object can then be used to
plot the DAG of the model.
Value
A tbl_graph
Author(s)
João Macalós, joaomacalos@gmail.com
Create a tbl_graph
object with cycles information
Description
Create a tbl_graph
object with cycles information
Usage
sfcr_dag_cycles(equations)
Arguments
equations |
A |
Details
This function creates a tbl_graph
with information about
the cycles attached to it. This object can then be used to
plot the DAG of the model.
Value
A tbl_graph
Author(s)
João Macalós, joaomacalos@gmail.com
Plot the DAG with cycles information
Description
Plot the DAG with cycles information
Usage
sfcr_dag_cycles_plot(equations, title = NULL, size = 10)
Arguments
equations |
A |
title |
Title of the plot. |
size |
Size of the points. |
Author(s)
João Macalós
Expand variables to implement sensitivity analysis
Description
The sfcr_expand()
function is a s3 generic that takes
a list of external objects and returns a expanded set of these lists.
It has methods for sfcr_set
objects and for sfcr_shock
objects.
Usage
sfcr_expand(x, variable, values)
Arguments
x |
A external set created with |
variable |
the name of variable to be expanded. |
values |
a vector containing the new values of the external or shock variable. |
Details
There are two available methods for the sfcr_expand()
function:
-
sfcr_set
: Takes asfcr_set
object with external variables and creates a list of sets that inherits all the aspects of thex
set supplied but set the values of thevariable
to the each element ofvalue
. The output is asfcr_mlt_set
object. -
sfcr_shock
: Takes asfcr_shock
object and creates a list of shocks that inherits all the aspects of thex
shock but set thevalues
of thevariable
to each element ofvalue
. The output of this method is asfcr_mlt_shock
object.
Author(s)
João Macalós
Examples
# 1. Expand a external set:
external <- sfcr_set(G_d ~ 20, W ~ 1, alpha1 ~ 0.6, alpha2 ~ 0.4, theta ~ 0.2)
sfcr_expand(external, alpha2, c(0.1, 0.2))
# 2. Expand a shock:
shock <- sfcr_shock(variables = sfcr_set(alpha1 ~ 0.8), start = 5, end = 50)
sfcr_expand(shock, alpha1, c(0.7, 0.8, 0.9))
Get block structure of a sfcr_tbl
object
Description
Get block structure of a sfcr_tbl
object
Usage
sfcr_get_blocks(sfcr_tbl)
Arguments
sfcr_tbl |
A |
Author(s)
João Macalós
Get Matrix form of sfcr_tbl
object
Description
Get Matrix form of sfcr_tbl
object
Usage
sfcr_get_matrix(sfcr_tbl)
Arguments
sfcr_tbl |
A |
Author(s)
João Macalós
Create balance-sheet or transactions-flow matrices
Description
Create balance-sheet or transactions-flow matrices
Usage
sfcr_matrix(columns, codes, ...)
Arguments
columns |
Vector containing the name of the columns in the matrix. |
codes |
A vector containing the abbreviation of the
column names that is going to be used as a reference to
build the rows. They must be provided in the same order
as the |
... |
Vectors that fill the rows of the matrix.
The first element of each vector must be the name of the
row in the respective matrix. The remaining elements of the vector
must be name-value pairs that exactly matches the |
Note
This function can be used to generate a transactions- flow matrix as well as a balance-sheet matrix. If the user wishes to validate these matrices with the simulated data, please pay attention to the following details:
Transactions-flow Matrix: In the transactions-flow matrix, the
sum
column is going to be generated automatically by the validation function. Please do not add it by hand.Balance-sheet Matrix: In the balance-sheet matrix, it might be the case that some rows do not sum to zero. Therefore, the user must supply by hand the non-zero values of the
sum
column. This column should always be the last column of the matrix and should always be named as "Sum". If there's no column named as "Sum", it will be generated automatically by the validation function with all entries equal to zero.
Author(s)
João Macalós, joaomacalos@gmail.com
Examples
# Balance-sheet matrix
bs_pc <- sfcr_matrix(
columns = c("Households", "Firms", "Government", "Central bank", "sum"),
codes = c("h", "f", "g", "cb", "s"),
r1 = c("Money", h = "+Hh", cb = "-Hs"),
r2 = c("Bills", h = "+Bh", g = "-Bs", cb = "+Bcb"),
r3 = c("Balance", h = "-V", g = "+V")
)
# Transactions-flow matrix
tfm_pc <- sfcr_matrix(
columns = c("Households", "Firms", "Government", "CB current", "CB capital"),
codes = c("h", "f", "g", "cbc", "cbk"),
c("Consumption", h = "-C", f = "+C"),
c("Govt. Expenditures", f = "+G", g = "-G"),
c("Income", h = "+Y", f = "-Y"),
c("Int. payments", h = "+r[-1] * Bh[-1]", g = "-r[-1] * Bs[-1]", cbc = "+r[-1] * Bcb[-1]"),
c("CB profits", g = "+r[-1] * Bcb[-1]", cbc = "-r[-1] * Bcb[-1]"),
c("Taxes", h = "-TX", g = "+TX"),
c("Ch. Money", h = "-(Hh - Hh[-1])", cbk = "+(Hs - Hs[-1])"),
c("Ch. Bills", h = "-(Bh - Bh[-1])", g = "+(Bs - Bs[-1])", cbk = "-(Bcb - Bcb[-1])")
)
Print matrix to screen
Description
Print matrix to screen
Usage
sfcr_matrix_display(matrix, which = "tfm")
Arguments
matrix |
A balance sheet or transactions-flow matrix |
which |
A character string for the matrix. Is it a balance-sheet or
a transactions-flow matrix? here are two options:
|
Details
This function takes a matrix as input and generate a kableExtra
table with math symbols displayed in latex style.
Note
This function converts the math expressions used to build the sfcr_matrix
into a latex format, but cannot add modifications to it. The user is
invited to explore the source code and the kableExtra
package in order to
personalize his/her own matrices.
Author(s)
João Macalós
Examples
# Balance-sheet matrix
bs_insout <- sfcr_matrix(
columns = c("Households", "Firms", "Government", "Central bank", "Banks", "Sum"),
codes = c("h", "f", "g", "cb", "b", "s"),
r1 = c("Inventories", f = "+INV", s = "+INV"),
r2 = c("HPM", h = "+Hhd", cb = "-Hs", b = "+Hbd"),
r3 = c("Advances", cb = "+As", b = "-Ad"),
r4 = c("Checking deposits", h = "+M1h", b = "-M1s"),
r5 = c("Time deposits", h = "+M2h", b = "-M2s"),
r6 = c("Bills", h = "+Bhh", g = "-Bs", cb = "+Bcb", b = "+Bbd"),
r7 = c("Bonds", h = "+BLh * pbl", g = "-BLs * pbl"),
r8 = c("Loans", f = "-Ld", b = "+Ls"),
r9 = c("Balance", h = "-V", f = 0, g = "+GD", cb = 0, b = 0, s = "-INV")
)
sfcr_matrix_display(bs_insout, "bs")
Simulate multiple SFC models at the same time
Description
The sfcr_multis()
function is used to simulate multiple models
at the same time, returning a list of sfcr_tbl
s.
Usage
sfcr_multis(expanded, fixed, periods, ...)
Arguments
expanded |
A |
fixed |
A |
periods |
A number specifying the total number of periods of the model to be simulated. |
... |
Additional arguments to pass to the underlying implementation of the
|
Details
The sfcr_multis()
function takes an expanded
object and
a fixed
to simulate multiple models that will share the content
of fixed
but vary on the expanded
.
This function is a generic, which means that its implementation
depends on the class of the expanded
argument.
The available methods for the sfcr_multis()
function depends
on the expanded
argument. There are three possible methods:
-
sfcr_mlt_set
: When thesfcr_multis()
takes ansfcr_mlt_set
class as the input ofexpanded
, it must take a list of equations of thesfcr_set
class as thefixed
input. This method simulates many baseline models that accept the same set of equations and vary on the external variables supplied with theexpanded
argument. -
sfcr_mlt_shock
: When thesfcr_multis()
takes ansfcr_mlt_shock
class as the input ofexpanded
, it must also take an object ofsfcr_tbl
class as the input offixed
. It will simulate multiple scenario models that takes the same baseline model and diverge on the content of the multiple shocks provided with theexpanded
argument that are applied to it. -
sfcr_mlt
: When thesfcr_multis()
function takes asfcr_mlt
class object as the input of theexpanded
argument, asfcr_shock
object must be supplied with thefixed
argument. This method simulates multiple scenario models that applies the same shock to a varying number of baseline models.
Author(s)
João Macalós
Examples
eqs <- sfcr_set(
TX_s ~ TX_d,
YD ~ W * N_s - TX_s,
C_d ~ alpha1 * YD + alpha2 * H_h[-1],
H_h ~ YD - C_d + H_h[-1],
N_s ~ N_d,
N_d ~ Y / W,
C_s ~ C_d,
G_s ~ G_d,
Y ~ C_s + G_s,
TX_d ~ theta * W * N_s,
H_s ~ G_d - TX_d + H_s[-1]
)
external <- sfcr_set(G_d ~ 20, W ~ 1, alpha1 ~ 0.6, alpha2 ~ 0.4, theta ~ 0.2)
shock <- sfcr_shock(
variables = sfcr_set(
alpha2 ~ 0.3
),
start = 1,
end = 3
)
baseline <- sfcr_baseline(eqs, external, periods = 5)
# Example 1: Many external sets, 1 set of equations:
expanded1 <- sfcr_expand(external, alpha1, c(0.7, 0.8))
multis1 <- sfcr_multis(expanded = expanded1, fixed = eqs, periods = 5)
# Example 2: Many shocks, 1 baseline model:
expanded2 <- sfcr_expand(shock, alpha2, c(0.1, 0.2))
multis2 <- sfcr_multis(expanded = expanded2, fixed = baseline, periods = 5)
# Example 3: Many baseline models, 1 shock:
multis3 <- sfcr_multis(expanded = multis1, fixed = shock, periods = 5)
Find a valid matrix of portfolio parameters
Description
The sfcr_portfolio()
function calculates a valid matrix of portfolio
parameters by applying the symmetry condition and then filling the missing
rows accordingly to the vertical and horizontal adding-up constraints.
Usage
sfcr_portfolio(m, known)
Arguments
m |
A matrix of parameter names |
known |
A named vector of known parameters. One entry for each symmetry condition is enough to find a valid matrix. |
Details
This function calculates only the values of the rates of return matrix, i.e., the internal matrix. The adding-up constraint number 1, that calculates the share of assets in the net wealth and the impact of regular income to wealth ratio must be calculated separately.
If supplied with insufficient parameters, the function will return a matrix with NA values.
This function requires at least (n^2 - n)/2 known parameters to find a valid portfolio matrix, where n is the number of rows/columns. This is achieved by setting known parameters outside the diagonal and not on symmetrical entries, i.e., not lambda12 and lambda21, for example.
Author(s)
João Macalós
Examples
j1 <- matrix(paste0("lambda", c(11:14, 21:24, 31:34, 41:44)), ncol = 4, nrow = 4, byrow = TRUE)
j2 <- c(lambda12 = 0, lambda13 = 0, lambda14 = 0, lambda23 = -15, lambda24 = -15, lambda34 = -15)
sfcr_portfolio(j1, j2)
Generate random sequences inside sfcr_set()
Description
This function can only be used inside sfcr_set()
when generating variables.
It smartly guesses the length of the sfcr_baseline()
model or of the
sfcr_shock()
that it is inserted.
Usage
sfcr_random(.f, ...)
Arguments
.f |
This argument accepts three options: "rnorm", "rbinom", and "runif",
and implement the respective functions from the built-in |
... |
Extra arguments to be passed to the |
Author(s)
João Macalós
Examples
# Create a random normal series to pass along an endogenous series
# Example taken from model PC EXT 2.
sfcr_set(
Ra ~ sfcr_random("rnorm", mean=0, sd=0.05)
)
Plot Sankey's diagram representation of transactions-flow matrix
Description
Plot Sankey's diagram representation of transactions-flow matrix
Usage
sfcr_sankey(tfm, baseline, when = "start")
Arguments
tfm |
A transactions-flow matrix |
baseline |
A baseline model |
when |
When the Sankey's diagram should be evaluated?
|
Author(s)
João Macalós
Add scenarios to a sfcr
model.
Description
Add scenarios to a sfcr
model.
Usage
sfcr_scenario(
baseline,
scenario,
periods,
max_iter = 350,
tol = 1e-10,
method = "Broyden",
...
)
Arguments
baseline |
A model generated with the |
scenario |
Either a shock created with |
periods |
A number specifying the total number of periods of the model to be simulated. |
max_iter |
Maximum iterations allowed per period. |
tol |
Tolerance accepted to determine convergence. |
method |
The method to use to find a solution. Defaults to "Broyden". |
... |
Extra arguments to pass to |
Details
Add scenario(s) to a model generated with sfcr_baseline()
functions.
This function inherits the block structure from the steady state model. See
sfcr_baseline
for further details on the algorithms.
Author(s)
João Macalós, joaomacalos@gmail.com
See Also
Examples
eqs <- sfcr_set(
TX_s ~ TX_d,
YD ~ W * N_s - TX_s,
C_d ~ alpha1 * YD + alpha2 * H_h[-1],
H_h ~ YD - C_d + H_h[-1],
N_s ~ N_d,
N_d ~ Y / W,
C_s ~ C_d,
G_s ~ G_d,
Y ~ C_s + G_s,
TX_d ~ theta * W * N_s,
H_s ~ G_d - TX_d + H_s[-1]
)
external <- sfcr_set(G_d ~ 20, W ~ 1, alpha1 ~ 0.6, alpha2 ~ 0.4, theta ~ 0.2)
# t is set to 10 to run faster. A usual model should run at least 50 periods to find a steady state
steady_state <- sfcr_baseline(eqs, external, periods = 10)
# Increase G_d from 20 to 30 between periods 5 and 10
shock1 <- sfcr_shock(sfcr_set(G_d ~ 30), 5, 10)
sfcr_scenario(steady_state, scenario = list(shock1), 10)
# Increase W to 2, alpha2 to 0.5, and decrease theta to 0.15
shock2 <- sfcr_shock(
variables = sfcr_set(
W ~ 2,
alpha2 ~ 0.5,
theta ~ 0.15
),
start = 5,
end = 10)
sfcr_scenario(steady_state, list(shock2), 10)
Define the formulas of the model
Description
The sfcr_set()
function is used to create the lists of equations,
external variables, initial values, and also to modify the variables inside
the sfcr_shock()
function.
Usage
sfcr_set(..., exclude = NULL)
Arguments
... |
The formulas used to define the equations and external values of the system |
exclude |
One or more indices of equations to be excluded. The
correct indices can be found with |
Details
This function is a S3 generic that applicable to only two inputs: formula
and
sfcr_set
. It is used to create a new set of equations or to modify an existing
one.
Therefore, the equations must be written using the R formula syntax, i.e., the left-hand
side of each equation is separated from the right-hand side with a ~
("twiddle")
instead of a =
.
Furthermore, the sfcr_set()
function recognizes two symbols that are not
native to R language: [-1]
, and d()
.
If a variable defined with
sfcr_set()
is followed by[-1]
, it will be recognized as a lagged variable.If a variable is defined inside
d()
, thesfcr
engines will transform them into a first difference equation. For example,d(Hh)
is internally transformed into(Hh - Hh[-1])
.
Random variables can be created using the sfcr_random()
function. See
sfcr_random
for further details.
Author(s)
João Macalós
Examples
# Endogenous set
equations <- sfcr_set(
TXs ~ TXd,
YD ~ W * Ns - TXs,
Cd ~ alpha1 * YD + alpha2 * Hh[-1],
Hh ~ YD - Cd + Hh[-1],
Ns ~ Nd,
Nd ~ Y / W,
Cs ~ Cd,
Gs ~ Gd,
Y ~ Cs + Gs,
TXd ~ theta * W * Ns,
Hs ~ Gd - TXd + Hs[-1]
)
# Exogenous set
exogenous <- sfcr_set(alpha1 ~ 0.8, alpha2 ~ 0.15)
# Modify an existing set
equations2 <- sfcr_set(equations, Hh ~ Hh[-1] + d(Hs), exclude = 4)
# Add normal random variable
sfcr_set(Ra ~ sfcr_random("rnorm", mean=10, sd=2))
Get names of endogenous vars and their index
Description
The sfcr_set_index()
function takes a list of equations as its input and returns
a tibble containing the name of the variable on the left-hand side of the equations
and their position in the equations list.
Usage
sfcr_set_index(eqs)
Arguments
eqs |
A list of equations created with |
Details
This function aims to facilitate locating a specific equation in the list in order to modify the list of equations.
To add random variation to endogenous variables, use sfcr_random()
.
Author(s)
João Macalós
Create shock(s) to add to a sfcr_scenario()
.
Description
Create shock(s) to add to a sfcr_scenario()
.
Usage
sfcr_shock(variables, start, end)
Arguments
variables |
A It is possible to add exogenous series a shock instead of constant variables. However, the length of such series must be exactly the same as the period of the shock (i.e., the difference between start and end). |
start |
An integer indicating the period when the shock takes place. |
end |
An integer indicating the period when the shock ends. |
Author(s)
João Macalós, joaomacalos@gmail.com
Examples
sfcr_shock(
variables = sfcr_set(G_d ~ 30, W ~ 1.5),
start = 5,
end = 66)
sfcr_shock(
variables = sfcr_set(G_d ~ seq(30, 40, length.out=62)),
start = 5,
end = 66)
Validate a transactions-flow or balance-sheet matrix
Description
This function validates a transactions-flow or balance-sheet
matrix with the simulated data obtained with sfcr_baseline()
function
Usage
sfcr_validate(matrix, baseline, which, tol = 1, rtol = FALSE)
Arguments
matrix |
A transactions-flow or balance sheet matrix |
baseline |
A baseline model. |
which |
Either "bs" (balance-sheet matrix) or "tfm" (transactions-flow matrix). |
tol |
A numerical value indicating the absolute accepted discrepancy accepted to validate whether the rows and columns are equal to their expected values. |
rtol |
A logical value indicating whether relative discrepancies should be
evaluated. It defaults to |
Details
The relative discrepancy is calculated differently if we are dealing with a
transactions-flow matrix or with a balance-sheet matrix. If which
is set to tfm
,
the sum of the row/column is evaluated against the sum of the positive entries of that row/column.
For example, in a transactions-flow matrix with three entries in the "change in the stock of bills" row (-Delta (Bhd), + Delta (Bs), and + Delta (Bbd)), the discrepancy d = Delta Bs - Delta Bhd - Delta Bbd is evaluated against Delta Bs, i.e., the row is validated if d/Delta Bs < tol.
In a balance-sheet matrix, all the rows/columns that sum to zero are validated exactly as in a transactions-flow matrix. The exception to this rule is when there is a expected value. In this case, the discrepancy is evaluated as a proportion of the expected. value
To prevent unnecessary calculations, a absolute check with tolerance defined as 1e-3 is executed prior to this evaluation.
The absolute discrepancy set with tol
should be enough to validate
a stationary SFC Model.
Author(s)
João Macalós