Skip to content

pymetrix-ha

A plugin: a separate package

pymetrix-ha is a first-party plugin, installed on its own (not yet on PyPI: from a clone of the repository):

python -m pip install -e packages/pymetrix-ha

Heterogeneous-agent macro models for pymetrix (Krusell-Smith, one- and two-asset HANK) by the sequence-space Jacobian method (sequence-jacobian).

The names pymetrix_ha exports (its __all__), with their full documentation. Import them from the plugin: from pymetrix_ha import .... The plugin's README says more.

Public names

AR1 dataclass

AR1(rho: float, sd: float = 1.0)

A shock's path: sd * rho**t for t = 0, 1, ..., T-1, as deviations from the steady state (an unexpected shock of size sd at date 0 that decays at rate rho).

BlockError

Bases: ModelError

A block sequence-jacobian cannot use as written; the message names the block and what to write.

blocks_from_source

blocks_from_source(text: str, name: str = 'blocks', names: Mapping[str, Any] | None = None) -> dict[str, Any]

Run Python text that defines blocks, with its source registered for inspect (as a file would be), and return what it defined: ns = blocks_from_source(text); HAModel([ns["household"], ns["firm"]], ...). This is how blocks typed into a console or kept as text in a project work despite sequence-jacobian reading blocks from their source. names: values the text uses (arrays, say), given to it as globals. The text is run as code: only run text you trust.

check_blocks

check_blocks(blocks: Iterable[Any]) -> None

Each block's outputs, as the library read them from its return lines, are names: raise BlockError, naming the block and the function, when one is an expression (or a return split over lines).

HADecomposition dataclass

HADecomposition(output: str, shock: str, kind: str, parts: DataFrame, total: Series, model_name: str = '', direct: tuple[str, ...] = (), steady: Series | None = None, mass: Series | None = None, provenance: Any = None, notes: tuple[str, ...] = tuple())

