| Title: | Simulate Stock-Flow Consistent Models |
| Version: | 0.2.3 |
| 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: | 2025-10-09 20:21:52 UTC; JouJo |
| Author: | Joao Macalos |
| Maintainer: | Joao Macalos <joaomacalos@gmail.com> |
| Repository: | CRAN |
| Date/Publication: | 2025-10-09 20:40:02 UTC |
Pipe operator
Description
Seemagrittr::%>% for details.
Usage
lhs %>% rhsAbort 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 referenceon 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 unexpectedbehavior 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 endof 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 unexpectedbehavior 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 atibble with the left-hand side andright-hand side as columns
Description
Split the formulae into atibble with the left-hand side andright-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 justcontinues with the baseline specification. It is useful to createa 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 aroundigraph functions)
Description
Find blocks of independent equations (wrapper aroundigraph 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 ortransactions-flow matrices
Description
Get numeric matrix for evaluation from balance-sheet ortransactions-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 evaluatethe expressions inside the Gauss Seidel algorithm
Description
Re-wrote the equations with the correct matrix syntax that will be used to evaluatethe 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-139for 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 cyclicalblocks 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 blocksof 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 usingnested for loops. At each round of iteration, the values calculatedare compared to the previous values. If the difference is belowa tolerance value set by the user, the round of calculations have convergedand 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 bemodified in place by the different solvers.
Author(s)
João Macalós
Newton-Raphson solver implemented withrootSolve::multiroot()
Description
Newton-Raphson solver implemented withrootSolve::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 cyclicalblocks of equations. It relies on themultiroot() function fromrootSolve.
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 verticaladding-up constraints
Description
Check that the portfolio matrix respect the horizontal and verticaladding-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
Thesfcr_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. |
hidden | Named object that identify the two variables that make the hidden equalityin the SFC model, e.g., |
max_iter | Maximum iterations allowed per period. |
.hidden_tol | 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 absolutecomparison 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 evaluatethe hidden equation or not. Defaults to |
... | Extra arguments to pass to |
Details
The output of asfcr_baseline() is asfcr_tbl. The only difference betweenasfcr_tbl and a standardtbl_df is that the former has two extra attributes:matrix andcall. Thematrix attribute, for example, can be accessed bycallingattributes(sfcr_sim_object)$matrix.It is possible to see, in the matrix, the number of iterations required to calculate eachblock of equations in the model.Thecall attribute shows the blocks of equations and preserve the call that are usedinternally.
Theequations,exogenous, andparameters arguments must be writtenwith the R formula syntax, i.e., the left-hand side of each item is separated to theright-hand side by a twiddle. Variables that represent lags of endogenous or exogenousvariables must be followed by[-1]. See examples for details on the syntax.
Before solving the system of equations, two consecutive depth-first searches identifyand order the blocks of independent equations in the system. The system is then solvedsequentially, i.e., the variables that depend only on lagged or exogenous values are evaluatedfirst, and then the variables that depends on these variables, etc. The solving algorithmsare only applied to the blocks of mutually dependent equations. The greatigraphpackage is used to implement the two consecutive depth-first searches.
Methods:
Thesfcr package provides three algorithms to solve the blocks of cyclical equations:the Gauss-Seidel algorithm, the Broyden algorithm, and the Newton-Raphson algorithm. Thedefault 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-Raphsonalgorithms.
The "Broyden" algorithm uses therootSolve::jacobian.full() function to get theinitial Jacobian matrix, and compiled code fromRcppArmadillo to invert thejacobians. 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 therootSolve::multiroot() function to solve the system.
Hidden equation:
One of the defining aspects of a SFC model is its water tight accounting. One wayto 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 absolutecomparison 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, therhtol argument ("relative hidden tolerance") must be set toTRUE in orderto perform a relative comparison. The relative comparison evaluates the numericaldiscrepancy in the hidden equation as a ratio of one of its elements. For example,ifhidden = c("Bbs" = "Bbd"), the hidden equation will be evaluated according tothe 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
Asfcr_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.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 statesfcr_baseline(equations = eqs, external = external, periods = 10)Create atbl_graph object blocks and cycles information
Description
Create atbl_graph object blocks and cycles information
Usage
sfcr_dag_blocks(equations)Arguments
equations | A |
Details
This function creates atbl_graph with information aboutthe blocks and cycles attached to it. This object can then be used toplot the DAG of the model.
Value
Atbl_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 atbl_graph with information aboutthe cycles attached to it. This object can then be used toplot the DAG of the model.
Value
Atbl_graph
Author(s)
João Macalós,joaomacalos@gmail.com
Create atbl_graph object with cycles information
Description
Create atbl_graph object with cycles information
Usage
sfcr_dag_cycles(equations)Arguments
equations | A |
Details
This function creates atbl_graph with information aboutthe cycles attached to it. This object can then be used toplot the DAG of the model.
Value
Atbl_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
Thesfcr_expand() function is a s3generic that takesa list of external objects and returns a expanded set of these lists.It has methods forsfcr_set objects and forsfcr_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 orshock variable. |
Details
There are two available methods for thesfcr_expand() function:
sfcr_set:Takes asfcr_setobject withexternal variables and createsa list of sets that inherits all the aspects of thexset suppliedbut set the values of thevariableto the each element ofvalue.The output is asfcr_mlt_setobject.sfcr_shock:Takes asfcr_shockobject and creates a list of shocks that inheritsall the aspects of thexshock but set thevaluesof thevariableto each element ofvalue. The output of thismethod is asfcr_mlt_shockobject.
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 asfcr_tbl object
Description
Get block structure of asfcr_tbl object
Usage
sfcr_get_blocks(sfcr_tbl)Arguments
sfcr_tbl | A |
Author(s)
João Macalós
Get Matrix form ofsfcr_tbl object
Description
Get Matrix form ofsfcr_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 thecolumn names that is going to be used as a reference tobuild the rows. They must be provided in the same orderas the |
... | Vectors that fill the rows of the matrix.The first element of each vectormust be the name of therow in the respective matrix. The remaining elements of the vectormust 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 userwishes to validate these matrices with the simulated data,please pay attention to the following details:
Transactions-flow Matrix:In the transactions-flow matrix, the
sumcolumn isgoing to be generated automatically by the validationfunction. Please do not add it by hand.Balance-sheet Matrix:In the balance-sheet matrix, it might be the case that somerows do not sum to zero. Therefore, the user must supplyby hand the non-zero values of the
sumcolumn.This column should always be the last column of the matrixand should always be named as "Sum". If there's no columnnamed as "Sum", it will be generated automatically by thevalidation function with all entries equal to zero.
Author(s)
João Macalós,joaomacalos@gmail.com
Examples
# Balance-sheet matrixbs_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 matrixtfm_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 ora transactions-flow matrix? here are two options: |
Details
This function takes a matrix as input and generate akableExtratable with math symbols displayed in latex style.
Note
This function converts the math expressions used to build thesfcr_matrixinto a latex format, but cannot add modifications to it. The user isinvited to explore the source code and thekableExtra package in order topersonalize his/her own matrices.
Author(s)
João Macalós
Examples
# Balance-sheet matrixbs_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
Thesfcr_multis() function is used to simulate multiple modelsat the same time, returning a list ofsfcr_tbls.
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
Thesfcr_multis() function takes anexpanded object andafixed to simulate multiple models that will share the contentoffixed but vary on theexpanded.
This function is ageneric, which means that its implementationdepends on the class of theexpanded argument.
The available methods for thesfcr_multis() function dependson theexpanded argument. There are three possible methods:
sfcr_mlt_set:When thesfcr_multis()takes ansfcr_mlt_setclassas the input ofexpanded, it must take a list of equations ofthesfcr_setclass as thefixedinput. This methodsimulates many baseline models that accept the same set of equationsand vary on the external variables supplied with theexpandedargument.sfcr_mlt_shock:When thesfcr_multis()takes ansfcr_mlt_shockclassas the input ofexpanded, it must also take an object ofsfcr_tblclass as the input offixed. It will simulatemultiple scenario models that takes the same baseline modeland diverge on the content of the multiple shocks provided with theexpandedargument that are applied to it.sfcr_mlt:When thesfcr_multis()function takes asfcr_mltclassobject as the input of theexpandedargument, asfcr_shockobject must be supplied with thefixedargument. This methodsimulates multiple scenario models that applies the same shock to avarying 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
Thesfcr_portfolio() function calculates a valid matrix of portfolioparameters by applying the symmetry condition and then filling the missingrows 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 symmetrycondition 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 theshare of assets in the net wealth and the impact of regular income to wealthratio must be calculated separately.
If supplied with insufficient parameters, the function will return amatrix with NA values.
This function requires at least (n^2 - n)/2 known parameters to find a valid portfoliomatrix, where n is the number of rows/columns. This is achieved by setting known parametersoutside the diagonal and not on symmetrical entries, i.e., not lambda12 and lambda21, forexample.
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 insidesfcr_set()
Description
This function can only be used insidesfcr_set() when generating variables.It smartly guesses the length of thesfcr_baseline() model or of thesfcr_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 asfcr model.
Description
Add scenarios to asfcr 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 withsfcr_baseline() functions.
This function inherits the block structure from the steady state model. Seesfcr_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 statesteady_state <- sfcr_baseline(eqs, external, periods = 10)# Increase G_d from 20 to 30 between periods 5 and 10shock1 <- 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.15shock2 <- 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
Thesfcr_set() function is used to create the lists of equations,external variables, initial values, and also to modify the variables insidethesfcr_shock() function.
Usage
sfcr_set(..., exclude = NULL)Arguments
... | The formulas used to define the equations and externalvalues of the system |
exclude | One or more indices of equations to be excluded. Thecorrect indices can be found with |
Details
This function is a S3 generic that applicable to only two inputs:formula andsfcr_set. It is used to create a new set of equations or to modify an existingone.
Therefore, the equations must be written using the R formula syntax, i.e., the left-handside of each equation is separated from the right-hand side with a~ ("twiddle")instead of a=.
Furthermore, thesfcr_set() function recognizes two symbols that are notnative to R language:[-1], andd().
If a variable defined with
sfcr_set()is followed by[-1], it willbe recognized as a lagged variable.If a variable is defined inside
d(), thesfcrengines will transformthem into a first difference equation. For example,d(Hh)is internally transformedinto(Hh - Hh[-1]).
Random variables can be created using thesfcr_random() function. Seesfcr_random for further details.
Author(s)
João Macalós
Examples
# Endogenous setequations <- 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 setexogenous <- sfcr_set(alpha1 ~ 0.8, alpha2 ~ 0.15)# Modify an existing setequations2 <- sfcr_set(equations, Hh ~ Hh[-1] + d(Hs), exclude = 4)# Add normal random variablesfcr_set(Ra ~ sfcr_random("rnorm", mean=10, sd=2))Get names of endogenous vars and their index
Description
Thesfcr_set_index() function takes a list of equations as its input and returnsa tibble containing the name of the variable on the left-hand side of the equationsand 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 tomodify the list of equations.
To add random variation to endogenous variables, usesfcr_random().
Author(s)
João Macalós
Create shock(s) to add to asfcr_scenario().
Description
Create shock(s) to add to asfcr_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-sheetmatrix with the simulated data obtained withsfcr_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 acceptedto validate whether the rows and columns are equal to their expected values. |
rtol | A logical value indicating whether relative discrepancies should beevaluated. It defaults to |
Details
The relative discrepancy is calculated differently if we are dealing with atransactions-flow matrix or with a balance-sheet matrix. Ifwhich is set totfm,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 Bbdis 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 asin 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 executedprior to this evaluation.
The absolute discrepancy set withtol should be enough to validatea stationary SFC Model.
Author(s)
João Macalós