An aggregate response split into parts that add up to it: by channel (kind="channel": the household block's inputs) or by group of households (kind="group").

  • parts: a DataFrame, a row per horizon (0 is the shock's period) and a column per part, as deviations from the steady state;
  • total: the general-equilibrium response the parts add up to (G times the shock's path);
  • direct: for channels, the parts that make the direct effect (the interest rates);
  • steady: for groups, each group's steady-state value of the output (its consumption) and mass, its share of households.

residual property

residual: Series

The total less the sum of the parts (zero to rounding).

to_frame

to_frame(view: str | None = None) -> DataFrame

The parts and the total, a row per horizon (view="relative": each group's response as a percentage of its own steady state; any other view by name, as the app's tabs show it).

table

table() -> Table

The parts and the total at each horizon, as deviations from the steady state.

summary

summary() -> Table

Each part's response on impact, at its largest and summed over the horizons shown, and its share of the total's sum; for channels, the direct effect and the indirect effects together too.

relative

relative() -> DataFrame

Each group's response as a percentage of its own steady-state value (groups only).

plot

plot() -> Any

The parts as stacked bars, the total as a line (as shock decompositions are drawn).

relative_plot

relative_plot() -> Any

Each group's response as a percentage of its own steady state: on impact, by group (bars), and over time (lines).

HALinear

HALinear(model: Any, steady: Any, G: Any, T: int, calls: dict[str, Any], seconds: float, caught: tuple[str, ...], printed: tuple[str, ...])

The model linearised at its steady state: the general-equilibrium Jacobians G for horizon T, mapping any path of the shocks to every output's path (Auclert, Bardóczy, Rognlie and Straub 2021). lin.jacobian("K", "Z") is one of them; lin.irf(40) gives the responses to each shock's AR(1) path as a pymetrix IRF; lin.summary() each response on impact and at its largest. provenance: the model, its grids, every option passed to the library and the steady state it was linearised at.

jacobian

jacobian(output: str, shock: str) -> ndarray

G[output][shock]: the T x T response of output at each date to shock at each date.

paths

paths(shocks: Mapping[str, Any] | None = None) -> dict[str, dict[str, ndarray]]

{shock: {output: path}}, each path of length T: G times the shock's path.

decompose

decompose(output: str = 'C', shock: str | None = None, periods: int = 40, block: str | None = None, path: Sequence[float] | None = None, direct: Sequence[str] | None = None) -> Any

output's response to shock (the first by default, along its AR(1), or path) split by channel: the household block's Jacobian on each of its inputs times that input's general-equilibrium path (an HADecomposition). direct: the channels that make the direct effect (by default the interest rates r, ra, rb), as Kaplan, Moll and Violante (2018) separate a monetary shock's direct effect from the indirect effects through income and transfers. The parts add up to G times the shock's path.

distribution_response

distribution_response(policy: str = 'c', shock: str | None = None, by: str = 'wealth', groups: int = 10, periods: int = 40, block: str | None = None, path: Sequence[float] | None = None) -> Any

The aggregate of policy (consumption by default) after shock, split by group of households: groups quantile groups of steady-state wealth (deciles by default; by="b" for one asset) or the income states (by="income"). An HADecomposition whose parts are each group's contribution, adding up to the aggregate response; relative() gives each as a percentage of the group's own steady state.

summary

summary() -> Table

Each response to each shock's path (its AR1), as deviations from the steady state: on impact, at its largest (in absolute value) with the horizon of that, and summed over the T periods of G.

irf

irf(periods: int = 40, shocks: Mapping[str, Any] | None = None, responses: Sequence[str] | None = None) -> Any

Impulse responses, as deviations from the steady state, to each shock's path: its AR1 (sd * rho**t) or a path given in shocks. A pymetrix IRF (values[h, response, shock], h = 0 to periods): the shocks' own paths first, then every output but the equilibrium targets (zero along the path).

HAModel

HAModel(blocks: Sequence[Any], calibration: Mapping[str, Any], steady_state: Mapping[str, Any], equilibrium: Mapping[str, Any], shocks: Mapping[str, AR1] | None = None, horizon: int = 300, name: str = '', options: HAOptions | None = None, steady_blocks: Sequence[Any] | None = None)

A heterogeneous-agent model: sequence-jacobian blocks (@sj.simple, @sj.het, or pymetrix_ha.simple and het, which check them), with

  • calibration: the parameters and grid sizes, by name;
  • steady_state: {"unknowns": {name: start, or (low, high) bounds}, "targets": {name: value}}, the calibration problem ("solver" too, to override options.solver);
  • equilibrium: {"unknowns": [...], "targets": [...]} for the dynamics (the targets are zero along a path);
  • shocks: {name: AR1(rho, sd)}, the exogenous inputs whose responses are asked for;
  • horizon: T, the length of the sequences (the Jacobians are T x T);
  • options: HAOptions, every tolerance and iteration limit;
  • steady_blocks: the blocks the calibration is solved on, when they differ from the model's (the HANK notebooks solve it with w = Z / mu in place of the Phillips curve). The model's own blocks are then evaluated at the calibration found, as the notebooks do (model.steady_state(calibration)).

The blocks are checked when the model is made: their outputs are names, and every input is calibrated, an unknown, a shock or another block's output.

household

household(block: str | None = None) -> Any

The het block called block (the model's first by default).

spec

spec() -> dict[str, Any]

The model as provenance records it: calibration, blocks (with a fingerprint of their source), the steady-state and equilibrium problems, the shocks and the horizon.

steady_state

steady_state() -> Any

The calibration solved: the unknowns found, the targets met, the household's policies and distribution (HASteadyState).

jacobian

jacobian(block: str | Any, inputs: Sequence[str], outputs: Sequence[str] | None = None, T: int | None = None, steady: Any = None) -> Any

One block's Jacobians at the steady state (Jacobians): for a het block, by the fake-news algorithm; ks.jacobian("household", ["r", "w"], T=5)["C", "r"] is the T x T response of consumption at each date to the interest rate at each date.

linearize

linearize(steady: Any = None, T: int | None = None, outputs: Sequence[str] | None = None) -> Any

The general-equilibrium Jacobians G at the steady state, for horizon T: every output's response at each date to each shock at each date (HALinear).

shock_paths

shock_paths(shocks: Mapping[str, Any] | None, T: int) -> dict[str, ndarray]

{name: path} of length T: an AR1's path, or a path given (deviations from the steady state, padded with zeros to T).

solve

solve(shocks: Mapping[str, Any] | None = None, nonlinear: bool = True, steady: Any = None, linear: Any = None, start: str = '2000Q1') -> Any

The perfect-foresight transition after an unexpected shock at date 0 (an "MIT shock"), back to the steady state (HATransition, a Solution). shocks: {name: AR1 or path} (the model's shocks by default); nonlinear=False gives the linear transition; start dates period 0 (the dates are labels: the model has no calendar). With nonlinear=True the linear transition is kept beside it, for comparison.

HAOptions dataclass

HAOptions(solver: str = '', ttol: float = 1e-12, ctol: float = 1e-09, backward_tol: float = 1e-08, backward_maxit: int = 5000, forward_tol: float = 1e-10, forward_maxit: int = 100000, h: float = 0.0001, twosided: bool = False, tol: float = 1e-08, maxit: int = 30)

Every setting pymetrix passes to sequence-jacobian. The defaults are the library's own (1.0.0), passed explicitly so that a new release of the library cannot change a result silently.

  • Steady state: solver ("": Brent's method, brentq, for one unknown given as bounds; else Powell's hybrid method, hybr, as the Krusell-Smith notebook uses), ttol (the targets), ctol (the consistency of a constrained solve), backward_tol and backward_maxit (the household's policies, by the endogenous grid method), forward_tol and forward_maxit (the distribution, by Young's method).
  • Jacobians: h, the step of the numerical derivatives inside the household block, one-sided unless twosided.
  • Transitions: tol, the largest absolute error in any target, and maxit Newton iterations.

HASteadyState

HASteadyState(model: Any, raw: Any, calls: dict[str, Any], evaluations: int, seconds: float, caught: tuple[str, ...], printed: tuple[str, ...])

The steady state: ss["K"], ss.values (every aggregate), ss.table(); ss.internals("household") and ss.distribution() for a het block's policies and distribution; ss.checks() for the distribution's mass and the aggregates against it. ss.raw is sequence-jacobian's own SteadyStateDict. provenance: the model, its grids, every option passed to the library and the solve (evaluations, the targets' residuals).

table

table() -> Table

Every aggregate: its value, and whether it was calibrated, solved for (an unknown), a target (with the value asked for and the residual) or computed by a block.

to_frame

to_frame(view: str | None = None) -> Any

The steady state's table as a DataFrame, or one of its views by name (to_frame("Distribution")).

internals

internals(block: str | None = None) -> dict[str, ndarray]

A het block's internals: its grids, Markov matrix, policies (a, c), backward variable and the distribution (D; Dbeg before the period's income shock), as arrays (income states by asset points).

distribution

distribution(block: str | None = None) -> ndarray

The stationary distribution of a het block (D): the mass at each income state and asset point.

summary

summary() -> Table

The steady state's table (table()): what every result answers.

wealth

wealth(block: str | None = None, by: str = 'wealth') -> ndarray

Each state's wealth (the sum of its assets), one asset's holding (by="b") or its income state (by="income"), as an array the shape of the distribution.

distribution_summary

distribution_summary(block: str | None = None, by: str = 'wealth') -> Table

The distribution of wealth (or of one asset, by="b"): its mean and median, the Gini coefficient, the shares of the bottom 50%, top 10% and top 1%, and the mass at the lowest point of each asset's grid (the borrowing limit; for the liquid asset, the hand-to-mouth). From the distribution D alone.

lorenz

lorenz(block: str | None = None, by: str = 'wealth') -> Any

The Lorenz curve of wealth (or one asset): a DataFrame of the share of households and the share of wealth they hold, households ordered by wealth.

plot

plot(block: str | None = None) -> Any

The distribution: the share of households with wealth up to each level (overall and by income state), and the Lorenz curve with the line of equality.

policy_plot

policy_plot(policy: str = 'c', block: str | None = None) -> Any

A policy (consumption c by default) against the first asset, a line per income state (with two assets, at the lowest point of the other's grid).

checks

checks() -> Table

For each het block: the distribution's total mass less 1 and its smallest entry; each aggregate output less the distribution's sum of its policy (A against the sum of D * a); and each target's residual.

HATransition dataclass

HATransition(frame: DataFrame, axes: tuple[Axis, ...], variables: Mapping[str, Variable] = dict(), flags: DataFrame | None = None, meta: DatasetMeta = DatasetMeta(), model: Any = None, scenario: Any = None, converged: bool = True, iterations: int = 0, provenance: Provenance | None = None, simulation: Any = None, convergence: DataFrame | None = None, linear: Any = None, errors: tuple[dict[str, float], ...] = (), steady_values: Any = None, nonlinear: bool = True)

Bases: Solution

The transition's paths in levels (a column per aggregate, a row per period from the shock's date), with:

  • deviations(): the same paths less the steady state;
  • linear: the linear transition (a Solution), beside a nonlinear one, for a check on size effects;
  • errors: each Newton iteration's largest absolute error in each target (the last is below the tolerance);
  • steady_values: the steady state the paths start from and return to.

deviations

deviations() -> Dataset

The paths less the steady state.

summary

summary() -> Table

Each path: its steady state, its deviation from it on impact (period 0, the shock's date), at its largest (in absolute value) with the period of that, and in the last period; for a nonlinear transition, the linear transition's largest deviation beside it.

plot_paths

plot_paths(variables: list[str] | None = None, periods: int = 40) -> Any

A panel per variable (the shocks and the main aggregates, by default): the path as a deviation from the steady state, with the linear transition dashed beside a nonlinear one, over the first periods.

het

het(exogenous: Any, policy: Any, backward: Any, backward_init: Callable[..., Any] | None = None, hetinputs: Iterable[Callable[..., Any]] | None = None, hetoutputs: Iterable[Callable[..., Any]] | None = None) -> Any

sequence_jacobian.het: a household block from its backward step (one step of the endogenous grid method, say), with the exogenous Markov matrix, the policy and the backward variable named.

Jacobians

Jacobians(matrices: Mapping[tuple[str, str], ndarray], outputs: Sequence[str], inputs: Sequence[str], T: int, about: str, provenance: Any = None, raw: Any = None)

T x T Jacobians by output and input: J["C", "r"][s, t] is the response of C at date s to a change in r at date t, at the steady state. J.table("C", "r") shows a corner; J.raw is the library's JacobianDict.

to_frame

to_frame(output: str, input: str) -> DataFrame

One Jacobian as a table: a row per date of the output, a column per date of the input.

table

table(output: str, input: str, size: int = 5) -> Table

The top-left size x size corner of one Jacobian.

simple

simple(f: Callable[..., Any]) -> Any

sequence_jacobian.simple: aggregate equations as a block (K(-1) for a lag, r(+1) for a lead). The outputs are the names on the function's last return line.

Plugin plumbing

What pymetrix's plugin loader reads (PLUGIN, register) and the plugin's version.

__version__ module-attribute

__version__ = '0.1.0a1'

PLUGIN module-attribute

PLUGIN = PluginInfo(name='pymetrix-ha', version=__version__, api='1.13', license='BSD-3-Clause', maintainer='Geoffrey Heenan', description='Heterogeneous-agent macro models by the sequence-space Jacobian method (sequence-jacobian): steady states, Jacobians, impulse responses and nonlinear transitions', requires={'sequence_jacobian': '>=1.0,<2', 'numba': '>=0.60'}, install='pip install "pymetrix[ha]"')

register

register() -> None

The entry point (pymetrix.plugins): the help topic. Importing the package registers it too; a second call does nothing.