API Documentation

Tools

High-level functions and classes for solving a wide variety of economic models. The “core” of HARK is a framework for “microeconomic” and “macroeconomic” models. A micro model concerns the dynamic optimization problem for some type of agents, where agents take the inputs to their problem as exogenous. A macro model adds an additional layer, endogenizing some of the inputs to the micro problem by finding a general equilibrium dynamic rule.

class HARK.core.AgentType(solution_terminal=None, cycles=1, time_flow=True, pseudo_terminal=True, tolerance=1e-06, seed=0, **kwds)

A superclass for economic agents in the HARK framework. Each model should specify its own subclass of AgentType, inheriting its methods and overwriting as necessary. Critically, every subclass of AgentType should define class- specific static values of the attributes time_vary and time_inv as lists of strings. Each element of time_vary is the name of a field in AgentSubType that varies over time in the model. Each element of time_inv is the name of a field in AgentSubType that is constant over time in the model. The string ‘solveOnePeriod’ should appear in exactly one of these lists, depending on whether the same solution method is used in all periods of the model.

addToTimeInv(*params)

Adds any number of parameters to time_inv for this instance.

Parameters:params (string) – Any number of strings naming attributes to be added to time_inv
Returns:
Return type:None
addToTimeVary(*params)

Adds any number of parameters to time_vary for this instance.

Parameters:params (string) – Any number of strings naming attributes to be added to time_vary
Returns:
Return type:None
checkElementsOfTimeVaryAreLists()

A method to check that elements of time_vary are lists.

checkRestrictions()

A method to check that various restrictions are met for the model class.

clearHistory()

Clears the histories of the attributes named in self.track_vars.

Parameters:None
Returns:
Return type:None
delFromTimeInv(*params)

Removes any number of parameters from time_inv for this instance.

Parameters:params (string) – Any number of strings naming attributes to be removed from time_inv
Returns:
Return type:None
delFromTimeVary(*params)

Removes any number of parameters from time_vary for this instance.

Parameters:params (string) – Any number of strings naming attributes to be removed from time_vary
Returns:
Return type:None
getControls()

Gets values of control variables for the current period, probably by using current states. Does nothing by default, but can be overwritten by subclasses of AgentType.

Parameters:None
Returns:
Return type:None
getMortality()

Simulates mortality or agent turnover according to some model-specific rules named simDeath and simBirth (methods of an AgentType subclass). simDeath takes no arguments and returns a Boolean array of size AgentCount, indicating which agents of this type have “died” and must be replaced. simBirth takes such a Boolean array as an argument and generates initial post-decision states for those agent indices.

Parameters:None
Returns:
Return type:None
getPostStates()

Gets values of post-decision state variables for the current period, probably by current states and controls and maybe market-level events or shock variables. Does nothing by default, but can be overwritten by subclasses of AgentType.

Parameters:None
Returns:
Return type:None
getShocks()

Gets values of shock variables for the current period. Does nothing by default, but can be overwritten by subclasses of AgentType.

Parameters:None
Returns:
Return type:None
getStates()

Gets values of state variables for the current period, probably by using post-decision states from last period, current period shocks, and maybe market-level events. Does nothing by default, but can be overwritten by subclasses of AgentType.

Parameters:None
Returns:
Return type:None
initializeSim()

Prepares this AgentType for a new simulation. Resets the internal random number generator, makes initial states for all agents (using simBirth), clears histories of tracked variables.

Parameters:None
Returns:
Return type:None
makeShockHistory()

Makes a pre-specified history of shocks for the simulation. Shock variables should be named in self.shock_vars, a list of strings that is subclass-specific. This method runs a subset of the standard simulation loop by simulating only mortality and shocks; each variable named in shock_vars is stored in a T_sim x AgentCount array in an attribute of self named X_hist. Automatically sets self.read_shocks to True so that these pre-specified shocks are used for all subsequent calls to simulate().

Parameters:None
Returns:
Return type:None
postSolve()

A method that is run immediately after the model is solved, to finalize the solution in some way. Does nothing here.

Parameters:none
Returns:
Return type:none
preSolve()

A method that is run immediately before the model is solved, to check inputs or to prepare the terminal solution, perhaps.

Parameters:none
Returns:
Return type:none
readShocks()

Reads values of shock variables for the current period from history arrays. For each var- iable X named in self.shock_vars, this attribute of self is set to self.X_hist[self.t_sim,:].

This method is only ever called if self.read_shocks is True. This can be achieved by using the method makeShockHistory() (or manually after storing a “handcrafted” shock history).

Parameters:None
Returns:
Return type:None
resetRNG()

Reset the random number generator for this type.

Parameters:none
Returns:
Return type:none
simBirth(which_agents)

Makes new agents for the simulation. Takes a boolean array as an input, indicating which agent indices are to be “born”. Does nothing by default, must be overwritten by a subclass.

Parameters:which_agents (np.array(Bool)) – Boolean array of size self.AgentCount indicating which agents should be “born”.
Returns:
Return type:None
simDeath()

Determines which agents in the current population “die” or should be replaced. Takes no inputs, returns a Boolean array of size self.AgentCount, which has True for agents who die and False for those that survive. Returns all False by default, must be overwritten by a subclass to have replacement events.

Parameters:None
Returns:who_dies – Boolean array of size self.AgentCount indicating which agents die and are replaced.
Return type:np.array
simOnePeriod()

Simulates one period for this type. Calls the methods getMortality(), getShocks() or readShocks, getStates(), getControls(), and getPostStates(). These should be defined for AgentType subclasses, except getMortality (define its components simDeath and simBirth instead) and readShocks.

Parameters:None
Returns:
Return type:None
simulate(sim_periods=None)

Simulates this agent type for a given number of periods. Defaults to self.T_sim if no input. Records histories of attributes named in self.track_vars in attributes named varname_hist.

Parameters:None
Returns:
Return type:None
solve(verbose=False)

Solve the model for this instance of an agent type by backward induction. Loops through the sequence of one period problems, passing the solution from period t+1 to the problem for period t.

Parameters:verbose (boolean) – If True, solution progress is printed to screen.
Returns:
Return type:none
timeFlip()

Reverse the flow of time for this instance.

Parameters:none
Returns:
Return type:none
timeFwd()

Make time flow forward for this instance.

Parameters:none
Returns:
Return type:none
timeReport()

Report to the user the direction that time is currently “flowing” for this instance. Only exists as a reminder of how time_flow works.

Parameters:none
Returns:
Return type:none
timeRev()

Make time flow backward for this instance.

Parameters:none
Returns:
Return type:none
class HARK.core.HARKobject

A superclass for object classes in HARK. Comes with two useful methods: a generic/universal distance method and an attribute assignment method.

assignParameters(**kwds)

Assign an arbitrary number of attributes to this agent.

Parameters:**kwds (keyword arguments) – Any number of keyword arguments of the form key=value. Each value will be assigned to the attribute named in self.
Returns:
Return type:none
distance(other)

A generic distance method, which requires the existence of an attribute called distance_criteria, giving a list of strings naming the attributes to be considered by the distance metric.

Parameters:other (object) – Another object to compare this instance to.
Returns:(unnamed) – The distance between this object and another, using the “universal distance” metric.
Return type:float
getAvg(varname, **kwds)

Calculates the average of an attribute of this instance. Returns NaN if no such attribute.

Parameters:varname (string) – The name of the attribute whose average is to be calculated. This attribute must be an np.array or other class compatible with np.mean.
Returns:avg – The average of this attribute. Might be an array if the axis keyword is passed.
Return type:float or np.array
class HARK.core.Market(agents=[], sow_vars=[], reap_vars=[], const_vars=[], track_vars=[], dyn_vars=[], millRule=None, calcDynamics=None, act_T=1000, tolerance=1e-06)

A superclass to represent a central clearinghouse of information. Used for dynamic general equilibrium models to solve the “macroeconomic” model as a layer on top of the “microeconomic” models of one or more AgentTypes.

cultivate()

Has each AgentType in agents perform their marketAction method, using variables sown from the market (and maybe also “private” variables). The marketAction method should store new results in attributes named in reap_vars to be reaped later.

Parameters:none
Returns:
Return type:none
makeHistory()

Runs a loop of sow–>cultivate–>reap–>mill act_T times, tracking the evolution of variables X named in track_vars in attributes named X_hist.

Parameters:none
Returns:
Return type:none
mill()

Processes the variables collected from agents using the function millRule, storing the results in attributes named in aggr_sow.

Parameters:none
Returns:
Return type:none
reap()

Collects attributes named in reap_vars from each AgentType in the market, storing them in respectively named attributes of self.

Parameters:none
Returns:
Return type:none
reset()

Reset the state of the market (attributes in sow_vars, etc) to some user-defined initial state, and erase the histories of tracked variables.

Parameters:none
Returns:
Return type:none
solve()

“Solves” the market by finding a “dynamic rule” that governs the aggregate market state such that when agents believe in these dynamics, their actions collectively generate the same dynamic rule.

Parameters:None
Returns:
Return type:None
solveAgents()

Solves the microeconomic problem for all AgentTypes in this market.

Parameters:None
Returns:
Return type:None
sow()

Distributes attrributes named in sow_vars from self to each AgentType in the market, storing them in respectively named attributes.

Parameters:none
Returns:
Return type:none
store()

Record the current value of each variable X named in track_vars in an attribute named X_hist.

Parameters:none
Returns:
Return type:none
updateDynamics()

Calculates a new “aggregate dynamic rule” using the history of variables named in track_vars, and distributes this rule to AgentTypes in agents.

Parameters:none
Returns:dynamics – The new “aggregate dynamic rule” that agents believe in and act on. Should have attributes named in dyn_vars.
Return type:instance
class HARK.core.Solution

A superclass for representing the “solution” to a single period problem in a dynamic microeconomic model.

NOTE: This can be deprecated now that HARKobject exists, but this requires replacing each instance of Solution with HARKobject in the other modules.

HARK.core.copy_module(target_path, my_directory_full_path, my_module)

Helper function for copy_module_to_local(). Provides the actual copy functionality, with highly cautious safeguards against copying over important things.

Parameters:
  • target_path (string) – String, file path to target location
  • my_directory_full_path (string) – String, full pathname to this file’s directory
  • my_module (string) – String, name of the module to copy
Returns:

Return type:

none

HARK.core.copy_module_to_local(full_module_name)

This function contains simple code to copy a submodule to a location on your hard drive, as specified by you. The purpose of this code is to provide users with a simple way to access a copy of code that usually sits deep in the Econ-ARK package structure, for purposes of tinkering and experimenting directly. This is meant to be a simple way to explore HARK code. To interact with the codebase under active development, please refer to the documentation under github.com/econ-ark/HARK/

To execute, do the following on the Python command line:

from HARK.core import copy_module_to_local copy_module_to_local(“FULL-HARK-MODULE-NAME-HERE”)

For example, if you want SolvingMicroDSOPs you would enter

from HARK.core import copy_module_to_local copy_module_to_local(“HARK.SolvingMicroDSOPs”)
HARK.core.distanceMetric(thing_A, thing_B)

A “universal distance” metric that can be used as a default in many settings.

Parameters:
  • thing_A (object) – A generic object.
  • thing_B (object) – Another generic object.
  • Returns
  • ------------
  • distance (float) – The “distance” between thing_A and thing_B.
HARK.core.solveAgent(agent, verbose)

Solve the dynamic model for one agent type. This function iterates on “cycles” of an agent’s model either a given number of times or until solution convergence if an infinite horizon model is used (with agent.cycles = 0).

Parameters:
  • agent (AgentType) – The microeconomic AgentType whose dynamic problem is to be solved.
  • verbose (boolean) – If True, solution progress is printed to screen (when cycles != 1).
Returns:

solution – A list of solutions to the one period problems that the agent will encounter in his “lifetime”. Returns in reverse chronological order.

Return type:

[Solution]

HARK.core.solveOneCycle(agent, solution_last)

Solve one “cycle” of the dynamic model for one agent type. This function iterates over the periods within an agent’s cycle, updating the time-varying parameters and passing them to the single period solver(s).

Parameters:
  • agent (AgentType) – The microeconomic AgentType whose dynamic problem is to be solved.
  • solution_last (Solution) – A representation of the solution of the period that comes after the end of the sequence of one period problems. This might be the term- inal period solution, a “pseudo terminal” solution, or simply the solution to the earliest period from the succeeding cycle.
Returns:

solution_cycle – A list of one period solutions for one “cycle” of the AgentType’s microeconomic model. Returns in reverse chronological order.

Return type:

[Solution]

Functions for working with the discrete-continuous EGM (DCEGM) algorithm as described in “The endogenous grid method for discrete-continuous dynamic choice models with (or without) taste shocks” by Iskhakov et al. (2016) [https://doi.org/10.3982/QE643 and ijrsDCEGM2017 in our Zotero]

Example can be found in https://github.com/econ-ark/DemARK/blob/master/notebooks/DCEGM-Upper-Envelope.ipynb

HARK.dcegm.calcMultilineEnvelope(M, C, V_T, commonM)

Do the envelope step of the DCEGM algorithm. Takes in market ressources, consumption levels, and inverse values from the EGM step. These represent (m, c) pairs that solve the necessary first order conditions. This function calculates the optimal (m, c, v_t) pairs on the commonM grid.

Parameters:
  • M (np.array) – market ressources from EGM step
  • C (np.array) – consumption from EGM step
  • V_T (np.array) – transformed values at the EGM grid
  • commonM (np.array) – common grid to do upper envelope calculations on
HARK.dcegm.calcSegments(x, v)

Find index vectors rise and fall such that rise holds the indeces i such that x[i+1]>x[i] and fall holds indeces j such that either - x[j+1] < x[j] or, - x[j]>x[j-1] and v[j]<v[j-1].

The vectors are essential to the DCEGM algorithm, as they definite the relevant intervals to be used to construct the upper envelope of potential solutions to the (necessary) first order conditions.

Parameters:
  • x (np.ndarray) – array of points where v is evaluated
  • v (np.ndarray) – array of values of some function of x
Returns:

  • rise (np.ndarray) – see description above
  • fall (np.ndarray) – see description above

Functions for estimating structural models, including optimization methods and bootstrapping tools.

HARK.estimation.bootstrapSampleFromData(data, weights=None, seed=0)

Samples rows from the input array of data, generating a new data array with an equal number of rows (records). Rows are drawn with equal probability by default, but probabilities can be specified with weights (must sum to 1).

Parameters:
  • data (np.array) – An array of data, with each row representing a record.
  • weights (np.array) – A weighting array with length equal to data.shape[0].
  • seed (int) – A seed for the random number generator.
Returns:

new_data – A resampled version of input data.

Return type:

np.array

HARK.estimation.minimizeNelderMead(objectiveFunction, parameter_guess, verbose=False, which_vars=None, **kwargs)

Minimizes the objective function using the Nelder-Mead simplex algorithm, starting from an initial parameter guess.

Parameters:
  • objectiveFunction (function) – The function to be minimized. It should take only a single argument, which should be a list representing the parameters to be estimated.
  • parameter_guess ([float]) – A starting point for the Nelder-Mead algorithm, which must be a valid input for objectiveFunction.
  • which_vars (np.array or None) – Array of booleans indicating which parameters should be estimated. When not provided, estimation is performed on all parameters.
  • verbose (boolean) – A flag for the amount of output to print.
Returns:

xopt – The values that minimize objectiveFunction.

Return type:

[float]

HARK.estimation.minimizePowell(objectiveFunction, parameter_guess, verbose=False)

Minimizes the objective function using a derivative-free Powell algorithm, starting from an initial parameter guess.

Parameters:
  • objectiveFunction (function) – The function to be minimized. It should take only a single argument, which should be a list representing the parameters to be estimated.
  • parameter_guess ([float]) – A starting point for the Powell algorithm, which must be a valid input for objectiveFunction.
  • verbose (boolean) – A flag for the amount of output to print.
Returns:

xopt – The values that minimize objectiveFunction.

Return type:

[float]

Custom interpolation methods for representing approximations to functions. It also includes wrapper classes to enforce standard methods across classes. Each interpolation class must have a distance() method that compares itself to another instance; this is used in HARK.core’s solve() method to check for solution convergence. The interpolator classes currently in this module inherit their distance method from HARKobject.

class HARK.interpolation.BilinearInterp(f_values, x_list, y_list, xSearchFunc=None, ySearchFunc=None)

Bilinear full (or tensor) grid interpolation of a function f(x,y).

class HARK.interpolation.BilinearInterpOnInterp1D(xInterpolators, y_values, z_values)

A 3D interpolator that bilinearly interpolates among a list of lists of 1D interpolators.

class HARK.interpolation.BilinearInterpOnInterp2D(wxInterpolators, y_values, z_values)

A 4D interpolation method that bilinearly interpolates among “layers” of arbitrary 2D interpolations. Useful for models with two endogenous state variables and two exogenous state variables when solving with the endogenous grid method. NOTE: should not be used if an exogenous 4D grid is used, will be significantly slower than QuadlinearInterp.

class HARK.interpolation.ConstantFunction(value)

A class for representing trivial functions that return the same real output for any input. This is convenient for models where an object might be a (non-trivial) function, but in some variations that object is just a constant number. Rather than needing to make a (Bi/Tri/Quad)- LinearInterpolation with trivial state grids and the same f_value in every entry, ConstantFunction allows the user to quickly make a constant/trivial function. This comes up, e.g., in models with endogenous pricing of insurance contracts; a contract’s premium might depend on some state variables of the individual, but in some variations the premium of a contract is just a number.

derivative(*args)

Evaluate the derivative of the function. The first input must exist and should be an array. Returns an array of identical shape to args[0] (if it exists). This is an array of zeros.

derivativeW(*args)

Evaluate the derivative of the function. The first input must exist and should be an array. Returns an array of identical shape to args[0] (if it exists). This is an array of zeros.

derivativeX(*args)

Evaluate the derivative of the function. The first input must exist and should be an array. Returns an array of identical shape to args[0] (if it exists). This is an array of zeros.

derivativeXX(*args)

Evaluate the derivative of the function. The first input must exist and should be an array. Returns an array of identical shape to args[0] (if it exists). This is an array of zeros.

derivativeY(*args)

Evaluate the derivative of the function. The first input must exist and should be an array. Returns an array of identical shape to args[0] (if it exists). This is an array of zeros.

derivativeZ(*args)

Evaluate the derivative of the function. The first input must exist and should be an array. Returns an array of identical shape to args[0] (if it exists). This is an array of zeros.

class HARK.interpolation.CubicInterp(x_list, y_list, dydx_list, intercept_limit=None, slope_limit=None, lower_extrap=False)

An interpolating function using piecewise cubic splines. Matches level and slope of 1D function at gridpoints, smoothly interpolating in between. Extrapolation above highest gridpoint approaches a limiting linear function if desired (linear extrapolation also enabled.)

class HARK.interpolation.Curvilinear2DInterp(f_values, x_values, y_values)

A 2D interpolation method for curvilinear or “warped grid” interpolation, as in White (2015). Used for models with two endogenous states that are solved with the endogenous grid method.

findCoords(x, y, x_pos, y_pos)

Calculates the relative coordinates (alpha,beta) for each point (x,y), given the sectors (x_pos,y_pos) in which they reside. Only called as a subroutine of __call__().

Parameters:
  • x (np.array) – Values whose sector should be found.
  • y (np.array) – Values whose sector should be found. Should be same size as x.
  • x_pos (np.array) – Sector x-coordinates for each point in (x,y), of the same size.
  • y_pos (np.array) – Sector y-coordinates for each point in (x,y), of the same size.
Returns:

  • alpha (np.array) – Relative “horizontal” position of the input in their respective sectors.
  • beta (np.array) – Relative “vertical” position of the input in their respective sectors.

findSector(x, y)

Finds the quadrilateral “sector” for each (x,y) point in the input. Only called as a subroutine of _evaluate().

Parameters:
  • x (np.array) – Values whose sector should be found.
  • y (np.array) – Values whose sector should be found. Should be same size as x.
Returns:

  • x_pos (np.array) – Sector x-coordinates for each point of the input, of the same size.
  • y_pos (np.array) – Sector y-coordinates for each point of the input, of the same size.

updatePolarity()

Fills in the polarity attribute of the interpolation, determining whether the “plus” (True) or “minus” (False) solution of the system of equations should be used for each sector. Needs to be called in __init__.

Parameters:none
Returns:
Return type:none
class HARK.interpolation.HARKinterpolator1D

A wrapper class for 1D interpolation methods in HARK.

derivative(x)

Evaluates the derivative of the interpolated function at the given input.

Parameters:x (np.array or float) – Real values to be evaluated in the interpolated function.
Returns:dydx – The interpolated function’s first derivative evaluated at x: dydx = f’(x), with the same shape as x.
Return type:np.array or float
eval_with_derivative(x)

Evaluates the interpolated function and its derivative at the given input.

Parameters:x (np.array or float) – Real values to be evaluated in the interpolated function.
Returns:
  • y (np.array or float) – The interpolated function evaluated at x: y = f(x), with the same shape as x.
  • dydx (np.array or float) – The interpolated function’s first derivative evaluated at x: dydx = f’(x), with the same shape as x.
class HARK.interpolation.HARKinterpolator2D

A wrapper class for 2D interpolation methods in HARK.

derivativeX(x, y)

Evaluates the partial derivative of interpolated function with respect to x (the first argument) at the given input.

Parameters:
  • x (np.array or float) – Real values to be evaluated in the interpolated function.
  • y (np.array or float) – Real values to be evaluated in the interpolated function; must be the same size as x.
Returns:

dfdx – The derivative of the interpolated function with respect to x, eval- uated at x,y: dfdx = f_x(x,y), with the same shape as x and y.

Return type:

np.array or float

derivativeY(x, y)

Evaluates the partial derivative of interpolated function with respect to y (the second argument) at the given input.

Parameters:
  • x (np.array or float) – Real values to be evaluated in the interpolated function.
  • y (np.array or float) – Real values to be evaluated in the interpolated function; must be the same size as x.
Returns:

dfdy – The derivative of the interpolated function with respect to y, eval- uated at x,y: dfdx = f_y(x,y), with the same shape as x and y.

Return type:

np.array or float

class HARK.interpolation.HARKinterpolator3D

A wrapper class for 3D interpolation methods in HARK.

derivativeX(x, y, z)

Evaluates the partial derivative of the interpolated function with respect to x (the first argument) at the given input.

Parameters:
  • x (np.array or float) – Real values to be evaluated in the interpolated function.
  • y (np.array or float) – Real values to be evaluated in the interpolated function; must be the same size as x.
  • z (np.array or float) – Real values to be evaluated in the interpolated function; must be the same size as x.
Returns:

dfdx – The derivative with respect to x of the interpolated function evaluated at x,y,z: dfdx = f_x(x,y,z), with the same shape as x, y, and z.

Return type:

np.array or float

derivativeY(x, y, z)

Evaluates the partial derivative of the interpolated function with respect to y (the second argument) at the given input.

Parameters:
  • x (np.array or float) – Real values to be evaluated in the interpolated function.
  • y (np.array or float) – Real values to be evaluated in the interpolated function; must be the same size as x.
  • z (np.array or float) – Real values to be evaluated in the interpolated function; must be the same size as x.
Returns:

dfdy – The derivative with respect to y of the interpolated function evaluated at x,y,z: dfdy = f_y(x,y,z), with the same shape as x, y, and z.

Return type:

np.array or float

derivativeZ(x, y, z)

Evaluates the partial derivative of the interpolated function with respect to z (the third argument) at the given input.

Parameters:
  • x (np.array or float) – Real values to be evaluated in the interpolated function.
  • y (np.array or float) – Real values to be evaluated in the interpolated function; must be the same size as x.
  • z (np.array or float) – Real values to be evaluated in the interpolated function; must be the same size as x.
Returns:

dfdz – The derivative with respect to z of the interpolated function evaluated at x,y,z: dfdz = f_z(x,y,z), with the same shape as x, y, and z.

Return type:

np.array or float

class HARK.interpolation.HARKinterpolator4D

A wrapper class for 4D interpolation methods in HARK.

derivativeW(w, x, y, z)

Evaluates the partial derivative with respect to w (the first argument) of the interpolated function at the given input.

Parameters:
  • w (np.array or float) – Real values to be evaluated in the interpolated function.
  • x (np.array or float) – Real values to be evaluated in the interpolated function; must be the same size as w.
  • y (np.array or float) – Real values to be evaluated in the interpolated function; must be the same size as w.
  • z (np.array or float) – Real values to be evaluated in the interpolated function; must be the same size as w.
Returns:

dfdw – The derivative with respect to w of the interpolated function eval- uated at w,x,y,z: dfdw = f_w(w,x,y,z), with the same shape as inputs.

Return type:

np.array or float

derivativeX(w, x, y, z)

Evaluates the partial derivative with respect to x (the second argument) of the interpolated function at the given input.

Parameters:
  • w (np.array or float) – Real values to be evaluated in the interpolated function.
  • x (np.array or float) – Real values to be evaluated in the interpolated function; must be the same size as w.
  • y (np.array or float) – Real values to be evaluated in the interpolated function; must be the same size as w.
  • z (np.array or float) – Real values to be evaluated in the interpolated function; must be the same size as w.
Returns:

dfdx – The derivative with respect to x of the interpolated function eval- uated at w,x,y,z: dfdx = f_x(w,x,y,z), with the same shape as inputs.

Return type:

np.array or float

derivativeY(w, x, y, z)

Evaluates the partial derivative with respect to y (the third argument) of the interpolated function at the given input.

Parameters:
  • w (np.array or float) – Real values to be evaluated in the interpolated function.
  • x (np.array or float) – Real values to be evaluated in the interpolated function; must be the same size as w.
  • y (np.array or float) – Real values to be evaluated in the interpolated function; must be the same size as w.
  • z (np.array or float) – Real values to be evaluated in the interpolated function; must be the same size as w.
Returns:

dfdy – The derivative with respect to y of the interpolated function eval- uated at w,x,y,z: dfdy = f_y(w,x,y,z), with the same shape as inputs.

Return type:

np.array or float

derivativeZ(w, x, y, z)

Evaluates the partial derivative with respect to z (the fourth argument) of the interpolated function at the given input.

Parameters:
  • w (np.array or float) – Real values to be evaluated in the interpolated function.
  • x (np.array or float) – Real values to be evaluated in the interpolated function; must be the same size as w.
  • y (np.array or float) – Real values to be evaluated in the interpolated function; must be the same size as w.
  • z (np.array or float) – Real values to be evaluated in the interpolated function; must be the same size as w.
Returns:

dfdz – The derivative with respect to z of the interpolated function eval- uated at w,x,y,z: dfdz = f_z(w,x,y,z), with the same shape as inputs.

Return type:

np.array or float

class HARK.interpolation.IdentityFunction(i_dim=0, n_dims=1)

A fairly trivial interpolator that simply returns one of its arguments. Useful for avoiding numeric error in extreme cases.

derivative(*args)

Returns the derivative of the function with respect to the first dimension.

derivativeW(*args)

Returns the derivative of the function with respect to the W dimension. This should only exist when n_dims >= 4.

derivativeX(*args)

Returns the derivative of the function with respect to the X dimension. This is the first input whenever n_dims < 4 and the second input otherwise.

derivativeY(*args)

Returns the derivative of the function with respect to the Y dimension. This is the second input whenever n_dims < 4 and the third input otherwise.

derivativeZ(*args)

Returns the derivative of the function with respect to the Z dimension. This is the third input whenever n_dims < 4 and the fourth input otherwise.

class HARK.interpolation.LinearInterp(x_list, y_list, intercept_limit=None, slope_limit=None, lower_extrap=False)

A “from scratch” 1D linear interpolation class. Allows for linear or decay extrapolation (approaching a limiting linear function from below).

class HARK.interpolation.LinearInterpOnInterp1D(xInterpolators, y_values)

A 2D interpolator that linearly interpolates among a list of 1D interpolators.

class HARK.interpolation.LinearInterpOnInterp2D(xyInterpolators, z_values)

A 3D interpolation method that linearly interpolates between “layers” of arbitrary 2D interpolations. Useful for models with two endogenous state variables and one exogenous state variable when solving with the endogenous grid method. NOTE: should not be used if an exogenous 3D grid is used, will be significantly slower than TrilinearInterp.

class HARK.interpolation.LowerEnvelope(*functions)

The lower envelope of a finite set of 1D functions, each of which can be of any class that has the methods __call__, derivative, and eval_with_derivative. Generally: it combines HARKinterpolator1Ds.

class HARK.interpolation.LowerEnvelope2D(*functions)

The lower envelope of a finite set of 2D functions, each of which can be of any class that has the methods __call__, derivativeX, and derivativeY. Generally: it combines HARKinterpolator2Ds.

class HARK.interpolation.LowerEnvelope3D(*functions)

The lower envelope of a finite set of 3D functions, each of which can be of any class that has the methods __call__, derivativeX, derivativeY, and derivativeZ. Generally: it combines HARKinterpolator2Ds.

class HARK.interpolation.QuadlinearInterp(f_values, w_list, x_list, y_list, z_list, wSearchFunc=None, xSearchFunc=None, ySearchFunc=None, zSearchFunc=None)

Quadlinear full (or tensor) grid interpolation of a function f(w,x,y,z).

class HARK.interpolation.TrilinearInterp(f_values, x_list, y_list, z_list, xSearchFunc=None, ySearchFunc=None, zSearchFunc=None)

Trilinear full (or tensor) grid interpolation of a function f(x,y,z).

class HARK.interpolation.TrilinearInterpOnInterp1D(wInterpolators, x_values, y_values, z_values)

A 4D interpolator that trilinearly interpolates among a list of lists of 1D interpolators.

class HARK.interpolation.UpperEnvelope(*functions)

The upper envelope of a finite set of 1D functions, each of which can be of any class that has the methods __call__, derivative, and eval_with_derivative. Generally: it combines HARKinterpolator1Ds.

class HARK.interpolation.VariableLowerBoundFunc2D(func, lowerBound)

A class for representing a function with two real inputs whose lower bound in the first input depends on the second input. Useful for managing curved natural borrowing constraints, as occurs in the persistent shocks model.

derivativeX(x, y)

Evaluate the first derivative with respect to x of the function at given state space points.

Parameters:
  • x (np.array) – First input values.
  • y (np.array) – Second input values; should be of same shape as x.
Returns:

dfdx_out – First derivative of function with respect to the first input, evaluated at (x,y), of same shape as inputs.

Return type:

np.array

derivativeY(x, y)

Evaluate the first derivative with respect to y of the function at given state space points.

Parameters:
  • x (np.array) – First input values.
  • y (np.array) – Second input values; should be of same shape as x.
Returns:

dfdy_out – First derivative of function with respect to the second input, evaluated at (x,y), of same shape as inputs.

Return type:

np.array

class HARK.interpolation.VariableLowerBoundFunc3D(func, lowerBound)

A class for representing a function with three real inputs whose lower bound in the first input depends on the second input. Useful for managing curved natural borrowing constraints.

derivativeX(x, y, z)

Evaluate the first derivative with respect to x of the function at given state space points.

Parameters:
  • x (np.array) – First input values.
  • y (np.array) – Second input values; should be of same shape as x.
  • z (np.array) – Third input values; should be of same shape as x.
Returns:

dfdx_out – First derivative of function with respect to the first input, evaluated at (x,y,z), of same shape as inputs.

Return type:

np.array

derivativeY(x, y, z)

Evaluate the first derivative with respect to y of the function at given state space points.

Parameters:
  • x (np.array) – First input values.
  • y (np.array) – Second input values; should be of same shape as x.
  • z (np.array) – Third input values; should be of same shape as x.
Returns:

dfdy_out – First derivative of function with respect to the second input, evaluated at (x,y,z), of same shape as inputs.

Return type:

np.array

derivativeZ(x, y, z)

Evaluate the first derivative with respect to z of the function at given state space points.

Parameters:
  • x (np.array) – First input values.
  • y (np.array) – Second input values; should be of same shape as x.
  • z (np.array) – Third input values; should be of same shape as x.
Returns:

dfdz_out – First derivative of function with respect to the third input, evaluated at (x,y,z), of same shape as inputs.

Return type:

np.array

HARK.interpolation.calcChoiceProbs(Vals, sigma)

Returns the choice probabilities given the choice specific value functions Vals. Probabilities are degenerate if sigma == 0.0. :param Vals: A numpy.array that holds choice specific values at common grid points. :type Vals: [numpy.array] :param sigma: A number that controls the variance of the taste shocks :type sigma: float

Returns:Probs – A numpy.array that holds the discrete choice probabilities
Return type:[numpy.array]
HARK.interpolation.calcLogSum(Vals, sigma)

Returns the optimal value given the choice specific value functions Vals. :param Vals: A numpy.array that holds choice specific values at common grid points. :type Vals: [numpy.array] :param sigma: A number that controls the variance of the taste shocks :type sigma: float

Returns:V – A numpy.array that holds the integrated value function.
Return type:[numpy.array]
HARK.interpolation.calcLogSumChoiceProbs(Vals, sigma)

Returns the final optimal value and choice probabilities given the choice specific value functions Vals. Probabilities are degenerate if sigma == 0.0. :param Vals: A numpy.array that holds choice specific values at common grid points. :type Vals: [numpy.array] :param sigma: A number that controls the variance of the taste shocks :type sigma: float

Returns:
  • V ([numpy.array]) – A numpy.array that holds the integrated value function.
  • P ([numpy.array]) – A numpy.array that holds the discrete choice probabilities

Early version of multithreading in HARK. To use most of this module, you should first install dill and joblib. Packages can be installed by typing “conda install dill” (etc) at a command prompt.

HARK.parallel.loadNelderMeadData(name)

Reads the progress of a parallel Nelder-Mead search from a text file, as created by saveNelderMeadData().

Parameters:name (string) – Name of the txt file from which to read search progress.
Returns:
  • simplex (np.array) – The current state of the simplex of parameter guesses.
  • fvals (np.array) – The objective function value at each row of simplex.
  • iters (int) – The number of completed Nelder-Mead iterations.
  • evals (int) – The cumulative number of function evaluations in the search process.
HARK.parallel.multiThreadCommands(agent_list, command_list, num_jobs=None)

Executes the list of commands in command_list for each AgentType in agent_list using a multithreaded system. Each command should be a method of that AgentType subclass.

Parameters:
  • agent_list ([AgentType]) – A list of instances of AgentType on which the commands will be run.
  • command_list ([string]) – A list of commands to run for each AgentType in agent_list.
Returns:

Return type:

None

HARK.parallel.multiThreadCommandsFake(agent_list, command_list, num_jobs=None)

Executes the list of commands in command_list for each AgentType in agent_list in an ordinary, single-threaded loop. Each command should be a method of that AgentType subclass. This function exists so as to easily disable multithreading, as it uses the same syntax as multithreadCommands.

Parameters:
  • agent_list ([AgentType]) – A list of instances of AgentType on which the commands will be run.
  • command_list ([string]) – A list of commands to run for each AgentType.
  • num_jobs (None) – Dummy input to match syntax of multiThreadCommands. Does nothing.
Returns:

Return type:

none

HARK.parallel.parallelNelderMead(objFunc, guess, perturb=None, P=1, ftol=1e-06, xtol=1e-08, maxiter=inf, maxeval=inf, r_param=1.0, e_param=1.0, c_param=0.5, s_param=0.5, maxthreads=None, name=None, resume=False, savefreq=None, verbose=1)

A parallel implementation of the Nelder-Mead minimization algorithm, as described in Lee and Wiswall. For long optimization procedures, it can save progress between iterations and resume later.

Parameters:
  • objFunc (function) – The objective function to be minimized. Takes a single 1D array as input.
  • guess (np.array) – Initial starting point for the simplex, representing an input for objFunc.
  • perturb (np.array) – Perturbation vector for the simplex, of the same length as an input to objFunc. If perturb[j] is non-zero, a simplex point will be created that perturbs the j-th element of guess by perturb[j]; if it is zero, then the j-th parameter of objFunc will not be optimized over. By default, perturb=None, indicating that all parameters should be optimized, with an initial perturbation of 0.1*guess.
  • P (int) – Degree of parallelization: the number of vertices of the simplex to try to update on each iteration of the process.
  • ftol (float) – Absolute tolerance of the objective function for convergence. If suc- cessive iterations return minimum function values that differ by less than ftol, the process terminates successfully.
  • xtol (float) – Absolute tolerance of the input values for convergence. If the maximum distance between the current minimum point and the worst point in the simplex is less than xtol, then the process terminates successfully.
  • maxiter (int) – Maximum number of Nelder-Mead iterations; reaching iters=maxiter is reported as an “unsuccessful” minimization.
  • maxeval (int) – Maximum number of evaluations of objFunc (across all processes); reaching evals=maxeval is reported as an “unsuccessful” minimization.
  • r_param (float) – Parameter indicating magnitude of the reflection point calculation.
  • e_param (float) – Parameter indicating magnitude of the expansion point calculation.
  • c_param (float) – Parameter indicating magnitude of the contraction point calculation.
  • s_param (float) – Parameter indicating magnitude of the shrink calculation.
  • maxthreads (int) – The maximum number of CPU cores that the optimization should use, regardless of the size of the problem.
  • name (string) – A filename for (optionally) saving the progress of the Nelder-Mead search, and for resuming a previous search (when resume=True). Useful for long searches that could potentially be interrupted by computer down time.
  • resume (boolean) – An indicator for whether the search should resume from earlier progress. When True, the process will load a progress file named in input name.
  • savefreq (int) – When not None, search progress will be saved to name.txt every savefreq iterations, to be loaded later with resume=True).
  • verbose (int) – Indicator for the verbosity of the optimization routine. Higher values generate more text output; verbose=0 produces no text output.
Returns:

  • min_point (np.array) – The input that minimizes objFunc, as found by the minimization.
  • fmin (float) – The minimum of objFunc; fmin = objFunc(min_point).

HARK.parallel.parallelNelderMeadWorker(objFunc, simplex, f_vals, j, P, opt_params)

A worker process for the parallel Nelder-Mead algorithm. Updates one point in the simplex, returning its function value as well. Should basically never be called directly, only by parallelNelderMead().

Parameters:
  • objFunc (function) – The function to be minimized; takes a single 1D array as input.
  • simplex (numpy.array) – The current simplex for minimization; simplex[k,:] is an input for objFunc.
  • f_vals (numpy.array) – The values of the objective function at each point of the simplex: f_vals[k] = objFunc(simplex[k,:])
  • j (int) – Index of the point in the simplex to update: simplex[j,:]
  • P (int) – Degree of parallelization of the algorithm.
  • opt_params (numpy.array) – Three element array with parameters for reflection, contraction, expansion.
Returns:

  • new_point (numpy.array) – An updated point for the simplex; might be the same as simplex[j,:].
  • new_val (float) – The value of the objective function at the new point: objFunc(new_point).
  • evals (int) – Number of evaluations of objFunc by this worker.

HARK.parallel.runCommands(agent, command_list)

Executes each command in command_list on a given AgentType. The commands should be methods of that AgentType’s subclass.

Parameters:
  • agent (AgentType) – An instance of AgentType on which the commands will be run.
  • command_list ([string]) – A list of commands that the agent should run, as methods.
Returns:

agent – The same AgentType instance passed as input, after running the commands.

Return type:

AgentType

HARK.parallel.saveNelderMeadData(name, simplex, fvals, iters, evals)

Stores the progress of a parallel Nelder-Mead search in a text file so that it can be resumed later (after manual termination or a crash).

Parameters:
  • name (string) – Name of the txt file in which to store search progress.
  • simplex (np.array) – The current state of the simplex of parameter guesses.
  • fvals (np.array) – The objective function value at each row of simplex.
  • iters (int) – The number of completed Nelder-Mead iterations.
  • evals (int) – The cumulative number of function evaluations in the search process.
Returns:

Return type:

None

Functions for generating simulated data and shocks.

HARK.simulation.drawBernoulli(N, p=0.5, seed=0)

Generates arrays of booleans drawn from a simple Bernoulli distribution. The input p can be a float or a list-like of floats; its length T determines the number of entries in the output. The t-th entry of the output is an array of N booleans which are True with probability p[t] and False otherwise.

Parameters:
  • N (int) – Number of draws in each row.
  • p (float or [float]) – Probability or probabilities of the event occurring (True).
  • seed (int) – Seed for random number generator.
Returns:

draws – T-length list of arrays of Bernoulli draws each of size N, or a single array of size N (if sigma is a scalar).

Return type:

np.array or [np.array]

HARK.simulation.drawDiscrete(N, P=[1.0], X=[0.0], exact_match=False, seed=0)

Simulates N draws from a discrete distribution with probabilities P and outcomes X.

Parameters:
  • P (np.array) – A list of probabilities of outcomes.
  • X (np.array) – A list of discrete outcomes.
  • N (int) – Number of draws to simulate.
  • exact_match (boolean) – Whether the draws should “exactly” match the discrete distribution (as closely as possible given finite draws). When True, returned draws are a random permutation of the N-length list that best fits the discrete distribution. When False (default), each draw is independent from the others and the result could deviate from the input.
  • seed (int) – Seed for random number generator.
Returns:

draws – An array draws from the discrete distribution; each element is a value in X.

Return type:

np.array

HARK.simulation.drawLognormal(N, mu=0.0, sigma=1.0, seed=0)

Generate arrays of lognormal draws. The sigma input can be a number or list-like. If a number, output is a length N array of draws from the lognormal distribution with standard deviation sigma. If a list, output is a length T list whose t-th entry is a length N array of draws from the lognormal with standard deviation sigma[t].

Parameters:
  • N (int) – Number of draws in each row.
  • mu (float or [float]) – One or more means. Number of elements T in mu determines number of rows of output.
  • sigma (float or [float]) – One or more standard deviations. Number of elements T in sigma determines number of rows of output.
  • seed (int) – Seed for random number generator.
  • Returns
  • ------------
  • draws (np.array or [np.array]) – T-length list of arrays of mean one lognormal draws each of size N, or a single array of size N (if sigma is a scalar).
HARK.simulation.drawMeanOneLognormal(N, sigma=1.0, seed=0)

Generate arrays of mean one lognormal draws. The sigma input can be a number or list-like. If a number, output is a length N array of draws from the lognormal distribution with standard deviation sigma. If a list, output is a length T list whose t-th entry is a length N array of draws from the lognormal with standard deviation sigma[t].

Parameters:
  • N (int) – Number of draws in each row.
  • sigma (float or [float]) – One or more standard deviations. Number of elements T in sigma determines number of rows of output.
  • seed (int) – Seed for random number generator.
  • Returns
  • ------------
  • draws (np.array or [np.array]) – T-length list of arrays of mean one lognormal draws each of size N, or a single array of size N (if sigma is a scalar).
HARK.simulation.drawNormal(N, mu=0.0, sigma=1.0, seed=0)

Generate arrays of normal draws. The mu and sigma inputs can be numbers or list-likes. If a number, output is a length N array of draws from the normal distribution with mean mu and standard deviation sigma. If a list, output is a length T list whose t-th entry is a length N array with draws from the normal distribution with mean mu[t] and standard deviation sigma[t].

Parameters:
  • N (int) – Number of draws in each row.
  • mu (float or [float]) – One or more means. Number of elements T in mu determines number of rows of output.
  • sigma (float or [float]) – One or more standard deviations. Number of elements T in sigma determines number of rows of output.
  • seed (int) – Seed for random number generator.
Returns:

draws – T-length list of arrays of normal draws each of size N, or a single array of size N (if sigma is a scalar).

Return type:

np.array or [np.array]

HARK.simulation.drawUniform(N, bot=0.0, top=1.0, seed=0)

Generate arrays of uniform draws. The bot and top inputs can be numbers or list-likes. If a number, output is a length N array of draws from the uniform distribution on [bot,top]. If a list, output is a length T list whose t-th entry is a length N array with draws from the uniform distribution on [bot[t],top[t]].

Parameters:
  • N (int) – Number of draws in each row.
  • bot (float or [float]) – One or more bottom values. Number of elements T in mu determines number of rows of output.
  • top (float or [float]) – One or more top values. Number of elements T in top determines number of rows of output.
  • seed (int) – Seed for random number generator.
Returns:

draws – T-length list of arrays of uniform draws each of size N, or a single array of size N (if sigma is a scalar).

Return type:

np.array or [np.array]

HARK.simulation.drawWeibull(N, scale=1.0, shape=1.0, seed=0)

Generate arrays of Weibull draws. The scale and shape inputs can be numbers or list-likes. If a number, output is a length N array of draws from the Weibull distribution with the given scale and shape. If a list, output is a length T list whose t-th entry is a length N array with draws from the Weibull distribution with scale scale[t] and shape shape[t].

Note: When shape=1, the Weibull distribution is simply the exponential dist.

Mean: scale*Gamma(1 + 1/shape)

Parameters:
  • N (int) – Number of draws in each row.
  • scale (float or [float]) – One or more scales. Number of elements T in scale determines number of rows of output.
  • shape (float or [float]) – One or more shape parameters. Number of elements T in scale determines number of rows of output.
  • seed (int) – Seed for random number generator.
  • Returns
  • ------------
  • draws (np.array or [np.array]) – T-length list of arrays of Weibull draws each of size N, or a single array of size N (if sigma is a scalar).

General purpose / miscellaneous functions. Includes functions to approximate continuous distributions with discrete ones, utility functions (and their derivatives), manipulation of discrete distributions, and basic plotting tools.

HARK.utilities.CARAutility(c, alpha)

Evaluates constant absolute risk aversion (CARA) utility of consumption c given risk aversion parameter alpha.

Parameters:
  • c (float) – Consumption value
  • alpha (float) – Risk aversion
Returns:

(unnamed) – Utility

Return type:

float

HARK.utilities.CARAutilityP(c, alpha)

Evaluates constant absolute risk aversion (CARA) marginal utility of consumption c given risk aversion parameter alpha.

Parameters:
  • c (float) – Consumption value
  • alpha (float) – Risk aversion
Returns:

(unnamed) – Marginal utility

Return type:

float

HARK.utilities.CARAutilityPP(c, alpha)

Evaluates constant absolute risk aversion (CARA) marginal marginal utility of consumption c given risk aversion parameter alpha.

Parameters:
  • c (float) – Consumption value
  • alpha (float) – Risk aversion
Returns:

(unnamed) – Marginal marginal utility

Return type:

float

HARK.utilities.CARAutilityPPP(c, alpha)

Evaluates constant absolute risk aversion (CARA) marginal marginal marginal utility of consumption c given risk aversion parameter alpha.

Parameters:
  • c (float) – Consumption value
  • alpha (float) – Risk aversion
Returns:

(unnamed) – Marginal marginal marginal utility

Return type:

float

HARK.utilities.CARAutilityP_inv(u, alpha)

Evaluates the inverse of constant absolute risk aversion (CARA) marginal utility function at marginal utility uP given risk aversion parameter alpha.

Parameters:
  • u (float) – Utility value
  • alpha (float) – Risk aversion
Returns:

(unnamed) – Consumption value corresponding to uP

Return type:

float

HARK.utilities.CARAutility_inv(u, alpha)

Evaluates inverse of constant absolute risk aversion (CARA) utility function at utility level u given risk aversion parameter alpha.

Parameters:
  • u (float) – Utility value
  • alpha (float) – Risk aversion
Returns:

(unnamed) – Consumption value corresponding to u

Return type:

float

HARK.utilities.CARAutility_invP(u, alpha)

Evaluates the derivative of inverse of constant absolute risk aversion (CARA) utility function at utility level u given risk aversion parameter alpha.

Parameters:
  • u (float) – Utility value
  • alpha (float) – Risk aversion
Returns:

(unnamed) – Marginal onsumption value corresponding to u

Return type:

float

HARK.utilities.CRRAutility(c, gam)

Evaluates constant relative risk aversion (CRRA) utility of consumption c given risk aversion parameter gam.

Parameters:
  • c (float) – Consumption value
  • gam (float) – Risk aversion
Returns:

  • (unnamed) (float) – Utility
  • Tests
  • —–
  • Test a value which should pass
  • >>> c, gamma = 1.0, 2.0 # Set two values at once with Python syntax
  • >>> utility(c=c, gam=gamma)
  • -1.0

HARK.utilities.CRRAutilityP(c, gam)

Evaluates constant relative risk aversion (CRRA) marginal utility of consumption c given risk aversion parameter gam.

Parameters:
  • c (float) – Consumption value
  • gam (float) – Risk aversion
Returns:

(unnamed) – Marginal utility

Return type:

float

HARK.utilities.CRRAutilityPP(c, gam)

Evaluates constant relative risk aversion (CRRA) marginal marginal utility of consumption c given risk aversion parameter gam.

Parameters:
  • c (float) – Consumption value
  • gam (float) – Risk aversion
Returns:

(unnamed) – Marginal marginal utility

Return type:

float

HARK.utilities.CRRAutilityPPP(c, gam)

Evaluates constant relative risk aversion (CRRA) marginal marginal marginal utility of consumption c given risk aversion parameter gam.

Parameters:
  • c (float) – Consumption value
  • gam (float) – Risk aversion
Returns:

(unnamed) – Marginal marginal marginal utility

Return type:

float

HARK.utilities.CRRAutilityPPPP(c, gam)

Evaluates constant relative risk aversion (CRRA) marginal marginal marginal marginal utility of consumption c given risk aversion parameter gam.

Parameters:
  • c (float) – Consumption value
  • gam (float) – Risk aversion
Returns:

(unnamed) – Marginal marginal marginal marginal utility

Return type:

float

HARK.utilities.CRRAutilityP_inv(uP, gam)

Evaluates the inverse of the CRRA marginal utility function (with risk aversion parameter gam) at a given marginal utility level uP.

Parameters:
  • uP (float) – Marginal utility value
  • gam (float) – Risk aversion
Returns:

(unnamed) – Consumption corresponding to given marginal utility value.

Return type:

float

HARK.utilities.CRRAutilityP_invP(uP, gam)

Evaluates the derivative of the inverse of the CRRA marginal utility function (with risk aversion parameter gam) at a given marginal utility level uP.

Parameters:
  • uP (float) – Marginal utility value
  • gam (float) – Risk aversion
Returns:

(unnamed) – Marginal consumption corresponding to given marginal utility value

Return type:

float

HARK.utilities.CRRAutility_inv(u, gam)

Evaluates the inverse of the CRRA utility function (with risk aversion para- meter gam) at a given utility level u.

Parameters:
  • u (float) – Utility value
  • gam (float) – Risk aversion
Returns:

(unnamed) – Consumption corresponding to given utility value

Return type:

float

HARK.utilities.CRRAutility_invP(u, gam)

Evaluates the derivative of the inverse of the CRRA utility function (with risk aversion parameter gam) at a given utility level u.

Parameters:
  • u (float) – Utility value
  • gam (float) – Risk aversion
Returns:

(unnamed) – Marginal consumption corresponding to given utility value

Return type:

float

class HARK.utilities.NullFunc

A trivial class that acts as a placeholder “do nothing” function.

distance(other)

Trivial distance metric that only cares whether the other object is also an instance of NullFunc. Intentionally does not inherit from HARKobject as this might create dependency problems.

Parameters:other (any) – Any object for comparison to this instance of NullFunc.
Returns:(unnamed) – The distance between self and other. Returns 0 if other is also a NullFunc; otherwise returns an arbitrary high number.
Return type:float
HARK.utilities.addDiscreteOutcome(distribution, x, p, sort=False)

Adds a discrete outcome of x with probability p to an existing distribution, holding constant the relative probabilities of other outcomes.

Parameters:
  • distribution ([np.array]) – Two element list containing a list of probabilities and a list of outcomes.
  • x (float) – The new value to be added to the distribution.
  • p (float) – The probability of the discrete outcome x occuring.
Returns:

  • X (np.array) – Discrete points for discrete probability mass function.
  • pmf (np.array) – Probability associated with each point in X.
  • Written by Matthew N. White
  • Latest update (11 December 2015)

HARK.utilities.addDiscreteOutcomeConstantMean(distribution, x, p, sort=False)

Adds a discrete outcome of x with probability p to an existing distribution, holding constant the relative probabilities of other outcomes and overall mean.

Parameters:
  • distribution ([np.array]) – Two element list containing a list of probabilities and a list of outcomes.
  • x (float) – The new value to be added to the distribution.
  • p (float) – The probability of the discrete outcome x occuring.
  • sort (bool) – Whether or not to sort X before returning it
Returns:

  • X (np.array) – Discrete points for discrete probability mass function.
  • pmf (np.array) – Probability associated with each point in X.
  • Written by Matthew N. White
  • Latest update (08 December 2015 by David Low)

HARK.utilities.approxBeta(N, a=1.0, b=1.0)

Calculate a discrete approximation to the beta distribution. May be quite slow, as it uses a rudimentary numeric integration method to generate the discrete approximation.

Parameters:
  • N (int) – Size of discrete space vector to be returned.
  • a (float) – First shape parameter (sometimes called alpha).
  • b (float) – Second shape parameter (sometimes called beta).
Returns:

  • X (np.array) – Discrete points for discrete probability mass function.
  • pmf (np.array) – Probability associated with each point in X.

HARK.utilities.approxLognormal(N, mu=0.0, sigma=1.0, tail_N=0, tail_bound=[0.02, 0.98], tail_order=2.718281828459045)

Construct a discrete approximation to a lognormal distribution with underlying normal distribution N(mu,sigma). Makes an equiprobable distribution by default, but user can optionally request augmented tails with exponentially sized point masses. This can improve solution accuracy in some models.

Parameters:
  • N (int) – Number of discrete points in the “main part” of the approximation.
  • mu (float) – Mean of underlying normal distribution.
  • sigma (float) – Standard deviation of underlying normal distribution.
  • tail_N (int) – Number of points in each “tail part” of the approximation; 0 = no tail.
  • tail_bound ([float]) – CDF boundaries of the tails vs main portion; tail_bound[0] is the lower tail bound, tail_bound[1] is the upper tail bound. Inoperative when tail_N = 0. Can make “one tailed” approximations with 0.0 or 1.0.
  • tail_order (float) – Factor by which consecutive point masses in a “tail part” differ in probability. Should be >= 1 for sensible spacing.
Returns:

  • pmf (np.ndarray) – Probabilities for discrete probability mass function.
  • X (np.ndarray) – Discrete values in probability mass function.
  • Written by Luca Gerotto
  • Based on Matab function “setup_workspace.m,” from Chris Carroll’s – [Solution Methods for Microeconomic Dynamic Optimization Problems] (http://www.econ2.jhu.edu/people/ccarroll/solvingmicrodsops/) toolkit.
  • Latest update (11 February 2017 by Matthew N. White)

HARK.utilities.approxMeanOneLognormal(N, sigma=1.0, **kwargs)

Calculate a discrete approximation to a mean one lognormal distribution. Based on function approxLognormal; see that function’s documentation for further notes.

Parameters:
  • N (int) – Size of discrete space vector to be returned.
  • sigma (float) – standard deviation associated with underlying normal probability distribution.
Returns:

  • X (np.array) – Discrete points for discrete probability mass function.
  • pmf (np.array) – Probability associated with each point in X.
  • Written by Nathan M. Palmer
  • Based on Matab function “setup_shocks.m,” from Chris Carroll’s – [Solution Methods for Microeconomic Dynamic Optimization Problems] (http://www.econ2.jhu.edu/people/ccarroll/solvingmicrodsops/) toolkit.
  • Latest update (01 May 2015)

HARK.utilities.approxUniform(N, bot=0.0, top=1.0)

Makes a discrete approximation to a uniform distribution, given its bottom and top limits and number of points.

Parameters:
  • N (int) – The number of points in the discrete approximation
  • bot (float) – The bottom of the uniform distribution
  • top (float) – The top of the uniform distribution
Returns:

(unnamed) – An equiprobable discrete approximation to the uniform distribution.

Return type:

np.array

HARK.utilities.calcSubpopAvg(data, reference, cutoffs, weights=None)

Calculates the average of (weighted) data between cutoff percentiles of a reference variable.

Parameters:
  • data (numpy.array) – A 1D array of float data.
  • reference (numpy.array) – A 1D array of float data of the same length as data.
  • cutoffs ([(float,float)]) – A list of doubles with the lower and upper percentile bounds (should be in [0,1]).
  • weights (numpy.array) – A weighting vector for the data.
Returns:

The (weighted) average of data that falls within the cutoff percentiles of reference.

Return type:

slice_avg

HARK.utilities.calcWeightedAvg(data, weights)

Generates a weighted average of simulated data. The Nth row of data is averaged and then weighted by the Nth element of weights in an aggregate average.

Parameters:
  • data (numpy.array) – An array of data with N rows of J floats
  • weights (numpy.array) – A length N array of weights for the N rows of data.
Returns:

weighted_sum – The weighted sum of the data.

Return type:

float

HARK.utilities.combineIndepDstns(*distributions)

Given n lists (or tuples) whose elements represent n independent, discrete probability spaces (probabilities and values), construct a joint pmf over all combinations of these independent points. Can take multivariate discrete distributions as inputs.

Parameters:distributions ([np.array]) – Arbitrary number of distributions (pmfs). Each pmf is a list or tuple. For each pmf, the first vector is probabilities and all subsequent vectors are values. For each pmf, this should be true: len(X_pmf[0]) == len(X_pmf[j]) for j in range(1,len(distributions))
Returns:
  • List of arrays, consisting of
  • P_out (np.array) – Probability associated with each point in X_out.
  • X_out (np.array (as many as in *distributions)) – Discrete points for the joint discrete probability mass function.
  • Written by Nathan Palmer
  • Latest update (5 July August 2017 by Matthew N White)
HARK.utilities.epanechnikovKernel(x, ref_x, h=1.0)

The Epanechnikov kernel.

Parameters:
  • x (np.array) – Values at which to evaluate the kernel
  • x_ref (float) – The reference point
  • h (float) – Kernel bandwidth
Returns:

out – Kernel values at each value of x

Return type:

np.array

HARK.utilities.getArgNames(function)

Returns a list of strings naming all of the arguments for the passed function.

Parameters:function (function) – A function whose argument names are wanted.
Returns:argNames – The names of the arguments of function.
Return type:[string]
HARK.utilities.getLorenzShares(data, weights=None, percentiles=[0.5], presorted=False)

Calculates the Lorenz curve at the requested percentiles of (weighted) data. Median by default.

Parameters:
  • data (numpy.array) – A 1D array of float data.
  • weights (numpy.array) – A weighting vector for the data.
  • percentiles ([float]) – A list of percentiles to calculate for the data. Each element should be in (0,1).
  • presorted (boolean) – Indicator for whether data has already been sorted.
Returns:

lorenz_out – The requested Lorenz curve points of the data.

Return type:

numpy.array

HARK.utilities.getPercentiles(data, weights=None, percentiles=[0.5], presorted=False)

Calculates the requested percentiles of (weighted) data. Median by default.

Parameters:
  • data (numpy.array) – A 1D array of float data.
  • weights (np.array) – A weighting vector for the data.
  • percentiles ([float]) – A list of percentiles to calculate for the data. Each element should be in (0,1).
  • presorted (boolean) – Indicator for whether data has already been sorted.
Returns:

pctl_out – The requested percentiles of the data.

Return type:

numpy.array

HARK.utilities.kernelRegression(x, y, bot=None, top=None, N=500, h=None)

Performs a non-parametric Nadaraya-Watson 1D kernel regression on given data with optionally specified range, number of points, and kernel bandwidth.

Parameters:
  • x (np.array) – The independent variable in the kernel regression.
  • y (np.array) – The dependent variable in the kernel regression.
  • bot (float) – Minimum value of interest in the regression; defaults to min(x).
  • top (float) – Maximum value of interest in the regression; defaults to max(y).
  • N (int) – Number of points to compute.
  • h (float) – The bandwidth of the (Epanechnikov) kernel. To-do: GENERALIZE.
Returns:

regression – A piecewise locally linear kernel regression: y = f(x).

Return type:

LinearInterp

HARK.utilities.makeGridExpMult(ming, maxg, ng, timestonest=20)

Make a multi-exponentially spaced grid.

Parameters:
  • ming (float) – Minimum value of the grid
  • maxg (float) – Maximum value of the grid
  • ng (int) – The number of grid points
  • timestonest (int) – the number of times to nest the exponentiation
Returns:

  • points (np.array) – A multi-exponentially spaced grid
  • Original Matab code can be found in Chris Carroll’s
  • [Solution Methods for Microeconomic Dynamic Optimization Problems]
  • (http (//www.econ2.jhu.edu/people/ccarroll/solvingmicrodsops/) toolkit.)
  • Latest update (01 May 2015)

HARK.utilities.makeMarkovApproxToNormal(x_grid, mu, sigma, K=351, bound=3.5)

Creates an approximation to a normal distribution with mean mu and standard deviation sigma, returning a stochastic vector called p_vec, corresponding to values in x_grid. If a RV is distributed x~N(mu,sigma), then the expectation of a continuous function f() is E[f(x)] = numpy.dot(p_vec,f(x_grid)).

Parameters:
  • x_grid (numpy.array) – A sorted 1D array of floats representing discrete values that a normally distributed RV could take on.
  • mu (float) – Mean of the normal distribution to be approximated.
  • sigma (float) – Standard deviation of the normal distribution to be approximated.
  • K (int) – Number of points in the normal distribution to sample.
  • bound (float) – Truncation bound of the normal distribution, as +/- bound*sigma.
Returns:

p_vec – A stochastic vector with probability weights for each x in x_grid.

Return type:

numpy.array

HARK.utilities.makeMarkovApproxToNormalByMonteCarlo(x_grid, mu, sigma, N_draws=10000)

Creates an approximation to a normal distribution with mean mu and standard deviation sigma, by Monte Carlo. Returns a stochastic vector called p_vec, corresponding to values in x_grid. If a RV is distributed x~N(mu,sigma), then the expectation of a continuous function f() is E[f(x)] = numpy.dot(p_vec,f(x_grid)).

Parameters:
  • x_grid (numpy.array) – A sorted 1D array of floats representing discrete values that a normally distributed RV could take on.
  • mu (float) – Mean of the normal distribution to be approximated.
  • sigma (float) – Standard deviation of the normal distribution to be approximated.
  • N_draws (int) – Number of draws to use in Monte Carlo.
Returns:

p_vec – A stochastic vector with probability weights for each x in x_grid.

Return type:

numpy.array

HARK.utilities.makeTauchenAR1(N, sigma=1.0, rho=0.9, bound=3.0)

Function to return a discretized version of an AR1 process. See http://www.fperri.net/TEACHING/macrotheory08/numerical.pdf for details

Parameters:
  • N (int) – Size of discretized grid
  • sigma (float) – Standard deviation of the error term
  • rho (float) – AR1 coefficient
  • bound (float) – The highest (lowest) grid point will be bound (-bound) multiplied by the unconditional standard deviation of the process
Returns:

  • y (np.array) – Grid points on which the discretized process takes values
  • trans_matrix (np.array) – Markov transition array for the discretized process
  • Written by Edmund S. Crawley
  • Latest update (27 October 2017)

HARK.utilities.memoize(obj)

A decorator to (potentially) make functions more efficient.

With this decorator, functions will “remember” if they have been evaluated with given inputs before. If they have, they will “remember” the outputs that have already been calculated for those inputs, rather than calculating them again.

HARK.utilities.plotFuncs(functions, bottom, top, N=1000, legend_kwds=None)

Plots 1D function(s) over a given range.

Parameters:
  • functions ([function] or function) – A single function, or a list of functions, to be plotted.
  • bottom (float) – The lower limit of the domain to be plotted.
  • top (float) – The upper limit of the domain to be plotted.
  • N (int) – Number of points in the domain to evaluate.
  • legend_kwds (None, or dictionary) – If not None, the keyword dictionary to pass to plt.legend
Returns:

Return type:

none

HARK.utilities.plotFuncsDer(functions, bottom, top, N=1000, legend_kwds=None)

Plots the first derivative of 1D function(s) over a given range.

Parameters:
  • function (function) – A function or list of functions, the derivatives of which are to be plotted.
  • bottom (float) – The lower limit of the domain to be plotted.
  • top (float) – The upper limit of the domain to be plotted.
  • N (int) – Number of points in the domain to evaluate.
  • legend_kwds (None, or dictionary) – If not None, the keyword dictionary to pass to plt.legend
Returns:

Return type:

none

Decorators which can be used for validating arguments passed into decorated functions

HARK.validators.non_empty(*parameter_names)

Enforces arguments to parameters passed in have len > 0

Consumption Saving

Consumption-saving models with aggregate productivity shocks as well as idiosyn- cratic income shocks. Currently only contains one microeconomic model with a basic solver. Also includes a subclass of Market called CobbDouglas economy, used for solving “macroeconomic” models with aggregate shocks.

class HARK.ConsumptionSaving.ConsAggShockModel.AggShockConsumerType(time_flow=True, **kwds)

A class to represent consumers who face idiosyncratic (transitory and per- manent) shocks to their income and live in an economy that has aggregate (transitory and permanent) shocks to labor productivity. As the capital- to-labor ratio varies in the economy, so does the wage rate and interest rate. “Aggregate shock consumers” have beliefs about how the capital ratio evolves over time and take aggregate shocks into account when making their decision about how much to consume.

addAggShkDstn(AggShkDstn)

Updates attribute IncomeDstn by combining idiosyncratic shocks with aggregate shocks.

Parameters:AggShkDstn ([np.array]) – Aggregate productivity shock distribution. First element is proba- bilities, second element is agg permanent shocks, third element is agg transitory shocks.
Returns:
Return type:None
calcBoundingValues()

Calculate human wealth plus minimum and maximum MPC in an infinite horizon model with only one period repeated indefinitely. Store results as attributes of self. Human wealth is the present discounted value of expected future income after receiving income this period, ignoring mort- ality. The maximum MPC is the limit of the MPC as m –> mNrmMin. The minimum MPC is the limit of the MPC as m –> infty.

NOT YET IMPLEMENTED FOR THIS CLASS

Parameters:None
Returns:
Return type:None
getControls()

Calculates consumption for each consumer of this type using the consumption functions.

Parameters:None
Returns:
Return type:None
getEconomyData(Economy)

Imports economy-determined objects into self from a Market. Instances of AggShockConsumerType “live” in some macroeconomy that has attributes relevant to their microeconomic model, like the relationship between the capital-to-labor ratio and the interest and wage rates; this method imports those attributes from an “economy” object and makes them attributes of the ConsumerType.

Parameters:Economy (Market) – The “macroeconomy” in which this instance “lives”. Might be of the subclass CobbDouglasEconomy, which has methods to generate the relevant attributes.
Returns:
Return type:None
getRfree()

Returns an array of size self.AgentCount with self.RfreeNow in every entry.

Parameters:None
Returns:RfreeNow – Array of size self.AgentCount with risk free interest rate for each agent.
Return type:np.array
getShocks()

Finds the effective permanent and transitory shocks this period by combining the aggregate and idiosyncratic shocks of each type.

Parameters:None
Returns:
Return type:None
makeEulerErrorFunc(mMax=100, approx_inc_dstn=True)

Creates a “normalized Euler error” function for this instance, mapping from market resources to “consumption error per dollar of consumption.” Stores result in attribute eulerErrorFunc as an interpolated function. Has option to use approximate income distribution stored in self.IncomeDstn or to use a (temporary) very dense approximation.

NOT YET IMPLEMENTED FOR THIS CLASS

Parameters:
  • mMax (float) – Maximum normalized market resources for the Euler error function.
  • approx_inc_dstn (Boolean) – Indicator for whether to use the approximate discrete income distri- bution stored in self.IncomeDstn[0], or to use a very accurate discrete approximation instead. When True, uses approximation in IncomeDstn; when False, makes and uses a very dense approximation.
Returns:

Return type:

None

marketAction()

In the aggregate shocks model, the “market action” is to simulate one period of receiving income and choosing how much to consume.

Parameters:None
Returns:
Return type:None
reset()

Initialize this type for a new simulated history of K/L ratio.

Parameters:None
Returns:
Return type:None
simBirth(which_agents)

Makes new consumers for the given indices. Initialized variables include aNrm and pLvl, as well as time variables t_age and t_cycle. Normalized assets and permanent income levels are drawn from lognormal distributions given by aNrmInitMean and aNrmInitStd (etc).

Parameters:which_agents (np.array(Bool)) – Boolean array of size self.AgentCount indicating which agents should be “born”.
Returns:
Return type:None
simDeath()

Randomly determine which consumers die, and distribute their wealth among the survivors. This method only works if there is only one period in the cycle.

Parameters:None
Returns:who_dies – Boolean array of size AgentCount indicating which agents die.
Return type:np.array(bool)
updateSolutionTerminal()

Updates the terminal period solution for an aggregate shock consumer. Only fills in the consumption function and marginal value function.

Parameters:None
Returns:
Return type:None
class HARK.ConsumptionSaving.ConsAggShockModel.AggShockMarkovConsumerType(**kwds)

A class for representing ex ante heterogeneous “types” of consumers who experience both aggregate and idiosyncratic shocks to productivity (both permanent and transitory), who lives in an environment where the macroeconomic state is subject to Markov-style discrete state evolution.

addAggShkDstn(AggShkDstn)

Variation on AggShockConsumerType.addAggShkDstn that handles the Markov state. AggShkDstn is a list of aggregate productivity shock distributions for each Markov state.

getControls()

Calculates consumption for each consumer of this type using the consumption functions. For this AgentType class, MrkvNow is the same for all consumers. However, in an extension with “macroeconomic inattention”, consumers might misperceive the state and thus act as if they are in different states.

Parameters:None
Returns:
Return type:None
getShocks()

Gets permanent and transitory income shocks for this period. Samples from IncomeDstn for each period in the cycle. This is a copy-paste from IndShockConsumerType, with the addition of the Markov macroeconomic state. Unfortunately, the getShocks method for MarkovConsumerType cannot be used, as that method assumes that MrkvNow is a vector with a value for each agent, not just a single int.

Parameters:None
Returns:
Return type:None
updateSolutionTerminal()

Update the terminal period solution. This method should be run when a new AgentType is created or when CRRA changes.

Parameters:None
Returns:
Return type:None
class HARK.ConsumptionSaving.ConsAggShockModel.AggShocksDynamicRule(AFunc)

Just a container class for passing the dynamic rule in the aggregate shocks model to agents.

class HARK.ConsumptionSaving.ConsAggShockModel.AggregateSavingRule(intercept, slope)

A class to represent agent beliefs about aggregate saving at the end of this period (AaggNow) as a function of (normalized) aggregate market resources at the beginning of the period (MaggNow).

class HARK.ConsumptionSaving.ConsAggShockModel.CobbDouglasAggVars(MaggNow, AaggNow, KtoLnow, RfreeNow, wRteNow, PermShkAggNow, TranShkAggNow)

A simple class for holding the relevant aggregate variables that should be passed from the market to each type. Includes the capital-to-labor ratio, the interest factor, the wage rate, and the aggregate permanent and tran- sitory shocks.

class HARK.ConsumptionSaving.ConsAggShockModel.CobbDouglasEconomy(agents=[], tolerance=0.0001, act_T=1200, **kwds)

A class to represent an economy with a Cobb-Douglas aggregate production function over labor and capital, extending HARK.Market. The “aggregate market process” for this market combines all individuals’ asset holdings into aggregate capital, yielding the interest factor on assets and the wage rate for the upcoming period.

Note: The current implementation assumes a constant labor supply, but this will be generalized in the future.

calcAFunc(MaggNow, AaggNow)

Calculate a new aggregate savings rule based on the history of the aggregate savings and aggregate market resources from a simulation.

Parameters:
  • MaggNow ([float]) – List of the history of the simulated aggregate market resources for an economy.
  • AaggNow ([float]) – List of the history of the simulated aggregate savings for an economy.
Returns:

(unnamed) – Object containing a new savings rule

Return type:

CapDynamicRule

calcDynamics(MaggNow, AaggNow)

Calculates a new dynamic rule for the economy: end of period savings as a function of aggregate market resources. Just calls calcAFunc().

See documentation for calcAFunc for more information.

calcRandW(aLvlNow, pLvlNow)

Calculates the interest factor and wage rate this period using each agent’s capital stock to get the aggregate capital ratio.

Parameters:aLvlNow ([np.array]) – Agents’ current end-of-period assets. Elements of the list correspond to types in the economy, entries within arrays to agents of that type.
Returns:AggVarsNow – An object containing the aggregate variables for the upcoming period: capital-to-labor ratio, interest factor, (normalized) wage rate, aggregate permanent and transitory shocks.
Return type:CobbDouglasAggVars
getPermGroFacAggLR()

A trivial function that returns self.PermGroFacAgg. Exists to be overwritten and extended by ConsAggShockMarkov model.

Parameters:None
Returns:PermGroFacAggLR – Long run aggregate permanent income growth, which is the same thing as aggregate permanent income growth.
Return type:float
makeAggShkDstn()

Creates the attributes TranShkAggDstn, PermShkAggDstn, and AggShkDstn. Draws on attributes TranShkAggStd, PermShkAddStd, TranShkAggCount, PermShkAggCount.

Parameters:None
Returns:
Return type:None
makeAggShkHist()

Make simulated histories of aggregate transitory and permanent shocks. Histories are of length self.act_T, for use in the general equilibrium simulation.

Parameters:None
Returns:
Return type:None
millRule(aLvlNow, pLvlNow)

Function to calculate the capital to labor ratio, interest factor, and wage rate based on each agent’s current state. Just calls calcRandW().

See documentation for calcRandW for more information.

reset()

Reset the economy to prepare for a new simulation. Sets the time index of aggregate shocks to zero and runs Market.reset().

Parameters:None
Returns:
Return type:None
update()

Use primitive parameters (and perfect foresight calibrations) to make interest factor and wage rate functions (of capital to labor ratio), as well as discrete approximations to the aggregate shock distributions.

Parameters:None
Returns:
Return type:None
class HARK.ConsumptionSaving.ConsAggShockModel.CobbDouglasMarkovEconomy(agents=[], tolerance=0.0001, act_T=1200, **kwds)

A class to represent an economy with a Cobb-Douglas aggregate production function over labor and capital, extending HARK.Market. The “aggregate market process” for this market combines all individuals’ asset holdings into aggregate capital, yielding the interest factor on assets and the wage rate for the upcoming period. This small extension incorporates a Markov state for the “macroeconomy”, so that the shock distribution and aggregate productivity growth factor can vary over time.

calcAFunc(MaggNow, AaggNow)

Calculate a new aggregate savings rule based on the history of the aggregate savings and aggregate market resources from a simulation. Calculates an aggregate saving rule for each macroeconomic Markov state.

Parameters:
  • MaggNow ([float]) – List of the history of the simulated aggregate market resources for an economy.
  • AaggNow ([float]) – List of the history of the simulated aggregate savings for an economy.
Returns:

(unnamed) – Object containing new saving rules for each Markov state.

Return type:

CapDynamicRule

getPermGroFacAggLR()

Calculates and returns the long run permanent income growth factor. This is the average growth factor in self.PermGroFacAgg, weighted by the long run distribution of Markov states (as determined by self.MrkvArray).

Parameters:None
Returns:PermGroFacAggLR – Long run aggregate permanent income growth factor
Return type:float
makeAggShkDstn()

Creates the attributes TranShkAggDstn, PermShkAggDstn, and AggShkDstn. Draws on attributes TranShkAggStd, PermShkAddStd, TranShkAggCount, PermShkAggCount. This version accounts for the Markov macroeconomic state.

Parameters:None
Returns:
Return type:None
makeAggShkHist()

Make simulated histories of aggregate transitory and permanent shocks. Histories are of length self.act_T, for use in the general equilibrium simulation. Draws on history of aggregate Markov states generated by internal call to makeMrkvHist().

Parameters:None
Returns:
Return type:None
makeMrkvHist()

Makes a history of macroeconomic Markov states, stored in the attribute MrkvNow_hist. This version ensures that each state is reached a sufficient number of times to have a valid sample for calcDynamics to produce a good dynamic rule. It will sometimes cause act_T to be increased beyond its initially specified level.

Parameters:None
Returns:
Return type:None
millRule(aLvlNow, pLvlNow)

Function to calculate the capital to labor ratio, interest factor, and wage rate based on each agent’s current state. Just calls calcRandW() and adds the Markov state index.

See documentation for calcRandW for more information.

update()

Use primitive parameters (and perfect foresight calibrations) to make interest factor and wage rate functions (of capital to labor ratio), as well as discrete approximations to the aggregate shock distributions.

Parameters:None
Returns:
Return type:None
class HARK.ConsumptionSaving.ConsAggShockModel.MargValueFunc2D(cFunc, CRRA)

A class for representing a marginal value function in models where the standard envelope condition of dvdm(m,M) = u’(c(m,M)) holds (with CRRA utility).

class HARK.ConsumptionSaving.ConsAggShockModel.SmallOpenEconomy(agents=[], tolerance=0.0001, act_T=1000, **kwds)

A class for representing a small open economy, where the wage rate and interest rate are exogenously determined by some “global” rate. However, the economy is still subject to aggregate productivity shocks.

calcDynamics(KtoLnow)

Calculates a new dynamic rule for the economy, which is just an empty object. There is no “dynamic rule” for a small open economy, because K/L does not generate w and R.

getAggShocks()

Returns aggregate state variables and shocks for this period. The capital-to-labor ratio is irrelevant and thus treated as constant, and the wage and interest rates are also constant. However, aggregate shocks are assigned from a prespecified history.

Parameters:None
Returns:AggVarsNow – Aggregate state and shock variables for this period.
Return type:CobbDouglasAggVars
makeAggShkDstn()

Creates the attributes TranShkAggDstn, PermShkAggDstn, and AggShkDstn. Draws on attributes TranShkAggStd, PermShkAddStd, TranShkAggCount, PermShkAggCount.

Parameters:None
Returns:
Return type:None
makeAggShkHist()

Make simulated histories of aggregate transitory and permanent shocks. Histories are of length self.act_T, for use in the general equilibrium simulation. This replicates the same method for CobbDouglasEconomy; future version should create parent class.

Parameters:None
Returns:
Return type:None
millRule()

No aggregation occurs for a small open economy, because the wage and interest rates are exogenously determined. However, aggregate shocks may occur.

See documentation for getAggShocks() for more information.

reset()

Reset the economy to prepare for a new simulation. Sets the time index of aggregate shocks to zero and runs Market.reset(). This replicates the reset method for CobbDouglasEconomy; future version should create parent class of that class and this one.

Parameters:None
Returns:
Return type:None
update()

Use primitive parameters to set basic objects. This is an extremely stripped-down version of update for CobbDouglasEconomy.

Parameters:none
Returns:
Return type:none
class HARK.ConsumptionSaving.ConsAggShockModel.SmallOpenMarkovEconomy(agents=[], tolerance=0.0001, act_T=1000, **kwds)

A class for representing a small open economy, where the wage rate and interest rate are exogenously determined by some “global” rate. However, the economy is still subject to aggregate productivity shocks. This version supports a discrete Markov state. All methods in this class inherit from the two parent classes.

HARK.ConsumptionSaving.ConsAggShockModel.solveConsAggMarkov(solution_next, IncomeDstn, LivPrb, DiscFac, CRRA, MrkvArray, PermGroFac, PermGroFacAgg, aXtraGrid, BoroCnstArt, Mgrid, AFunc, Rfunc, wFunc, DeprFac)

Solve one period of a consumption-saving problem with idiosyncratic and aggregate shocks (transitory and permanent). Moreover, the macroeconomic state follows a Markov process that determines the income distribution and aggregate permanent growth factor. This is a basic solver that can’t handle cubic splines, nor can it calculate a value function.

Parameters:
  • solution_next (ConsumerSolution) – The solution to the succeeding one period problem.
  • IncomeDstn ([[np.array]]) – A list of lists, each containing five arrays of floats, representing a discrete approximation to the income process between the period being solved and the one immediately following (in solution_next). Order: event probabilities, idisyncratic permanent shocks, idiosyncratic transitory shocks, aggregate permanent shocks, aggregate transitory shocks.
  • LivPrb (float) – Survival probability; likelihood of being alive at the beginning of the succeeding period.
  • DiscFac (float) – Intertemporal discount factor for future utility.
  • CRRA (float) – Coefficient of relative risk aversion.
  • MrkvArray (np.array) – Markov transition matrix between discrete macroeconomic states. MrkvArray[i,j] is probability of being in state j next period conditional on being in state i this period.
  • PermGroFac (float) – Expected permanent income growth factor at the end of this period, for the individual’s productivity.
  • PermGroFacAgg ([float]) – Expected aggregate productivity growth in each Markov macro state.
  • aXtraGrid (np.array) – Array of “extra” end-of-period asset values– assets above the absolute minimum acceptable level.
  • BoroCnstArt (float) – Artificial borrowing constraint; minimum allowable end-of-period asset-to- permanent-income ratio. Unlike other models, this can’t be None.
  • Mgrid (np.array) – A grid of aggregate market resourses to permanent income in the economy.
  • AFunc ([function]) – Aggregate savings as a function of aggregate market resources, for each Markov macro state.
  • Rfunc (function) – The net interest factor on assets as a function of capital ratio k.
  • wFunc (function) – The wage rate for labor as a function of capital-to-labor ratio k.
  • DeprFac (float) – Capital Depreciation Rate
Returns:

solution_now – The solution to the single period consumption-saving problem. Includes a consumption function cFunc (linear interpolation over linear interpola- tions) and marginal value function vPfunc.

Return type:

ConsumerSolution

HARK.ConsumptionSaving.ConsAggShockModel.solveConsAggShock(solution_next, IncomeDstn, LivPrb, DiscFac, CRRA, PermGroFac, PermGroFacAgg, aXtraGrid, BoroCnstArt, Mgrid, AFunc, Rfunc, wFunc, DeprFac)

Solve one period of a consumption-saving problem with idiosyncratic and aggregate shocks (transitory and permanent). This is a basic solver that can’t handle cubic splines, nor can it calculate a value function.

Parameters:
  • solution_next (ConsumerSolution) – The solution to the succeeding one period problem.
  • IncomeDstn ([np.array]) – A list containing five arrays of floats, representing a discrete approximation to the income process between the period being solved and the one immediately following (in solution_next). Order: event probabilities, idisyncratic permanent shocks, idiosyncratic transitory shocks, aggregate permanent shocks, aggregate transitory shocks.
  • LivPrb (float) – Survival probability; likelihood of being alive at the beginning of the succeeding period.
  • DiscFac (float) – Intertemporal discount factor for future utility.
  • CRRA (float) – Coefficient of relative risk aversion.
  • PermGroFac (float) – Expected permanent income growth factor at the end of this period.
  • PermGroFacAgg (float) – Expected aggregate productivity growth factor.
  • aXtraGrid (np.array) – Array of “extra” end-of-period asset values– assets above the absolute minimum acceptable level.
  • BoroCnstArt (float) – Artificial borrowing constraint; minimum allowable end-of-period asset-to- permanent-income ratio. Unlike other models, this can’t be None.
  • Mgrid (np.array) – A grid of aggregate market resourses to permanent income in the economy.
  • AFunc (function) – Aggregate savings as a function of aggregate market resources.
  • Rfunc (function) – The net interest factor on assets as a function of capital ratio k.
  • wFunc (function) – The wage rate for labor as a function of capital-to-labor ratio k.
  • DeprFac (float) – Capital Depreciation Rate
Returns:

solution_now – The solution to the single period consumption-saving problem. Includes a consumption function cFunc (linear interpolation over linear interpola- tions) and marginal value function vPfunc.

Return type:

ConsumerSolution

Classes to solve consumption-saving models with idiosyncratic shocks to income in which shocks are not necessarily fully transitory or fully permanent. Extends ConsIndShockModel by explicitly tracking persistent income as a state variable, and allows (log) persistent income to follow an AR1 process rather than random walk.

class HARK.ConsumptionSaving.ConsGenIncProcessModel.ConsGenIncProcessSolver(solution_next, IncomeDstn, LivPrb, DiscFac, CRRA, Rfree, pLvlNextFunc, BoroCnstArt, aXtraGrid, pLvlGrid, vFuncBool, CubicBool)

A class for solving one period problem of a consumer who experiences persistent and transitory shocks to his income. Unlike in ConsIndShock, consumers do not necessarily have the same predicted level of p next period as this period (after controlling for growth). Instead, they have a function that translates current persistent income into expected next period persistent income (subject to shocks).

addMPCandHumanWealth(solution)

Take a solution and add human wealth and the bounding MPCs to it.

Parameters:
  • solution (ConsumerSolution) – The solution to this period’s consumption-saving problem.
  • Returns
  • ----------
  • solution – The solution to this period’s consumption-saving problem, but now with human wealth and the bounding MPCs.
addvPPfunc(solution)

Adds the marginal marginal value function to an existing solution, so that the next solver can evaluate vPP and thus use cubic interpolation.

Parameters:solution (ConsumerSolution) – The solution to this single period problem, which must include the consumption function.
Returns:solution – The same solution passed as input, but with the marginal marginal value function for this period added as the attribute vPPfunc.
Return type:ConsumerSolution
assignParameters(solution_next, IncomeDstn, LivPrb, DiscFac, CRRA, Rfree, pLvlNextFunc, BoroCnstArt, aXtraGrid, pLvlGrid, vFuncBool, CubicBool)

Assigns inputs as attributes of self for use by other methods

Parameters:
  • solution_next (ConsumerSolution) – The solution to next period’s one period problem.
  • IncomeDstn ([np.array]) – A list containing three arrays of floats, representing a discrete approximation to the income process between the period being solved and the one immediately following (in solution_next). Order: event probabilities, persistent shocks, transitory shocks.
  • LivPrb (float) – Survival probability; likelihood of being alive at the beginning of the succeeding period.
  • DiscFac (float) – Intertemporal discount factor for future utility.
  • CRRA (float) – Coefficient of relative risk aversion.
  • Rfree (float) – Risk free interest factor on end-of-period assets.
  • pLvlNextFunc (float) – Expected persistent income next period as a function of current pLvl.
  • BoroCnstArt (float or None) – Borrowing constraint for the minimum allowable assets to end the period with.
  • aXtraGrid (np.array) – Array of “extra” end-of-period (normalized) asset values– assets above the absolute minimum acceptable level.
  • pLvlGrid (np.array) – Array of persistent income levels at which to solve the problem.
  • vFuncBool (boolean) – An indicator for whether the value function should be computed and included in the reported solution.
  • CubicBool (boolean) – An indicator for whether the solver should use cubic or linear interpolation.
Returns:

Return type:

none

calcEndOfPrdvP()

Calculates end-of-period marginal value of assets at each state space point in aLvlNow x pLvlNow. Does so by taking a weighted sum of next period marginal values across income shocks (in preconstructed grids self.mLvlNext x self.pLvlNext).

Parameters:None
Returns:EndOfPrdVP – A 2D array of end-of-period marginal value of assets.
Return type:np.array
defBoroCnst(BoroCnstArt)

Defines the constrained portion of the consumption function as cFuncNowCnst, an attribute of self.

Parameters:BoroCnstArt (float or None) – Borrowing constraint for the minimum allowable assets to end the period with. If it is less than the natural borrowing constraint, then it is irrelevant; BoroCnstArt=None indicates no artificial bor- rowing constraint.
Returns:
Return type:None
getPointsForInterpolation(EndOfPrdvP, aLvlNow)

Finds endogenous interpolation points (c,m) for the consumption function.

Parameters:
  • EndOfPrdvP (np.array) – Array of end-of-period marginal values.
  • aLvlNow (np.array) – Array of end-of-period asset values that yield the marginal values in EndOfPrdvP.
Returns:

  • c_for_interpolation (np.array) – Consumption points for interpolation.
  • m_for_interpolation (np.array) – Corresponding market resource points for interpolation.

makeBasicSolution(EndOfPrdvP, aLvl, pLvl, interpolator)

Given end of period assets and end of period marginal value, construct the basic solution for this period.

Parameters:
  • EndOfPrdvP (np.array) – Array of end-of-period marginal values.
  • aLvl (np.array) – Array of end-of-period asset values that yield the marginal values in EndOfPrdvP.
  • pLvl (np.array) – Array of persistent income levels that yield the marginal values in EndOfPrdvP (corresponding pointwise to aLvl).
  • interpolator (function) – A function that constructs and returns a consumption function.
Returns:

solution_now – The solution to this period’s consumption-saving problem, with a consumption function, marginal value function, and minimum m.

Return type:

ConsumerSolution

makeCubiccFunc(mLvl, pLvl, cLvl)

Makes a quasi-cubic spline interpolation of the unconstrained consumption function for this period. Function is cubic splines with respect to mLvl, but linear in pLvl.

Parameters:
  • mLvl (np.array) – Market resource points for interpolation.
  • pLvl (np.array) – Persistent income level points for interpolation.
  • cLvl (np.array) – Consumption points for interpolation.
Returns:

cFuncUnc – The unconstrained consumption function for this period.

Return type:

CubicInterp

makeEndOfPrdvFunc(EndOfPrdvP)

Construct the end-of-period value function for this period, storing it as an attribute of self for use by other methods.

Parameters:EndOfPrdvP (np.array) – Array of end-of-period marginal value of assets corresponding to the asset values in self.aLvlNow x self.pLvlGrid.
Returns:
Return type:none
makeLinearcFunc(mLvl, pLvl, cLvl)

Makes a quasi-bilinear interpolation to represent the (unconstrained) consumption function.

Parameters:
  • mLvl (np.array) – Market resource points for interpolation.
  • pLvl (np.array) – Persistent income level points for interpolation.
  • cLvl (np.array) – Consumption points for interpolation.
Returns:

cFuncUnc – The unconstrained consumption function for this period.

Return type:

LinearInterp

makevFunc(solution)

Creates the value function for this period, defined over market resources m and persistent income p. self must have the attribute EndOfPrdvFunc in order to execute.

Parameters:solution (ConsumerSolution) – The solution to this single period problem, which must include the consumption function.
Returns:vFuncNow – A representation of the value function for this period, defined over market resources m and persistent income p: v = vFuncNow(m,p).
Return type:ValueFunc
makevPfunc(cFunc)

Constructs the marginal value function for this period.

Parameters:cFunc (function) – Consumption function this period, defined over market resources and persistent income level.
Returns:vPfunc – Marginal value (of market resources) function for this period.
Return type:function
prepareToCalcEndOfPrdvP()

Prepare to calculate end-of-period marginal value by creating an array of market resources that the agent could have next period, considering the grid of end-of-period normalized assets, the grid of persistent income levels, and the distribution of shocks he might experience next period.

Parameters:None
Returns:
  • aLvlNow (np.array) – 2D array of end-of-period assets; also stored as attribute of self.
  • pLvlNow (np.array) – 2D array of persistent income levels this period.
setAndUpdateValues(solution_next, IncomeDstn, LivPrb, DiscFac)

Unpacks some of the inputs (and calculates simple objects based on them), storing the results in self for use by other methods. These include: income shocks and probabilities, next period’s marginal value function (etc), the probability of getting the worst income shock next period, the patience factor, human wealth, and the bounding MPCs. Human wealth is stored as a function of persistent income.

Parameters:
  • solution_next (ConsumerSolution) – The solution to next period’s one period problem.
  • IncomeDstn ([np.array]) – A list containing three arrays of floats, representing a discrete approximation to the income process between the period being solved and the one immediately following (in solution_next). Order: event probabilities, persistent shocks, transitory shocks.
  • LivPrb (float) – Survival probability; likelihood of being alive at the beginning of the succeeding period.
  • DiscFac (float) – Intertemporal discount factor for future utility.
Returns:

Return type:

None

solve()

Solves a one period consumption saving problem with risky income, with persistent income explicitly tracked as a state variable.

Parameters:None
Returns:solution – The solution to the one period problem, including a consumption function (defined over market resources and persistent income), a marginal value function, bounding MPCs, and human wealth as a func- tion of persistent income. Might also include a value function and marginal marginal value function, depending on options selected.
Return type:ConsumerSolution
usePointsForInterpolation(cLvl, mLvl, pLvl, interpolator)

Constructs a basic solution for this period, including the consumption function and marginal value function.

Parameters:
  • cLvl (np.array) – Consumption points for interpolation.
  • mLvl (np.array) – Corresponding market resource points for interpolation.
  • pLvl (np.array) – Corresponding persistent income level points for interpolation.
  • interpolator (function) – A function that constructs and returns a consumption function.
Returns:

solution_now – The solution to this period’s consumption-saving problem, with a consumption function, marginal value function, and minimum m.

Return type:

ConsumerSolution

class HARK.ConsumptionSaving.ConsGenIncProcessModel.GenIncProcessConsumerType(cycles=0, time_flow=True, **kwds)

A consumer type with idiosyncratic shocks to persistent and transitory income. His problem is defined by a sequence of income distributions, survival prob- abilities, and persistent income growth functions, as well as time invariant values for risk aversion, discount factor, the interest rate, the grid of end-of-period assets, and an artificial borrowing constraint.

getControls()

Calculates consumption for each consumer of this type using the consumption functions.

Parameters:None
Returns:
Return type:None
getPostStates()

Calculates end-of-period assets for each consumer of this type. Identical to version in IndShockConsumerType but uses Lvl rather than Nrm variables.

Parameters:None
Returns:
Return type:None
getStates()

Calculates updated values of normalized market resources and persistent income level for each agent. Uses pLvlNow, aLvlNow, PermShkNow, TranShkNow.

Parameters:None
Returns:
Return type:None
installRetirementFunc()

Installs a special pLvlNextFunc representing retirement in the correct element of self.pLvlNextFunc. Draws on the attributes T_retire and pLvlNextFuncRet. If T_retire is zero or pLvlNextFuncRet does not exist, this method does nothing. Should only be called from within the method updatepLvlNextFunc, which ensures that time is flowing forward.

Parameters:None
Returns:
Return type:None
simBirth(which_agents)

Makes new consumers for the given indices. Initialized variables include aNrm and pLvl, as well as time variables t_age and t_cycle. Normalized assets and persistent income levels are drawn from lognormal distributions given by aNrmInitMean and aNrmInitStd (etc).

Parameters:which_agents (np.array(Bool)) – Boolean array of size self.AgentCount indicating which agents should be “born”.
Returns:
Return type:None
update()

Update the income process, the assets grid, the persistent income grid, and the terminal solution.

Parameters:None
Returns:
Return type:None
updateSolutionTerminal()

Update the terminal period solution. This method should be run when a new AgentType is created or when CRRA changes.

Parameters:None
Returns:
Return type:None
updatepLvlGrid()

Update the grid of persistent income levels. Currently only works for infinite horizon models (cycles=0) and lifecycle models (cycles=1). Not clear what to do about cycles>1 because the distribution of persistent income will be different within a period depending on how many cycles have elapsed. This method uses a simulation approach to generate the pLvlGrid at each period of the cycle, drawing on the initial distribution of persistent income, the pLvlNextFuncs, and the attribute pLvlPctiles.

Parameters:None
Returns:
Return type:None
updatepLvlNextFunc()

A dummy method that creates a trivial pLvlNextFunc attribute that has no persistent income dynamics. This method should be overwritten by subclasses in order to make (e.g.) an AR1 income process.

Parameters:None
Returns:
Return type:None
class HARK.ConsumptionSaving.ConsGenIncProcessModel.IndShockExplicitPermIncConsumerType(cycles=0, time_flow=True, **kwds)

A consumer type with idiosyncratic shocks to permanent and transitory income. The problem is defined by a sequence of income distributions, survival prob- abilities, and permanent income growth rates, as well as time invariant values for risk aversion, discount factor, the interest rate, the grid of end-of- period assets, and an artificial borrowing constraint. This agent type is identical to an IndShockConsumerType but for explicitly tracking pLvl as a state variable during solution. There is no real economic use for it.

updatepLvlNextFunc()

A method that creates the pLvlNextFunc attribute as a sequence of linear functions, indicating constant expected permanent income growth across permanent income levels. Draws on the attribute PermGroFac, and installs a special retirement function when it exists.

Parameters:None
Returns:
Return type:None
class HARK.ConsumptionSaving.ConsGenIncProcessModel.MargMargValueFunc2D(cFunc, CRRA)

A class for representing a marginal marginal value function in models where the standard envelope condition of v’(m,p) = u’(c(m,p)) holds (with CRRA utility).

class HARK.ConsumptionSaving.ConsGenIncProcessModel.MargValueFunc2D(cFunc, CRRA)

A class for representing a marginal value function in models where the standard envelope condition of v’(m,p) = u’(c(m,p)) holds (with CRRA utility). This is copied from ConsAggShockModel, with the second state variable re- labeled as persistent income p.

derivativeX(m, p)

Evaluate the first derivative with respect to market resources of the marginal value function at given levels of market resources m and per- manent income p.

Parameters:
  • m (float or np.array) – Market resources whose value is to be calcuated.
  • p (float or np.array) – Persistent income levels whose value is to be calculated.
Returns:

vPP – Marginal marginal value of market resources when beginning this period with market resources m and persistent income p; has same size as inputs m and p.

Return type:

float or np.array

class HARK.ConsumptionSaving.ConsGenIncProcessModel.PersistentShockConsumerType(cycles=0, time_flow=True, **kwds)

Type with idiosyncratic shocks to persistent (‘Prst’) and transitory income. The problem is defined by a sequence of income distributions, survival prob- abilities, and persistent income growth rates, as well as time invariant values for risk aversion, discount factor, the interest rate, the grid of end-of- period assets, an artificial borrowing constraint, and the AR1 correlation coefficient for (log) persistent income.

updatepLvlNextFunc()

A method that creates the pLvlNextFunc attribute as a sequence of AR1-style functions. Draws on the attributes PermGroFac and PrstIncCorr. If cycles=0, the product of PermGroFac across all periods must be 1.0, otherwise this method is invalid.

Parameters:None
Returns:
Return type:None
class HARK.ConsumptionSaving.ConsGenIncProcessModel.ValueFunc2D(vFuncNvrs, CRRA)

A class for representing a value function in a model where persistent income is explicitly included as a state variable. The underlying interpolation is in the space of (m,p) –> u_inv(v); this class “re-curves” to the value function.

class HARK.ConsumptionSaving.ConsGenIncProcessModel.pLvlFuncAR1(pLogMean, PermGroFac, Corr)

A class for representing AR1-style persistent income growth functions.

HARK.ConsumptionSaving.ConsGenIncProcessModel.solveConsGenIncProcess(solution_next, IncomeDstn, LivPrb, DiscFac, CRRA, Rfree, pLvlNextFunc, BoroCnstArt, aXtraGrid, pLvlGrid, vFuncBool, CubicBool)

Solves the one period problem of a consumer who experiences persistent and transitory shocks to his income. Unlike in ConsIndShock, consumers do not necessarily have expected persistent income growth that is constant with respect to their current level of pLvl. Instead, they have a function that translates current pLvl into expected next period pLvl (subject to shocks).

Parameters:
  • solution_next (ConsumerSolution) – The solution to next period’s one period problem.
  • IncomeDstn ([np.array]) – A list containing three arrays of floats, representing a discrete approximation to the income process between the period being solved and the one immediately following (in solution_next). Order: event probabilities, persistent shocks, transitory shocks.
  • LivPrb (float) – Survival probability; likelihood of being alive at the beginning of the succeeding period.
  • DiscFac (float) – Intertemporal discount factor for future utility.
  • CRRA (float) – Coefficient of relative risk aversion.
  • Rfree (float) – Risk free interest factor on end-of-period assets.
  • pLvlNextFunc (float) – Expected persistent income next period as a function of current pLvl.
  • BoroCnstArt (float or None) – Borrowing constraint for the minimum allowable assets to end the period with. Currently ignored, with BoroCnstArt=0 used implicitly.
  • aXtraGrid (np.array) – Array of “extra” end-of-period (normalized) asset values– assets above the absolute minimum acceptable level.
  • pLvlGrid (np.array) – Array of persistent income levels at which to solve the problem.
  • vFuncBool (boolean) – An indicator for whether the value function should be computed and included in the reported solution.
  • CubicBool (boolean) – An indicator for whether the solver should use cubic or linear interpolation.
Returns:

solution – The solution to the one period problem, including a consumption function (defined over market resources and persistent income), a marginal value function, bounding MPCs, and normalized human wealth.

Return type:

ConsumerSolution

Classes to solve canonical consumption-savings models with idiosyncratic shocks to income. All models here assume CRRA utility with geometric discounting, no bequest motive, and income shocks are fully transitory or fully permanent.

It currently solves three types of models:
  1. A very basic “perfect foresight” consumption-savings model with no uncertainty.
  2. A consumption-savings model with risk over transitory and permanent income shocks.
  3. The model described in (2), with an interest rate for debt that differs from the interest rate for savings.

See NARK for information on variable naming conventions. See HARK documentation for mathematical descriptions of the models being solved.

class HARK.ConsumptionSaving.ConsIndShockModel.ConsIndShockSetup(solution_next, IncomeDstn, LivPrb, DiscFac, CRRA, Rfree, PermGroFac, BoroCnstArt, aXtraGrid, vFuncBool, CubicBool)

A superclass for solvers of one period consumption-saving problems with constant relative risk aversion utility and permanent and transitory shocks to income. Has methods to set up but not solve the one period problem.

assignParameters(solution_next, IncomeDstn, LivPrb, DiscFac, CRRA, Rfree, PermGroFac, BoroCnstArt, aXtraGrid, vFuncBool, CubicBool)

Assigns period parameters as attributes of self for use by other methods

Parameters:
  • solution_next (ConsumerSolution) – The solution to next period’s one period problem.
  • IncomeDstn ([np.array]) – A list containing three arrays of floats, representing a discrete approximation to the income process between the period being solved and the one immediately following (in solution_next). Order: event probabilities, permanent shocks, transitory shocks.
  • LivPrb (float) – Survival probability; likelihood of being alive at the beginning of the succeeding period.
  • DiscFac (float) – Intertemporal discount factor for future utility.
  • CRRA (float) – Coefficient of relative risk aversion.
  • Rfree (float) – Risk free interest factor on end-of-period assets.
  • PermGroFac (float) – Expected permanent income growth factor at the end of this period.
  • BoroCnstArt (float or None) – Borrowing constraint for the minimum allowable assets to end the period with. If it is less than the natural borrowing constraint, then it is irrelevant; BoroCnstArt=None indicates no artificial bor- rowing constraint.
  • aXtraGrid (np.array) – Array of “extra” end-of-period asset values– assets above the absolute minimum acceptable level.
  • vFuncBool (boolean) – An indicator for whether the value function should be computed and included in the reported solution.
  • CubicBool (boolean) – An indicator for whether the solver should use cubic or linear inter- polation.
Returns:

Return type:

none

defBoroCnst(BoroCnstArt)

Defines the constrained portion of the consumption function as cFuncNowCnst, an attribute of self. Uses the artificial and natural borrowing constraints.

Parameters:BoroCnstArt (float or None) – Borrowing constraint for the minimum allowable assets to end the period with. If it is less than the natural borrowing constraint, then it is irrelevant; BoroCnstArt=None indicates no artificial bor- rowing constraint.
Returns:
Return type:none
defUtilityFuncs()

Defines CRRA utility function for this period (and its derivatives, and their inverses), saving them as attributes of self for other methods to use.

Parameters:none
Returns:
Return type:none
prepareToSolve()

Perform preparatory work before calculating the unconstrained consumption function.

Parameters:none
Returns:
Return type:none
setAndUpdateValues(solution_next, IncomeDstn, LivPrb, DiscFac)

Unpacks some of the inputs (and calculates simple objects based on them), storing the results in self for use by other methods. These include: income shocks and probabilities, next period’s marginal value function (etc), the probability of getting the worst income shock next period, the patience factor, human wealth, and the bounding MPCs.

Parameters:
  • solution_next (ConsumerSolution) – The solution to next period’s one period problem.
  • IncomeDstn ([np.array]) – A list containing three arrays of floats, representing a discrete approximation to the income process between the period being solved and the one immediately following (in solution_next). Order: event probabilities, permanent shocks, transitory shocks.
  • LivPrb (float) – Survival probability; likelihood of being alive at the beginning of the succeeding period.
  • DiscFac (float) – Intertemporal discount factor for future utility.
Returns:

Return type:

None

class HARK.ConsumptionSaving.ConsIndShockModel.ConsIndShockSolver(solution_next, IncomeDstn, LivPrb, DiscFac, CRRA, Rfree, PermGroFac, BoroCnstArt, aXtraGrid, vFuncBool, CubicBool)

This class solves a single period of a standard consumption-saving problem. It inherits from ConsIndShockSolverBasic, adding the ability to perform cubic interpolation and to calculate the value function.

addvFunc(solution, EndOfPrdvP)

Creates the value function for this period and adds it to the solution.

Parameters:
  • solution (ConsumerSolution) – The solution to this single period problem, likely including the consumption function, marginal value function, etc.
  • EndOfPrdvP (np.array) – Array of end-of-period marginal value of assets corresponding to the asset values in self.aNrmNow.
Returns:

solution – The single period solution passed as an input, but now with the value function (defined over market resources m) as an attribute.

Return type:

ConsumerSolution

addvPPfunc(solution)

Adds the marginal marginal value function to an existing solution, so that the next solver can evaluate vPP and thus use cubic interpolation.

Parameters:solution (ConsumerSolution) – The solution to this single period problem, which must include the consumption function.
Returns:solution – The same solution passed as input, but with the marginal marginal value function for this period added as the attribute vPPfunc.
Return type:ConsumerSolution
makeCubiccFunc(mNrm, cNrm)

Makes a cubic spline interpolation of the unconstrained consumption function for this period.

Parameters:
  • mNrm (np.array) – Corresponding market resource points for interpolation.
  • cNrm (np.array) – Consumption points for interpolation.
Returns:

cFuncUnc – The unconstrained consumption function for this period.

Return type:

CubicInterp

makeEndOfPrdvFunc(EndOfPrdvP)

Construct the end-of-period value function for this period, storing it as an attribute of self for use by other methods.

Parameters:EndOfPrdvP (np.array) – Array of end-of-period marginal value of assets corresponding to the asset values in self.aNrmNow.
Returns:
Return type:none
makevFunc(solution)

Creates the value function for this period, defined over market resources m. self must have the attribute EndOfPrdvFunc in order to execute.

Parameters:solution (ConsumerSolution) – The solution to this single period problem, which must include the consumption function.
Returns:vFuncNow – A representation of the value function for this period, defined over normalized market resources m: v = vFuncNow(m).
Return type:ValueFunc
solve()

Solves the single period consumption-saving problem using the method of endogenous gridpoints. Solution includes a consumption function cFunc (using cubic or linear splines), a marginal value function vPfunc, a min- imum acceptable level of normalized market resources mNrmMin, normalized human wealth hNrm, and bounding MPCs MPCmin and MPCmax. It might also have a value function vFunc and marginal marginal value function vPPfunc.

Parameters:none
Returns:solution – The solution to the single period consumption-saving problem.
Return type:ConsumerSolution
class HARK.ConsumptionSaving.ConsIndShockModel.ConsIndShockSolverBasic(solution_next, IncomeDstn, LivPrb, DiscFac, CRRA, Rfree, PermGroFac, BoroCnstArt, aXtraGrid, vFuncBool, CubicBool)

This class solves a single period of a standard consumption-saving problem, using linear interpolation and without the ability to calculate the value function. ConsIndShockSolver inherits from this class and adds the ability to perform cubic interpolation and to calculate the value function.

Note that this class does not have its own initializing method. It initial- izes the same problem in the same way as ConsIndShockSetup, from which it inherits.

addMPCandHumanWealth(solution)

Take a solution and add human wealth and the bounding MPCs to it.

Parameters:
  • solution (ConsumerSolution) – The solution to this period’s consumption-saving problem.
  • Returns
  • ----------
  • solution – The solution to this period’s consumption-saving problem, but now with human wealth and the bounding MPCs.
calcEndOfPrdvP()

Calculate end-of-period marginal value of assets at each point in aNrmNow. Does so by taking a weighted sum of next period marginal values across income shocks (in a preconstructed grid self.mNrmNext).

Parameters:none
Returns:EndOfPrdvP – A 1D array of end-of-period marginal value of assets
Return type:np.array
getPointsForInterpolation(EndOfPrdvP, aNrmNow)

Finds interpolation points (c,m) for the consumption function.

Parameters:
  • EndOfPrdvP (np.array) – Array of end-of-period marginal values.
  • aNrmNow (np.array) – Array of end-of-period asset values that yield the marginal values in EndOfPrdvP.
Returns:

  • c_for_interpolation (np.array) – Consumption points for interpolation.
  • m_for_interpolation (np.array) – Corresponding market resource points for interpolation.

makeBasicSolution(EndOfPrdvP, aNrm, interpolator)

Given end of period assets and end of period marginal value, construct the basic solution for this period.

Parameters:
  • EndOfPrdvP (np.array) – Array of end-of-period marginal values.
  • aNrm (np.array) – Array of end-of-period asset values that yield the marginal values in EndOfPrdvP.
  • interpolator (function) – A function that constructs and returns a consumption function.
Returns:

solution_now – The solution to this period’s consumption-saving problem, with a consumption function, marginal value function, and minimum m.

Return type:

ConsumerSolution

makeLinearcFunc(mNrm, cNrm)

Makes a linear interpolation to represent the (unconstrained) consumption function.

Parameters:
  • mNrm (np.array) – Corresponding market resource points for interpolation.
  • cNrm (np.array) – Consumption points for interpolation.
Returns:

cFuncUnc – The unconstrained consumption function for this period.

Return type:

LinearInterp

prepareToCalcEndOfPrdvP()

Prepare to calculate end-of-period marginal value by creating an array of market resources that the agent could have next period, considering the grid of end-of-period assets and the distribution of shocks he might experience next period.

Parameters:none
Returns:aNrmNow – A 1D array of end-of-period assets; also stored as attribute of self.
Return type:np.array
solve()

Solves a one period consumption saving problem with risky income.

Parameters:None
Returns:solution – The solution to the one period problem.
Return type:ConsumerSolution
usePointsForInterpolation(cNrm, mNrm, interpolator)

Constructs a basic solution for this period, including the consumption function and marginal value function.

Parameters:
  • cNrm (np.array) – (Normalized) consumption points for interpolation.
  • mNrm (np.array) – (Normalized) corresponding market resource points for interpolation.
  • interpolator (function) – A function that constructs and returns a consumption function.
Returns:

solution_now – The solution to this period’s consumption-saving problem, with a consumption function, marginal value function, and minimum m.

Return type:

ConsumerSolution

class HARK.ConsumptionSaving.ConsIndShockModel.ConsKinkedRsolver(solution_next, IncomeDstn, LivPrb, DiscFac, CRRA, Rboro, Rsave, PermGroFac, BoroCnstArt, aXtraGrid, vFuncBool, CubicBool)

A class to solve a single period consumption-saving problem where the interest rate on debt differs from the interest rate on savings. Inherits from ConsIndShockSolver, with nearly identical inputs and outputs. The key diff- erence is that Rfree is replaced by Rsave (a>0) and Rboro (a<0). The solver can handle Rboro == Rsave, which makes it identical to ConsIndShocksolver, but it terminates immediately if Rboro < Rsave, as this has a different solution.

makeCubiccFunc(mNrm, cNrm)

Makes a cubic spline interpolation that contains the kink of the unconstrained consumption function for this period.

Parameters:
  • mNrm (np.array) – Corresponding market resource points for interpolation.
  • cNrm (np.array) – Consumption points for interpolation.
Returns:

cFuncUnc – The unconstrained consumption function for this period.

Return type:

CubicInterp

prepareToCalcEndOfPrdvP()

Prepare to calculate end-of-period marginal value by creating an array of market resources that the agent could have next period, considering the grid of end-of-period assets and the distribution of shocks he might experience next period. This differs from the baseline case because different savings choices yield different interest rates.

Parameters:none
Returns:aNrmNow – A 1D array of end-of-period assets; also stored as attribute of self.
Return type:np.array
class HARK.ConsumptionSaving.ConsIndShockModel.ConsPerfForesightSolver(solution_next, DiscFac, LivPrb, CRRA, Rfree, PermGroFac, BoroCnstArt, MaxKinks)

A class for solving a one period perfect foresight consumption-saving problem. An instance of this class is created by the function solvePerfForesight in each period.

addSSmNrm(solution)

Finds steady state (normalized) market resources and adds it to the solution. This is the level of market resources such that the expectation of market resources in the next period is unchanged. This value doesn’t necessarily exist.

Parameters:solution (ConsumerSolution) – Solution to this period’s problem, which must have attribute cFunc.
Returns:solution – Same solution that was passed, but now with the attribute mNrmSS.
Return type:ConsumerSolution
assignParameters(solution_next, DiscFac, LivPrb, CRRA, Rfree, PermGroFac, BoroCnstArt, MaxKinks)

Saves necessary parameters as attributes of self for use by other methods.

Parameters:
  • solution_next (ConsumerSolution) – The solution to next period’s one period problem.
  • DiscFac (float) – Intertemporal discount factor for future utility.
  • LivPrb (float) – Survival probability; likelihood of being alive at the beginning of the succeeding period.
  • CRRA (float) – Coefficient of relative risk aversion.
  • Rfree (float) – Risk free interest factor on end-of-period assets.
  • PermGroFac (float) – Expected permanent income growth factor at the end of this period.
  • BoroCnstArt (float or None) – Artificial borrowing constraint, as a multiple of permanent income. Can be None, indicating no artificial constraint.
  • MaxKinks (int) – Maximum number of kink points to allow in the consumption function; additional points will be thrown out.
Returns:

Return type:

None

defUtilityFuncs()

Defines CRRA utility function for this period (and its derivatives), saving them as attributes of self for other methods to use.

Parameters:None
Returns:
Return type:None
defValueFuncs()
Defines the value and marginal value functions for this period. Uses the fact that for a perfect foresight CRRA utility problem, if the MPC in period t is \(\kappa_{t}\), and relative risk aversion :math:`
ho`, then the inverse value vFuncNvrs has a
constant slope of :math:`kappa_{t}^{-

ho/(1- ho)}` and

vFuncNvrs has value of zero at the lower bound of market resources mNrmMin. See PerfForesightConsumerType.ipynb documentation notebook for a brief explanation and the links below for a fuller treatment.

https://econ.jhu.edu/people/ccarroll/public/lecturenotes/consumption/PerfForesightCRRA/#vFuncAnalytical https://econ.jhu.edu/people/ccarroll/SolvingMicroDSOPs/#vFuncPF

None

None

makePFcFunc()

Makes the (linear) consumption function for this period.

Parameters:None
Returns:
Return type:None
solve()

Solves the one period perfect foresight consumption-saving problem.

Parameters:None
Returns:solution – The solution to this period’s problem.
Return type:ConsumerSolution
class HARK.ConsumptionSaving.ConsIndShockModel.ConsumerSolution(cFunc=None, vFunc=None, vPfunc=None, vPPfunc=None, mNrmMin=None, hNrm=None, MPCmin=None, MPCmax=None)

A class representing the solution of a single period of a consumption-saving problem. The solution must include a consumption function and marginal value function.

Here and elsewhere in the code, Nrm indicates that variables are normalized by permanent income.

appendSolution(new_solution)

Appends one solution to another to create a ConsumerSolution whose attributes are lists. Used in ConsMarkovModel, where we append solutions conditional on a particular value of a Markov state to each other in order to get the entire solution.

Parameters:new_solution (ConsumerSolution) – The solution to a consumption-saving problem; each attribute is a list representing state-conditional values or functions.
Returns:
Return type:None
class HARK.ConsumptionSaving.ConsIndShockModel.IndShockConsumerType(cycles=1, time_flow=True, verbose=False, quiet=False, **kwds)

A consumer type with idiosyncratic shocks to permanent and transitory income. His problem is defined by a sequence of income distributions, survival prob- abilities, and permanent income growth rates, as well as time invariant values for risk aversion, discount factor, the interest rate, the grid of end-of- period assets, and an artificial borrowing constraint.

calcBoundingValues()

Calculate human wealth plus minimum and maximum MPC in an infinite horizon model with only one period repeated indefinitely. Store results as attributes of self. Human wealth is the present discounted value of expected future income after receiving income this period, ignoring mort- ality. The maximum MPC is the limit of the MPC as m –> mNrmMin. The minimum MPC is the limit of the MPC as m –> infty.

Parameters:None
Returns:
Return type:None
checkConditions(verbose=False, public_call=True)

This method checks whether the instance’s type satisfies the Growth Impatience Condition (GIC), Return Impatience Condition (RIC), Absolute Impatience Condition (AIC), Weak Return Impatience Condition (WRIC), Finite Human Wealth Condition (FHWC) and Finite Value of Autarky Condition (FVAC). These are the conditions that are sufficient for nondegenerate infinite horizon solutions when there is a 1 period cycle. Depending on the model at hand, a different combination of these conditions must be satisfied. (For an exposition of the conditions, see http://econ.jhu.edu/people/ccarroll/papers/BufferStockTheory/)

Parameters:verbose (boolean) – Specifies different levels of verbosity of feedback. When False, it only reports whether the instance’s type fails to satisfy a particular condition. When True, it reports all results, i.e. the factor values for all conditions.
Returns:
Return type:None
getShocks()

Gets permanent and transitory income shocks for this period. Samples from IncomeDstn for each period in the cycle.

Parameters:None
Returns:
Return type:None
makeEulerErrorFunc(mMax=100, approx_inc_dstn=True)

Creates a “normalized Euler error” function for this instance, mapping from market resources to “consumption error per dollar of consumption.” Stores result in attribute eulerErrorFunc as an interpolated function. Has option to use approximate income distribution stored in self.IncomeDstn or to use a (temporary) very dense approximation.

Only works on (one period) infinite horizon models at this time, will be generalized later.

Parameters:
  • mMax (float) – Maximum normalized market resources for the Euler error function.
  • approx_inc_dstn (Boolean) – Indicator for whether to use the approximate discrete income distri- bution stored in self.IncomeDstn[0], or to use a very accurate discrete approximation instead. When True, uses approximation in IncomeDstn; when False, makes and uses a very dense approximation.
Returns:

Return type:

None

update()

Update the income process, the assets grid, and the terminal solution.

Parameters:none
Returns:
Return type:none
updateAssetsGrid()

Updates this agent’s end-of-period assets grid by constructing a multi- exponentially spaced grid of aXtra values.

Parameters:none
Returns:
Return type:none
updateIncomeProcess()

Updates this agent’s income process based on his own attributes.

Parameters:
  • none
  • Returns
  • -----------
  • none
class HARK.ConsumptionSaving.ConsIndShockModel.KinkedRconsumerType(cycles=1, time_flow=True, **kwds)

A consumer type that faces idiosyncratic shocks to income and has a different interest factor on saving vs borrowing. Extends IndShockConsumerType, with very small changes. Solver for this class is currently only compatible with linear spline interpolation.

calcBoundingValues()

Calculate human wealth plus minimum and maximum MPC in an infinite horizon model with only one period repeated indefinitely. Store results as attributes of self. Human wealth is the present discounted value of expected future income after receiving income this period, ignoring mort- ality. The maximum MPC is the limit of the MPC as m –> mNrmMin. The minimum MPC is the limit of the MPC as m –> infty. This version deals with the different interest rates on borrowing vs saving.

Parameters:None
Returns:
Return type:None
checkConditions(verbose=False)

This method checks whether the instance’s type satisfies the Growth Impatience Condition (GIC), Return Impatience Condition (RIC), Absolute Impatience Condition (AIC), Weak Return Impatience Condition (WRIC), Finite Human Wealth Condition (FHWC) and Finite Value of Autarky Condition (FVAC). These are the conditions that are sufficient for nondegenerate infinite horizon solutions with a 1 period cycle. Depending on the model at hand, a different combination of these conditions must be satisfied. To check which conditions are relevant to the model at hand, a reference to the relevant theoretical literature is made.

SHOULD BE INHERITED FROM ConsIndShockModel

Parameters:verbose (boolean) – Specifies different levels of verbosity of feedback. When False, it only reports whether the instance’s type fails to satisfy a particular condition. When True, it reports all results, i.e. the factor values for all conditions.
Returns:
Return type:None
getRfree()

Returns an array of size self.AgentCount with self.Rboro or self.Rsave in each entry, based on whether self.aNrmNow >< 0.

Parameters:None
Returns:RfreeNow – Array of size self.AgentCount with risk free interest rate for each agent.
Return type:np.array
makeEulerErrorFunc(mMax=100, approx_inc_dstn=True)

Creates a “normalized Euler error” function for this instance, mapping from market resources to “consumption error per dollar of consumption.” Stores result in attribute eulerErrorFunc as an interpolated function. Has option to use approximate income distribution stored in self.IncomeDstn or to use a (temporary) very dense approximation.

SHOULD BE INHERITED FROM ConsIndShockModel

Parameters:
  • mMax (float) – Maximum normalized market resources for the Euler error function.
  • approx_inc_dstn (Boolean) – Indicator for whether to use the approximate discrete income distri- bution stored in self.IncomeDstn[0], or to use a very accurate discrete approximation instead. When True, uses approximation in IncomeDstn; when False, makes and uses a very dense approximation.
Returns:

Return type:

None

class HARK.ConsumptionSaving.ConsIndShockModel.MargMargValueFunc(cFunc, CRRA)

A class for representing a marginal marginal value function in models where the standard envelope condition of v’(m) = u’(c(m)) holds (with CRRA utility).

class HARK.ConsumptionSaving.ConsIndShockModel.MargValueFunc(cFunc, CRRA)

A class for representing a marginal value function in models where the standard envelope condition of v’(m) = u’(c(m)) holds (with CRRA utility).

derivative(m)

Evaluate the derivative of the marginal value function at given levels of market resources m; this is the marginal marginal value function.

Parameters:m (float or np.array) – Market resources (normalized by permanent income) whose marginal marginal value is to be found.
Returns:vPP – Marginal marginal lifetime value of beginning this period with market resources m; has same size as input m.
Return type:float or np.array
class HARK.ConsumptionSaving.ConsIndShockModel.PerfForesightConsumerType(cycles=1, time_flow=True, verbose=False, quiet=False, **kwds)

A perfect foresight consumer type who has no uncertainty other than mortality. His problem is defined by a coefficient of relative risk aversion, intertemporal discount factor, interest factor, an artificial borrowing constraint (maybe) and time sequences of the permanent income growth rate and survival probability.

checkConditions(verbose=False, verbose_reference=False, public_call=False)

This method checks whether the instance’s type satisfies the Growth Impatience Condition (GIC), Return Impatience Condition (RIC), Absolute Impatience Condition (AIC), Weak Return Impatience Condition (WRIC), Finite Human Wealth Condition (FHWC) and Finite Value of Autarky Condition (FVAC). These are the conditions that are sufficient for nondegenerate solutions under infinite horizon with a 1 period cycle. Depending on the model at hand, a different combination of these conditions must be satisfied. To check which conditions are relevant to the model at hand, a reference to the relevant theoretical literature is made.

Parameters:verbose (boolean) – Specifies different levels of verbosity of feedback. When False, it only reports whether the instance’s type fails to satisfy a particular condition. When True, it reports all results, i.e. the factor values for all conditions.
Returns:
Return type:None
checkRestrictions()

A method to check that various restrictions are met for the model class.

getControls()

Calculates consumption for each consumer of this type using the consumption functions.

Parameters:None
Returns:
Return type:None
getPostStates()

Calculates end-of-period assets for each consumer of this type.

Parameters:None
Returns:
Return type:None
getRfree()

Returns an array of size self.AgentCount with self.Rfree in every entry.

Parameters:None
Returns:RfreeNow – Array of size self.AgentCount with risk free interest rate for each agent.
Return type:np.array
getShocks()

Finds permanent and transitory income “shocks” for each agent this period. As this is a perfect foresight model, there are no stochastic shocks: PermShkNow = PermGroFac for each agent (according to their t_cycle) and TranShkNow = 1.0 for all agents.

Parameters:None
Returns:
Return type:None
getStates()

Calculates updated values of normalized market resources and permanent income level for each agent. Uses pLvlNow, aNrmNow, PermShkNow, TranShkNow.

Parameters:None
Returns:
Return type:None
simBirth(which_agents)

Makes new consumers for the given indices. Initialized variables include aNrm and pLvl, as well as time variables t_age and t_cycle. Normalized assets and permanent income levels are drawn from lognormal distributions given by aNrmInitMean and aNrmInitStd (etc).

Parameters:which_agents (np.array(Bool)) – Boolean array of size self.AgentCount indicating which agents should be “born”.
Returns:
Return type:None
simDeath()

Determines which agents die this period and must be replaced. Uses the sequence in LivPrb to determine survival probabilities for each agent.

Parameters:None
Returns:which_agents – Boolean array of size AgentCount indicating which agents die.
Return type:np.array(bool)
unpackcFunc()

“Unpacks” the consumption functions into their own field for easier access. After the model has been solved, the consumption functions reside in the attribute cFunc of each element of ConsumerType.solution. This method creates a (time varying) attribute cFunc that contains a list of consumption functions.

Parameters:none
Returns:
Return type:none
updateSolutionTerminal()

Update the terminal period solution. This method should be run when a new AgentType is created or when CRRA changes.

Parameters:none
Returns:
Return type:none
class HARK.ConsumptionSaving.ConsIndShockModel.ValueFunc(vFuncNvrs, CRRA)

A class for representing a value function. The underlying interpolation is in the space of (m,u_inv(v)); this class “re-curves” to the value function.

HARK.ConsumptionSaving.ConsIndShockModel.applyFlatIncomeTax(IncomeDstn, tax_rate, T_retire, unemployed_indices=[], transitory_index=2)

Applies a flat income tax rate to all employed income states during the working period of life (those before T_retire). Time runs forward in this function.

Parameters:
  • IncomeDstn ([income distributions]) – The discrete approximation to the income distribution in each time period.
  • tax_rate (float) – A flat income tax rate to be applied to all employed income.
  • T_retire (int) – The time index after which the agent retires.
  • unemployed_indices ([int]) – Indices of transitory shocks that represent unemployment states (no tax).
  • transitory_index (int) – The index of each element of IncomeDstn representing transitory shocks.
Returns:

IncomeDstn_new – The updated income distributions, after applying the tax.

Return type:

[income distributions]

HARK.ConsumptionSaving.ConsIndShockModel.constructAssetsGrid(parameters)

Constructs the base grid of post-decision states, representing end-of-period assets above the absolute minimum.

All parameters are passed as attributes of the single input parameters. The input can be an instance of a ConsumerType, or a custom Parameters class.

Parameters:
  • aXtraMin (float) – Minimum value for the a-grid
  • aXtraMax (float) – Maximum value for the a-grid
  • aXtraCount (int) – Size of the a-grid
  • aXtraExtra ([float]) – Extra values for the a-grid.
  • exp_nest (int) – Level of nesting for the exponentially spaced grid
Returns:

aXtraGrid – Base array of values for the post-decision-state grid.

Return type:

np.ndarray

HARK.ConsumptionSaving.ConsIndShockModel.constructLognormalIncomeProcessUnemployment(parameters)

Generates a list of discrete approximations to the income process for each life period, from end of life to beginning of life. Permanent shocks are mean one lognormally distributed with standard deviation PermShkStd[t] during the working life, and degenerate at 1 in the retirement period. Transitory shocks are mean one lognormally distributed with a point mass at IncUnemp with probability UnempPrb while working; they are mean one with a point mass at IncUnempRet with probability UnempPrbRet. Retirement occurs after t=T_retire periods of working.

Note 1: All time in this function runs forward, from t=0 to t=T

Note 2: All parameters are passed as attributes of the input parameters.

PermShkStd : [float]
List of standard deviations in log permanent income uncertainty during the agent’s life.
PermShkCount : int
The number of approximation points to be used in the discrete approxima- tion to the permanent income shock distribution.
TranShkStd : [float]
List of standard deviations in log transitory income uncertainty during the agent’s life.
TranShkCount : int
The number of approximation points to be used in the discrete approxima- tion to the permanent income shock distribution.
UnempPrb : float
The probability of becoming unemployed during the working period.
UnempPrbRet : float
The probability of not receiving typical retirement income when retired.
T_retire : int
The index value for the final working period in the agent’s life. If T_retire <= 0 then there is no retirement.
IncUnemp : float
Transitory income received when unemployed.
IncUnempRet : float
Transitory income received while “unemployed” when retired.
T_cycle : int
Total number of non-terminal periods in the consumer’s sequence of periods.
Returns:
  • IncomeDstn ([[np.array]]) – A list with T_cycle elements, each of which is a list of three arrays representing a discrete approximation to the income process in a period. Order: probabilities, permanent shocks, transitory shocks.
  • PermShkDstn ([[np.array]]) – A list with T_cycle elements, each of which is a list of two arrays representing a discrete approximation to the permanent income shocks.
  • TranShkDstn ([[np.array]]) – A list with T_cycle elements, each of which is a list of two arrays representing a discrete approximation to the transitory income shocks.
HARK.ConsumptionSaving.ConsIndShockModel.solveConsIndShock(solution_next, IncomeDstn, LivPrb, DiscFac, CRRA, Rfree, PermGroFac, BoroCnstArt, aXtraGrid, vFuncBool, CubicBool)

Solves a single period consumption-saving problem with CRRA utility and risky income (subject to permanent and transitory shocks). Can generate a value function if requested; consumption function can be linear or cubic splines.

Parameters:
  • solution_next (ConsumerSolution) – The solution to next period’s one period problem.
  • IncomeDstn ([np.array]) – A list containing three arrays of floats, representing a discrete approximation to the income process between the period being solved and the one immediately following (in solution_next). Order: event probabilities, permanent shocks, transitory shocks.
  • LivPrb (float) – Survival probability; likelihood of being alive at the beginning of the succeeding period.
  • DiscFac (float) – Intertemporal discount factor for future utility.
  • CRRA (float) – Coefficient of relative risk aversion.
  • Rfree (float) – Risk free interest factor on end-of-period assets.
  • PermGroFac (float) – Expected permanent income growth factor at the end of this period.
  • BoroCnstArt (float or None) – Borrowing constraint for the minimum allowable assets to end the period with. If it is less than the natural borrowing constraint, then it is irrelevant; BoroCnstArt=None indicates no artificial bor- rowing constraint.
  • aXtraGrid (np.array) – Array of “extra” end-of-period asset values– assets above the absolute minimum acceptable level.
  • vFuncBool (boolean) – An indicator for whether the value function should be computed and included in the reported solution.
  • CubicBool (boolean) – Indicator for whether the solver should use cubic or linear interpolation.
Returns:

solution_now – The solution to the single period consumption-saving problem. Includes a consumption function cFunc (using cubic or linear splines), a marginal value function vPfunc, a minimum acceptable level of normalized market resources mNrmMin, normalized human wealth hNrm, and bounding MPCs MPCmin and MPCmax. It might also have a value function vFunc and marginal mar- ginal value function vPPfunc.

Return type:

ConsumerSolution

HARK.ConsumptionSaving.ConsIndShockModel.solveConsKinkedR(solution_next, IncomeDstn, LivPrb, DiscFac, CRRA, Rboro, Rsave, PermGroFac, BoroCnstArt, aXtraGrid, vFuncBool, CubicBool)

Solves a single period consumption-saving problem with CRRA utility and risky income (subject to permanent and transitory shocks), and different interest factors on borrowing and saving. Restriction: Rboro >= Rsave. Currently cannot construct a cubic spline consumption function, only linear. Can gen- erate a value function if requested.

Parameters:
  • solution_next (ConsumerSolution) – The solution to next period’s one period problem.
  • IncomeDstn ([np.array]) – A list containing three arrays of floats, representing a discrete approximation to the income process between the period being solved and the one immediately following (in solution_next). Order: event probabilities, permanent shocks, transitory shocks.
  • LivPrb (float) – Survival probability; likelihood of being alive at the beginning of the succeeding period.
  • DiscFac (float) – Intertemporal discount factor for future utility.
  • CRRA (float) – Coefficient of relative risk aversion.
  • Rboro (float) – Interest factor on assets between this period and the succeeding period when assets are negative.
  • Rsave (float) – Interest factor on assets between this period and the succeeding period when assets are positive.
  • PermGroFac (float) – Expected permanent income growth factor at the end of this period.
  • BoroCnstArt (float or None) – Borrowing constraint for the minimum allowable assets to end the period with. If it is less than the natural borrowing constraint, then it is irrelevant; BoroCnstArt=None indicates no artificial bor- rowing constraint.
  • aXtraGrid (np.array) – Array of “extra” end-of-period asset values– assets above the absolute minimum acceptable level.
  • vFuncBool (boolean) – An indicator for whether the value function should be computed and included in the reported solution.
  • CubicBool (boolean) – Indicator for whether the solver should use cubic or linear interpolation.
Returns:

solution_now – The solution to the single period consumption-saving problem. Includes a consumption function cFunc (using cubic or linear splines), a marginal value function vPfunc, a minimum acceptable level of normalized market resources mNrmMin, normalized human wealth hNrm, and bounding MPCs MPCmin and MPCmax. It might also have a value function vFunc.

Return type:

ConsumerSolution

HARK.ConsumptionSaving.ConsIndShockModel.solvePerfForesight(solution_next, DiscFac, LivPrb, CRRA, Rfree, PermGroFac, BoroCnstArt, MaxKinks)

Solves a single period consumption-saving problem for a consumer with perfect foresight.

Parameters:
  • solution_next (ConsumerSolution) – The solution to next period’s one period problem.
  • DiscFac (float) – Intertemporal discount factor for future utility.
  • LivPrb (float) – Survival probability; likelihood of being alive at the beginning of the succeeding period.
  • CRRA (float) – Coefficient of relative risk aversion.
  • Rfree (float) – Risk free interest factor on end-of-period assets.
  • PermGroFac (float) – Expected permanent income growth factor at the end of this period.
  • BoroCnstArt (float or None) – Artificial borrowing constraint, as a multiple of permanent income. Can be None, indicating no artificial constraint.
  • MaxKinks (int) – Maximum number of kink points to allow in the consumption function; additional points will be thrown out. Only relevant in infinite horizon models with artificial borrowing constraint.
Returns:

solution_now – The solution to this period’s problem.

Return type:

ConsumerSolution

Classes to solve and simulate consumption-savings model with a discrete, exogenous, stochastic Markov state. The only solver here extends ConsIndShockModel to include a Markov state; the interest factor, permanent growth factor, and income distribution can vary with the discrete state.

class HARK.ConsumptionSaving.ConsMarkovModel.ConsMarkovSolver(solution_next, IncomeDstn_list, LivPrb, DiscFac, CRRA, Rfree_list, PermGroFac_list, MrkvArray, BoroCnstArt, aXtraGrid, vFuncBool, CubicBool)

A class to solve a single period consumption-saving problem with risky income and stochastic transitions between discrete states, in a Markov fashion. Extends ConsIndShockSolver, with identical inputs but for a discrete Markov state, whose transition rule is summarized in MrkvArray. Markov states can differ in their interest factor, permanent growth factor, live probability, and income distribution, so the inputs Rfree, PermGroFac, IncomeDstn, and LivPrb are now arrays or lists specifying those values in each (succeeding) Markov state.

calcEndOfPrdvP()

Calculates end of period marginal value (and marginal marginal) value at each aXtra gridpoint for each current state, unconditional on the future Markov state (i.e. weighting conditional end-of-period marginal value by transition probabilities).

Parameters:none
Returns:
Return type:none
calcEndOfPrdvPP()

Calculates end-of-period marginal marginal value using a pre-defined array of next period market resources in self.mNrmNext.

Parameters:none
Returns:EndOfPrdvPP – End-of-period marginal marginal value of assets at each value in the grid of assets.
Return type:np.array
calcEndOfPrdvPcond()

Calculate end-of-period marginal value of assets at each point in aNrmNow conditional on a particular state occuring in the next period.

Parameters:None
Returns:EndOfPrdvP – A 1D array of end-of-period marginal value of assets.
Return type:np.array
calcHumWealthAndBoundingMPCs()

Calculates human wealth and the maximum and minimum MPC for each current period state, then stores them as attributes of self for use by other methods.

Parameters:none
Returns:
Return type:none
conditionOnState(state_index)

Temporarily assume that a particular Markov state will occur in the succeeding period, and condition solver attributes on this assumption. Allows the solver to construct the future-state-conditional marginal value function (etc) for that future state.

Parameters:state_index (int) – Index of the future Markov state to condition on.
Returns:
Return type:none
defBoundary()

Find the borrowing constraint for each current state and save it as an attribute of self for use by other methods.

Parameters:none
Returns:
Return type:none
makeCubiccFunc(mNrm, cNrm)

Make a cubic interpolation to represent the (unconstrained) consumption function conditional on the current period state.

Parameters:
  • mNrm (np.array) – Array of normalized market resource values for interpolation.
  • cNrm (np.array) – Array of normalized consumption values for interpolation.
Returns:

cFuncUnc

Return type:

an instance of HARK.interpolation.CubicInterp

makeEndOfPrdvFuncCond()

Construct the end-of-period value function conditional on next period’s state. NOTE: It might be possible to eliminate this method and replace it with ConsIndShockSolver.makeEndOfPrdvFunc, but the self.X_cond variables must be renamed.

Parameters:none
Returns:EndofPrdvFunc_cond – The end-of-period value function conditional on a particular state occuring in the next period.
Return type:ValueFunc
makeEndOfPrdvPfuncCond()

Construct the end-of-period marginal value function conditional on next period’s state.

Parameters:None
Returns:EndofPrdvPfunc_cond – The end-of-period marginal value function conditional on a particular state occuring in the succeeding period.
Return type:MargValueFunc
makeLinearcFunc(mNrm, cNrm)

Make a linear interpolation to represent the (unconstrained) consumption function conditional on the current period state.

Parameters:
  • mNrm (np.array) – Array of normalized market resource values for interpolation.
  • cNrm (np.array) – Array of normalized consumption values for interpolation.
Returns:

cFuncUnc

Return type:

an instance of HARK.interpolation.LinearInterp

makeSolution(cNrm, mNrm)

Construct an object representing the solution to this period’s problem.

Parameters:
  • cNrm (np.array) – Array of normalized consumption values for interpolation. Each row corresponds to a Markov state for this period.
  • mNrm (np.array) – Array of normalized market resource values for interpolation. Each row corresponds to a Markov state for this period.
Returns:

solution – The solution to the single period consumption-saving problem. Includes a consumption function cFunc (using cubic or linear splines), a marg- inal value function vPfunc, a minimum acceptable level of normalized market resources mNrmMin, normalized human wealth hNrm, and bounding MPCs MPCmin and MPCmax. It might also have a value function vFunc and marginal marginal value function vPPfunc. All of these attributes are lists or arrays, with elements corresponding to the current Markov state. E.g. solution.cFunc[0] is the consumption function when in the i=0 Markov state this period.

Return type:

ConsumerSolution

makevFunc(solution)

Construct the value function for each current state.

Parameters:solution (ConsumerSolution) – The solution to the single period consumption-saving problem. Must have a consumption function cFunc (using cubic or linear splines) as a list with elements corresponding to the current Markov state. E.g. solution.cFunc[0] is the consumption function when in the i=0 Markov state this period.
Returns:vFuncNow – A list of value functions (defined over normalized market resources m) for each current period Markov state.
Return type:[ValueFunc]
solve()

Solve the one period problem of the consumption-saving model with a Markov state.

Parameters:none
Returns:solution – The solution to the single period consumption-saving problem. Includes a consumption function cFunc (using cubic or linear splines), a marg- inal value function vPfunc, a minimum acceptable level of normalized market resources mNrmMin, normalized human wealth hNrm, and bounding MPCs MPCmin and MPCmax. It might also have a value function vFunc and marginal marginal value function vPPfunc. All of these attributes are lists or arrays, with elements corresponding to the current Markov state. E.g. solution.cFunc[0] is the consumption function when in the i=0 Markov state this period.
Return type:ConsumerSolution
class HARK.ConsumptionSaving.ConsMarkovModel.MarkovConsumerType(cycles=1, time_flow=True, **kwds)

An agent in the Markov consumption-saving model. His problem is defined by a sequence of income distributions, survival probabilities, discount factors, and permanent income growth rates, as well as time invariant values for risk aversion, the interest rate, the grid of end-of-period assets, and how he is borrowing constrained.

calcBoundingValues()

Calculate human wealth plus minimum and maximum MPC in an infinite horizon model with only one period repeated indefinitely. Store results as attributes of self. Human wealth is the present discounted value of expected future income after receiving income this period, ignoring mort- ality. The maximum MPC is the limit of the MPC as m –> mNrmMin. The minimum MPC is the limit of the MPC as m –> infty. Results are all np.array with elements corresponding to each Markov state.

NOT YET IMPLEMENTED FOR THIS CLASS

Parameters:None
Returns:
Return type:None
checkMarkovInputs()

Many parameters used by MarkovConsumerType are arrays. Make sure those arrays are the right shape.

Parameters:None
Returns:
Return type:None
getControls()

Calculates consumption for each consumer of this type using the consumption functions.

Parameters:None
Returns:
Return type:None
getRfree()

Returns an array of size self.AgentCount with interest factor that varies with discrete state.

Parameters:None
Returns:RfreeNow – Array of size self.AgentCount with risk free interest rate for each agent.
Return type:np.array
getShocks()

Gets new Markov states and permanent and transitory income shocks for this period. Samples from IncomeDstn for each period-state in the cycle.

Parameters:None
Returns:
Return type:None
makeEulerErrorFunc(mMax=100, approx_inc_dstn=True)

Creates a “normalized Euler error” function for this instance, mapping from market resources to “consumption error per dollar of consumption.” Stores result in attribute eulerErrorFunc as an interpolated function. Has option to use approximate income distribution stored in self.IncomeDstn or to use a (temporary) very dense approximation.

NOT YET IMPLEMENTED FOR THIS CLASS

Parameters:
  • mMax (float) – Maximum normalized market resources for the Euler error function.
  • approx_inc_dstn (Boolean) – Indicator for whether to use the approximate discrete income distri- bution stored in self.IncomeDstn[0], or to use a very accurate discrete approximation instead. When True, uses approximation in IncomeDstn; when False, makes and uses a very dense approximation.
Returns:

Return type:

None

preSolve()

Check to make sure that the inputs that are specific to MarkovConsumerType are of the right shape (if arrays) or length (if lists).

Parameters:None
Returns:
Return type:None
readShocks()

A slight modification of AgentType.readShocks that makes sure that MrkvNow is int, not float.

Parameters:None
Returns:
Return type:None
simBirth(which_agents)

Makes new Markov consumer by drawing initial normalized assets, permanent income levels, and discrete states. Calls IndShockConsumerType.simBirth, then draws from initial Markov distribution.

Parameters:which_agents (np.array(Bool)) – Boolean array of size self.AgentCount indicating which agents should be “born”.
Returns:
Return type:None
simDeath()

Determines which agents die this period and must be replaced. Uses the sequence in LivPrb to determine survival probabilities for each agent.

Parameters:None
Returns:which_agents – Boolean array of size AgentCount indicating which agents die.
Return type:np.array(bool)
updateSolutionTerminal()

Update the terminal period solution. This method should be run when a new AgentType is created or when CRRA changes.

Parameters:none
Returns:
Return type:none
HARK.ConsumptionSaving.ConsMarkovModel.solveConsMarkov(solution_next, IncomeDstn, LivPrb, DiscFac, CRRA, Rfree, PermGroFac, MrkvArray, BoroCnstArt, aXtraGrid, vFuncBool, CubicBool)

Solves a single period consumption-saving problem with risky income and stochastic transitions between discrete states, in a Markov fashion. Has identical inputs as solveConsIndShock, except for a discrete Markov transitionrule MrkvArray. Markov states can differ in their interest factor, permanent growth factor, and income distribution, so the inputs Rfree, PermGroFac, and IncomeDstn are arrays or lists specifying those values in each (succeeding) Markov state.

Parameters:
  • solution_next (ConsumerSolution) – The solution to next period’s one period problem.
  • IncomeDstn_list ([[np.array]]) – A length N list of income distributions in each succeeding Markov state. Each income distribution contains three arrays of floats, representing a discrete approximation to the income process at the beginning of the succeeding period. Order: event probabilities, permanent shocks, transitory shocks.
  • LivPrb (float) – Survival probability; likelihood of being alive at the beginning of the succeeding period.
  • DiscFac (float) – Intertemporal discount factor for future utility.
  • CRRA (float) – Coefficient of relative risk aversion.
  • Rfree_list (np.array) – Risk free interest factor on end-of-period assets for each Markov state in the succeeding period.
  • PermGroGac_list (float) – Expected permanent income growth factor at the end of this period for each Markov state in the succeeding period.
  • MrkvArray (numpy.array) – An NxN array representing a Markov transition matrix between discrete states. The i,j-th element of MrkvArray is the probability of moving from state i in period t to state j in period t+1.
  • BoroCnstArt (float or None) – Borrowing constraint for the minimum allowable assets to end the period with. If it is less than the natural borrowing constraint, then it is irrelevant; BoroCnstArt=None indicates no artificial bor- rowing constraint.
  • aXtraGrid (np.array) – Array of “extra” end-of-period asset values– assets above the absolute minimum acceptable level.
  • vFuncBool (boolean) – An indicator for whether the value function should be computed and included in the reported solution.
  • CubicBool (boolean) – An indicator for whether the solver should use cubic or linear inter- polation.
Returns:

solution – The solution to the single period consumption-saving problem. Includes a consumption function cFunc (using cubic or linear splines), a marg- inal value function vPfunc, a minimum acceptable level of normalized market resources mNrmMin, normalized human wealth hNrm, and bounding MPCs MPCmin and MPCmax. It might also have a value function vFunc and marginal marginal value function vPPfunc. All of these attributes are lists or arrays, with elements corresponding to the current Markov state. E.g. solution.cFunc[0] is the consumption function when in the i=0 Markov state this period.

Return type:

ConsumerSolution

Consumption-saving models that also include medical spending.

class HARK.ConsumptionSaving.ConsMedModel.ConsMedShockSolver(solution_next, IncomeDstn, MedShkDstn, LivPrb, DiscFac, CRRA, CRRAmed, Rfree, MedPrice, pLvlNextFunc, BoroCnstArt, aXtraGrid, pLvlGrid, vFuncBool, CubicBool)

Class for solving the one period problem for the “medical shocks” model, in which consumers receive shocks to permanent and transitory income as well as shocks to “medical need”– multiplicative utility shocks for a second good.

addvPPfunc(solution)

Adds the marginal marginal value function to an existing solution, so that the next solver can evaluate vPP and thus use cubic interpolation.

Parameters:solution (ConsumerSolution) – The solution to this single period problem, which must include the consumption function.
Returns:solution – The same solution passed as input, but with the marginal marginal value function for this period added as the attribute vPPfunc.
Return type:ConsumerSolution
defBoroCnst(BoroCnstArt)

Defines the constrained portion of the consumption function as cFuncNowCnst, an attribute of self. Uses the artificial and natural borrowing constraints.

Parameters:BoroCnstArt (float or None) – Borrowing constraint for the minimum allowable (normalized) assets to end the period with. If it is less than the natural borrowing constraint at a particular permanent income level, then it is irrelevant; BoroCnstArt=None indicates no artificial borrowing constraint.
Returns:
Return type:None
defUtilityFuncs()

Defines CRRA utility function for this period (and its derivatives, and their inverses), saving them as attributes of self for other methods to use. Extends version from ConsIndShock models by also defining inverse marginal utility function over medical care.

Parameters:none
Returns:
Return type:none
getPointsForInterpolation(EndOfPrdvP, aLvlNow)

Finds endogenous interpolation points (x,m) for the expenditure function.

Parameters:
  • EndOfPrdvP (np.array) – Array of end-of-period marginal values.
  • aLvlNow (np.array) – Array of end-of-period asset values that yield the marginal values in EndOfPrdvP.
Returns:

  • x_for_interpolation (np.array) – Total expenditure points for interpolation.
  • m_for_interpolation (np.array) – Corresponding market resource points for interpolation.
  • p_for_interpolation (np.array) – Corresponding permanent income points for interpolation.

makeBasicSolution(EndOfPrdvP, aLvl, interpolator)

Given end of period assets and end of period marginal value, construct the basic solution for this period.

Parameters:
  • EndOfPrdvP (np.array) – Array of end-of-period marginal values.
  • aLvl (np.array) – Array of end-of-period asset values that yield the marginal values in EndOfPrdvP.
  • interpolator (function) – A function that constructs and returns a consumption function.
Returns:

solution_now – The solution to this period’s consumption-saving problem, with a consumption function, marginal value function, and minimum m.

Return type:

ConsumerSolution

makeCubicxFunc(mLvl, pLvl, MedShk, xLvl)

Constructs the (unconstrained) expenditure function for this period using bilinear interpolation (over permanent income and the medical shock) among an array of cubic interpolations over market resources.

Parameters:
  • mLvl (np.array) – Corresponding market resource points for interpolation.
  • pLvl (np.array) – Corresponding permanent income level points for interpolation.
  • MedShk (np.array) – Corresponding medical need shocks for interpolation.
  • xLvl (np.array) – Expenditure points for interpolation, corresponding to those in mLvl, pLvl, and MedShk.
Returns:

xFuncUnc – Unconstrained total expenditure function for this period.

Return type:

BilinearInterpOnInterp1D

makeLinearxFunc(mLvl, pLvl, MedShk, xLvl)

Constructs the (unconstrained) expenditure function for this period using bilinear interpolation (over permanent income and the medical shock) among an array of linear interpolations over market resources.

Parameters:
  • mLvl (np.array) – Corresponding market resource points for interpolation.
  • pLvl (np.array) – Corresponding permanent income level points for interpolation.
  • MedShk (np.array) – Corresponding medical need shocks for interpolation.
  • xLvl (np.array) – Expenditure points for interpolation, corresponding to those in mLvl, pLvl, and MedShk.
Returns:

xFuncUnc – Unconstrained total expenditure function for this period.

Return type:

BilinearInterpOnInterp1D

makevAndvPfuncs(policyFunc)

Constructs the marginal value function for this period.

Parameters:policyFunc (function) – Consumption and medical care function for this period, defined over market resources, permanent income level, and the medical need shock.
Returns:
  • vFunc (function) – Value function for this period, defined over market resources and permanent income.
  • vPfunc (function) – Marginal value (of market resources) function for this period, defined over market resources and permanent income.
setAndUpdateValues(solution_next, IncomeDstn, LivPrb, DiscFac)

Unpacks some of the inputs (and calculates simple objects based on them), storing the results in self for use by other methods. These include: income shocks and probabilities, medical shocks and probabilities, next period’s marginal value function (etc), the probability of getting the worst income shock next period, the patience factor, human wealth, and the bounding MPCs.

Parameters:
  • solution_next (ConsumerSolution) – The solution to next period’s one period problem.
  • IncomeDstn ([np.array]) – A list containing three arrays of floats, representing a discrete approximation to the income process between the period being solved and the one immediately following (in solution_next). Order: event probabilities, permanent shocks, transitory shocks.
  • LivPrb (float) – Survival probability; likelihood of being alive at the beginning of the succeeding period.
  • DiscFac (float) – Intertemporal discount factor for future utility.
Returns:

Return type:

None

solve()

Solves a one period consumption saving problem with risky income and shocks to medical need.

Parameters:None
Returns:solution – The solution to the one period problem, including a consumption function, medical spending function ( both defined over market re- sources, permanent income, and medical shock), a marginal value func- tion (defined over market resources and permanent income), and human wealth as a function of permanent income.
Return type:ConsumerSolution
usePointsForInterpolation(xLvl, mLvl, pLvl, MedShk, interpolator)

Constructs a basic solution for this period, including the consumption function and marginal value function.

Parameters:
  • xLvl (np.array) – Total expenditure points for interpolation.
  • mLvl (np.array) – Corresponding market resource points for interpolation.
  • pLvl (np.array) – Corresponding permanent income level points for interpolation.
  • MedShk (np.array) – Corresponding medical need shocks for interpolation.
  • interpolator (function) – A function that constructs and returns a consumption function.
Returns:

solution_now – The solution to this period’s consumption-saving problem, with a consumption function, marginal value function, and minimum m.

Return type:

ConsumerSolution

class HARK.ConsumptionSaving.ConsMedModel.MedShockConsumerType(cycles=0, time_flow=True, **kwds)

A class to represent agents who consume two goods: ordinary composite consumption and medical care; both goods yield CRRAutility, and the coefficients on the goods might be different. Agents expect to receive shocks to permanent and transitory income as well as multiplicative shocks to utility from medical care.

getControls()

Calculates consumption and medical care for each consumer of this type using the consumption and medical care functions.

Parameters:None
Returns:
Return type:None
getPostStates()

Calculates end-of-period assets for each consumer of this type.

Parameters:None
Returns:
Return type:None
getShocks()

Gets permanent and transitory income shocks for this period as well as medical need shocks and the price of medical care.

Parameters:None
Returns:
Return type:None
update()

Update the income process, the assets grid, the permanent income grid, the medical shock distribution, and the terminal solution.

Parameters:none
Returns:
Return type:none
updateMedShockProcess()

Constructs discrete distributions of medical preference shocks for each period in the cycle. Distributions are saved as attribute MedShkDstn, which is added to time_vary.

Parameters:None
Returns:
Return type:None
updateSolutionTerminal()

Update the terminal period solution for this type. Similar to other models, optimal behavior involves spending all available market resources; however, the agent must split his resources between consumption and medical care.

Parameters:
  • None
  • Returns
  • --------
  • None
updatepLvlGrid()

Update the grid of permanent income levels. Currently only works for infinite horizon models (cycles=0) and lifecycle models (cycles=1). Not clear what to do about cycles>1. Identical to version in persistent shocks model, but pLvl=0 is manually added to the grid (because there is no closed form lower-bounding cFunc for pLvl=0).

Parameters:None
Returns:
Return type:None
class HARK.ConsumptionSaving.ConsMedModel.MedShockPolicyFunc(xFunc, xLvlGrid, MedShkGrid, MedPrice, CRRAcon, CRRAmed, xLvlCubicBool=False, MedShkCubicBool=False)

Class for representing the policy function in the medical shocks model: opt- imal consumption and medical care for given market resources, permanent income, and medical need shock. Always obeys Con + MedPrice*Med = optimal spending.

derivativeX(mLvl, pLvl, MedShk)

Evaluate the derivative of consumption and medical care with respect to market resources at given levels of market resources, permanent income, and medical need shocks.

Parameters:
  • mLvl (np.array) – Market resource levels.
  • pLvl (np.array) – Permanent income levels; should be same size as mLvl.
  • MedShk (np.array) – Medical need shocks; should be same size as mLvl.
Returns:

  • dcdm (np.array) – Derivative of consumption with respect to market resources for each point in (xLvl,MedShk).
  • dMeddm (np.array) – Derivative of medical care with respect to market resources for each point in (xLvl,MedShk).

derivativeY(mLvl, pLvl, MedShk)

Evaluate the derivative of consumption and medical care with respect to permanent income at given levels of market resources, permanent income, and medical need shocks.

Parameters:
  • mLvl (np.array) – Market resource levels.
  • pLvl (np.array) – Permanent income levels; should be same size as mLvl.
  • MedShk (np.array) – Medical need shocks; should be same size as mLvl.
Returns:

  • dcdp (np.array) – Derivative of consumption with respect to permanent income for each point in (xLvl,MedShk).
  • dMeddp (np.array) – Derivative of medical care with respect to permanent income for each point in (xLvl,MedShk).

derivativeZ(mLvl, pLvl, MedShk)

Evaluate the derivative of consumption and medical care with respect to medical need shock at given levels of market resources, permanent income, and medical need shocks.

Parameters:
  • mLvl (np.array) – Market resource levels.
  • pLvl (np.array) – Permanent income levels; should be same size as mLvl.
  • MedShk (np.array) – Medical need shocks; should be same size as mLvl.
Returns:

  • dcdShk (np.array) – Derivative of consumption with respect to medical need for each point in (xLvl,MedShk).
  • dMeddShk (np.array) – Derivative of medical care with respect to medical need for each point in (xLvl,MedShk).

class HARK.ConsumptionSaving.ConsMedModel.MedThruXfunc(xFunc, cFunc, MedPrice)

Class for representing medical care function derived from total expenditure and consumption.

derivativeX(mLvl, pLvl, MedShk)

Evaluate the derivative of consumption and medical care with respect to market resources at given levels of market resources, permanent income, and medical need shocks.

Parameters:
  • mLvl (np.array) – Market resource levels.
  • pLvl (np.array) – Permanent income levels; should be same size as mLvl.
  • MedShk (np.array) – Medical need shocks; should be same size as mLvl.
Returns:

  • dcdm (np.array) – Derivative of consumption with respect to market resources for each point in (xLvl,MedShk).
  • dMeddm (np.array) – Derivative of medical care with respect to market resources for each point in (xLvl,MedShk).

derivativeY(mLvl, pLvl, MedShk)

Evaluate the derivative of medical care with respect to permanent income at given levels of market resources, permanent income, and medical need shocks.

Parameters:
  • mLvl (np.array) – Market resource levels.
  • pLvl (np.array) – Permanent income levels; should be same size as mLvl.
  • MedShk (np.array) – Medical need shocks; should be same size as mLvl.
Returns:

dMeddp – Derivative of medical care with respect to permanent income for each point in (xLvl,MedShk).

Return type:

np.array

derivativeZ(mLvl, pLvl, MedShk)

Evaluate the derivative of medical care with respect to medical need shock at given levels of market resources, permanent income, and medical need shocks.

Parameters:
  • mLvl (np.array) – Market resource levels.
  • pLvl (np.array) – Permanent income levels; should be same size as mLvl.
  • MedShk (np.array) – Medical need shocks; should be same size as mLvl.
Returns:

dMeddShk – Derivative of medical care with respect to medical need for each point in (xLvl,MedShk).

Return type:

np.array

class HARK.ConsumptionSaving.ConsMedModel.cThruXfunc(xFunc, cFunc)

Class for representing consumption function derived from total expenditure and consumption.

derivativeX(mLvl, pLvl, MedShk)

Evaluate the derivative of consumption with respect to market resources at given levels of market resources, permanent income, and medical need shocks.

Parameters:
  • mLvl (np.array) – Market resource levels.
  • pLvl (np.array) – Permanent income levels; should be same size as mLvl.
  • MedShk (np.array) – Medical need shocks; should be same size as mLvl.
Returns:

dcdm – Derivative of consumption with respect to market resources for each point in (xLvl,MedShk).

Return type:

np.array

derivativeY(mLvl, pLvl, MedShk)

Evaluate the derivative of consumption and medical care with respect to permanent income at given levels of market resources, permanent income, and medical need shocks.

Parameters:
  • mLvl (np.array) – Market resource levels.
  • pLvl (np.array) – Permanent income levels; should be same size as mLvl.
  • MedShk (np.array) – Medical need shocks; should be same size as mLvl.
Returns:

dcdp – Derivative of consumption with respect to permanent income for each point in (xLvl,MedShk).

Return type:

np.array

derivativeZ(mLvl, pLvl, MedShk)

Evaluate the derivative of consumption and medical care with respect to medical need shock at given levels of market resources, permanent income, and medical need shocks.

Parameters:
  • mLvl (np.array) – Market resource levels.
  • pLvl (np.array) – Permanent income levels; should be same size as mLvl.
  • MedShk (np.array) – Medical need shocks; should be same size as mLvl.
Returns:

dcdShk – Derivative of consumption with respect to medical need for each point in (xLvl,MedShk).

Return type:

np.array

HARK.ConsumptionSaving.ConsMedModel.solveConsMedShock(solution_next, IncomeDstn, MedShkDstn, LivPrb, DiscFac, CRRA, CRRAmed, Rfree, MedPrice, pLvlNextFunc, BoroCnstArt, aXtraGrid, pLvlGrid, vFuncBool, CubicBool)

Solve the one period problem for a consumer with shocks to permanent and transitory income as well as medical need shocks (as multiplicative shifters for utility from a second medical care good).

Parameters:
  • solution_next (ConsumerSolution) – The solution to next period’s one period problem.
  • IncomeDstn ([np.array]) – A list containing three arrays of floats, representing a discrete approximation to the income process between the period being solved and the one immediately following (in solution_next). Order: event probabilities, permanent shocks, transitory shocks.
  • MedShkDstn ([np.array]) – Discrete distribution of the multiplicative utility shifter for med- ical care. Order: probabilities, preference shocks.
  • LivPrb (float) – Survival probability; likelihood of being alive at the beginning of the succeeding period.
  • DiscFac (float) – Intertemporal discount factor for future utility.
  • CRRA (float) – Coefficient of relative risk aversion for composite consumption.
  • CRRAmed (float) – Coefficient of relative risk aversion for medical care.
  • Rfree (float) – Risk free interest factor on end-of-period assets.
  • MedPrice (float) – Price of unit of medical care relative to unit of consumption.
  • pLvlNextFunc (float) – Expected permanent income next period as a function of current pLvl.
  • PrstIncCorr (float) – Correlation of permanent income from period to period.
  • BoroCnstArt (float or None) – Borrowing constraint for the minimum allowable assets to end the period with.
  • aXtraGrid (np.array) – Array of “extra” end-of-period (normalized) asset values– assets above the absolute minimum acceptable level.
  • pLvlGrid (np.array) – Array of permanent income levels at which to solve the problem.
  • vFuncBool (boolean) – An indicator for whether the value function should be computed and included in the reported solution.
  • CubicBool (boolean) – An indicator for whether the solver should use cubic or linear inter- polation.
Returns:

solution – Solution to this period’s problem, including a consumption function, medical spending function, and marginal value function. The former two are defined over (mLvl,pLvl,MedShk), while the latter is defined only on (mLvl,pLvl), with MedShk integrated out.

Return type:

ConsumerSolution

class HARK.ConsumptionSaving.ConsPortfolioModel.ConsIndShockPortfolioSolver(solution_next, IncomeDstn, LivPrb, DiscFac, CRRA, Rfree, PermGroFac, BoroCnstArt, aXtraGrid, vFuncBool, CubicBool, approxRiskyDstn, RiskyCount, RiskyShareCount, RiskyShareLimitFunc, AdjustPrb, PortfolioGrid, AdjustCount, PortfolioDomain)

A class for solving a one period consumption-saving problem with portfolio choice. An instance of this class is created by the function solveConsPortfolio in each period.

addvFunc(solution)

Creates the value function for this period and adds it to the solution.

Parameters:solution (ConsumerSolution) – The solution to this single period problem, likely including the consumption function, marginal value function, etc.
Returns:solution – The single period solution passed as an input, but now with the value function (defined over market resources m) as an attribute.
Return type:ConsumerSolution
calcEndOfPrdvP()

Calculate end-of-period marginal value of assets at each point in aNrmNow. Does so by taking a weighted sum of next period marginal values across income shocks (in a preconstructed grid self.mNrmNext).

Parameters:none
Returns:EndOfPrdvP – A 1D array of end-of-period marginal value of assets
Return type:np.array
defBoroCnst(BoroCnstArt)

Defines the constrained portion of the consumption function as cFuncNowCnst, an attribute of self. Uses the artificial and natural borrowing constraints.

Parameters:BoroCnstArt (float or None) – Borrowing constraint for the minimum allowable assets to end the period with. If it is less than the natural borrowing constraint, then it is irrelevant; BoroCnstArt=None indicates no artificial bor- rowing constraint.
Returns:
Return type:none
makeEndOfPrdvFunc(AdjustIndex, ShareIndex)

Construct the end-of-period value function for this period, storing it as an attribute of self for use by other methods.

Parameters:none
Returns:
Return type:none
makevFunc(solution, AdjustIndex, ShareIndex)

Creates the value function for this period, defined over market resources m. self must have the attribute EndOfPrdvFunc in order to execute.

Parameters:solution (ConsumerSolution) – The solution to this single period problem, which must include the consumption function.
Returns:vFuncNow – A representation of the value function for this period, defined over normalized market resources m: v = vFuncNow(m).
Return type:ValueFunc
prepareToCalcEndOfPrdvP()

Prepare to calculate end-of-period marginal value by creating an array of market resources that the agent could have next period, considering the grid of end-of-period assets and the distribution of shocks he might experience next period. This method adds extra steps because it first solves the portfolio problem given the end-of-period assets to be able to get next period resources.

Parameters:none
Returns:aNrmNow – A 1D array of end-of-period assets; also stored as attribute of self.
Return type:np.array
prepareToCalcRiskyShare()

Prepare variables used to find optimal portfolio shares. Branches to either the discrete or continuous portfolio choice set.

setAndUpdateValues(solution_next, IncomeDstn, LivPrb, DiscFac)

Unpacks some of the inputs (and calculates simple objects based on them), storing the results in self for use by other methods. These include: income shocks and probabilities, next period’s marginal value function (etc), the probability of getting the worst income shock next period, the patience factor, human wealth, and the bounding MPCs.

Parameters:
  • solution_next (ConsumerSolution) – The solution to next period’s one period problem.
  • IncomeDstn ([np.array]) – A list containing three arrays of floats, representing a discrete approximation to the income process between the period being solved and the one immediately following (in solution_next). Order: event probabilities, permanent shocks, transitory shocks.
  • LivPrb (float) – Survival probability; likelihood of being alive at the beginning of the succeeding period.
  • DiscFac (float) – Intertemporal discount factor for future utility.
Returns:

Return type:

None

solve()

Solves a one period consumption saving problem with risky income and a portfolio choice over a riskless and a risky asset.

Parameters:None
Returns:solution – The solution to the one period problem.
Return type:ConsumerSolution
class HARK.ConsumptionSaving.ConsPortfolioModel.LogNormalPortfolioConsumerType(cycles=1, time_flow=True, verbose=False, quiet=False, **kwds)

A consumer type with a portfolio choice. This agent type has log-normal return factors. Their problem is defined by a coefficient of relative risk aversion, intertemporal discount factor, interest factor, and time sequences of the permanent income growth rate, survival probability, and return factor averages and standard deviations.

HARK.ConsumptionSaving.ConsPortfolioModel.LogNormalRiskyDstnDraw(RiskyAvg=1.0, RiskyStd=0.0)

A class for generating functions that draw random values from a log-normal distribution as parameterized by the input RiskyAvg and RiskyStd values. The returned function takes no argument and returns a value.

HARK.ConsumptionSaving.ConsPortfolioModel.RiskyDstnFactory(RiskyAvg=1.0, RiskyStd=0.0)

A class for generating functions that generate nodes and weights for a log- normal distribution as parameterized by the input RiskyAvg and RiskyStd values. The returned function takes a number of points to request and returns a list of lists where the first list contains the weights (probabilities) and the second list contains the values.

Extensions to ConsIndShockModel concerning models with preference shocks. It currently only two models:

  1. An extension of ConsIndShock, but with an iid lognormal multiplicative shock each period.
  2. A combination of (1) and ConsKinkedR, demonstrating how to construct a new model by inheriting from multiple classes.
class HARK.ConsumptionSaving.ConsPrefShockModel.ConsKinkyPrefSolver(solution_next, IncomeDstn, PrefShkDstn, LivPrb, DiscFac, CRRA, Rboro, Rsave, PermGroFac, BoroCnstArt, aXtraGrid, vFuncBool, CubicBool)

A class for solving the one period consumption-saving problem with risky income (permanent and transitory shocks), multiplicative shocks to utility each period, and a different interest rate on saving vs borrowing.

class HARK.ConsumptionSaving.ConsPrefShockModel.ConsPrefShockSolver(solution_next, IncomeDstn, PrefShkDstn, LivPrb, DiscFac, CRRA, Rfree, PermGroFac, BoroCnstArt, aXtraGrid, vFuncBool, CubicBool)

A class for solving the one period consumption-saving problem with risky income (permanent and transitory shocks) and multiplicative shocks to utility each period.

getPointsForInterpolation(EndOfPrdvP, aNrmNow)

Find endogenous interpolation points for each asset point and each discrete preference shock.

Parameters:
  • EndOfPrdvP (np.array) – Array of end-of-period marginal values.
  • aNrmNow (np.array) – Array of end-of-period asset values that yield the marginal values in EndOfPrdvP.
Returns:

  • c_for_interpolation (np.array) – Consumption points for interpolation.
  • m_for_interpolation (np.array) – Corresponding market resource points for interpolation.

makevFunc(solution)

Make the beginning-of-period value function (unconditional on the shock).

Parameters:solution (ConsumerSolution) – The solution to this single period problem, which must include the consumption function.
Returns:vFuncNow – A representation of the value function for this period, defined over normalized market resources m: v = vFuncNow(m).
Return type:ValueFunc
usePointsForInterpolation(cNrm, mNrm, interpolator)

Make a basic solution object with a consumption function and marginal value function (unconditional on the preference shock).

Parameters:
  • cNrm (np.array) – Consumption points for interpolation.
  • mNrm (np.array) – Corresponding market resource points for interpolation.
  • interpolator (function) – A function that constructs and returns a consumption function.
Returns:

solution_now – The solution to this period’s consumption-saving problem, with a consumption function, marginal value function, and minimum m.

Return type:

ConsumerSolution

class HARK.ConsumptionSaving.ConsPrefShockModel.KinkyPrefConsumerType(cycles=1, time_flow=True, **kwds)

A class for representing consumers who experience multiplicative shocks to utility each period, specified as iid lognormal and different interest rates on borrowing vs saving.

class HARK.ConsumptionSaving.ConsPrefShockModel.PrefShockConsumerType(cycles=1, time_flow=True, **kwds)

A class for representing consumers who experience multiplicative shocks to utility each period, specified as iid lognormal.

calcBoundingValues()

Calculate human wealth plus minimum and maximum MPC in an infinite horizon model with only one period repeated indefinitely. Store results as attributes of self. Human wealth is the present discounted value of expected future income after receiving income this period, ignoring mort- ality. The maximum MPC is the limit of the MPC as m –> mNrmMin. The minimum MPC is the limit of the MPC as m –> infty.

NOT YET IMPLEMENTED FOR THIS CLASS

Parameters:None
Returns:
Return type:None
getControls()

Calculates consumption for each consumer of this type using the consumption functions.

Parameters:None
Returns:
Return type:None
getShocks()

Gets permanent and transitory income shocks for this period as well as preference shocks.

Parameters:None
Returns:
Return type:None
makeEulerErrorFunc(mMax=100, approx_inc_dstn=True)

Creates a “normalized Euler error” function for this instance, mapping from market resources to “consumption error per dollar of consumption.” Stores result in attribute eulerErrorFunc as an interpolated function. Has option to use approximate income distribution stored in self.IncomeDstn or to use a (temporary) very dense approximation.

NOT YET IMPLEMENTED FOR THIS CLASS

Parameters:
  • mMax (float) – Maximum normalized market resources for the Euler error function.
  • approx_inc_dstn (Boolean) – Indicator for whether to use the approximate discrete income distri- bution stored in self.IncomeDstn[0], or to use a very accurate discrete approximation instead. When True, uses approximation in IncomeDstn; when False, makes and uses a very dense approximation.
Returns:

Return type:

None

update()

Updates the assets grid, income process, terminal period solution, and preference shock process. A very slight extension of IndShockConsumerType.update() for the preference shock model.

Parameters:None
Returns:
Return type:None
updatePrefShockProcess()

Make a discrete preference shock structure for each period in the cycle for this agent type, storing them as attributes of self for use in the solution (and other methods).

Parameters:none
Returns:
Return type:none
HARK.ConsumptionSaving.ConsPrefShockModel.solveConsKinkyPref(solution_next, IncomeDstn, PrefShkDstn, LivPrb, DiscFac, CRRA, Rboro, Rsave, PermGroFac, BoroCnstArt, aXtraGrid, vFuncBool, CubicBool)

Solves a single period of a consumption-saving model with preference shocks to marginal utility and a different interest rate on saving vs borrowing. Problem is solved using the method of endogenous gridpoints.

Parameters:
  • solution_next (ConsumerSolution) – The solution to the succeeding one period problem.
  • IncomeDstn ([np.array]) – A list containing three arrays of floats, representing a discrete approximation to the income process between the period being solved and the one immediately following (in solution_next). Order: event probabilities, permanent shocks, transitory shocks.
  • PrefShkDstn ([np.array]) – Discrete distribution of the multiplicative utility shifter. Order: probabilities, preference shocks.
  • LivPrb (float) – Survival probability; likelihood of being alive at the beginning of the succeeding period.
  • DiscFac (float) – Intertemporal discount factor for future utility.
  • CRRA (float) – Coefficient of relative risk aversion.
  • Rboro (float) – Interest factor on assets between this period and the succeeding period when assets are negative.
  • Rsave (float) – Interest factor on assets between this period and the succeeding period when assets are positive.
  • PermGroGac (float) – Expected permanent income growth factor at the end of this period.
  • BoroCnstArt (float or None) – Borrowing constraint for the minimum allowable assets to end the period with. If it is less than the natural borrowing constraint, then it is irrelevant; BoroCnstArt=None indicates no artificial bor- rowing constraint.
  • aXtraGrid (np.array) – Array of “extra” end-of-period asset values– assets above the absolute minimum acceptable level.
  • vFuncBool (boolean) – An indicator for whether the value function should be computed and included in the reported solution.
  • CubicBool (boolean) – An indicator for whether the solver should use cubic or linear inter- polation.
Returns:

solution – The solution to the single period consumption-saving problem. Includes a consumption function cFunc (using linear splines), a marginal value function vPfunc, a minimum acceptable level of normalized market re- sources mNrmMin, normalized human wealth hNrm, and bounding MPCs MPCmin and MPCmax. It might also have a value function vFunc. The consumption function is defined over normalized market resources and the preference shock, c = cFunc(m,PrefShk), but the (marginal) value function is defined unconditionally on the shock, just before it is revealed.

Return type:

ConsumerSolution

HARK.ConsumptionSaving.ConsPrefShockModel.solveConsPrefShock(solution_next, IncomeDstn, PrefShkDstn, LivPrb, DiscFac, CRRA, Rfree, PermGroFac, BoroCnstArt, aXtraGrid, vFuncBool, CubicBool)

Solves a single period of a consumption-saving model with preference shocks to marginal utility. Problem is solved using the method of endogenous gridpoints.

Parameters:
  • solution_next (ConsumerSolution) – The solution to the succeeding one period problem.
  • IncomeDstn ([np.array]) – A list containing three arrays of floats, representing a discrete approximation to the income process between the period being solved and the one immediately following (in solution_next). Order: event probabilities, permanent shocks, transitory shocks.
  • PrefShkDstn ([np.array]) – Discrete distribution of the multiplicative utility shifter. Order: probabilities, preference shocks.
  • LivPrb (float) – Survival probability; likelihood of being alive at the beginning of the succeeding period.
  • DiscFac (float) – Intertemporal discount factor for future utility.
  • CRRA (float) – Coefficient of relative risk aversion.
  • Rfree (float) – Risk free interest factor on end-of-period assets.
  • PermGroGac (float) – Expected permanent income growth factor at the end of this period.
  • BoroCnstArt (float or None) – Borrowing constraint for the minimum allowable assets to end the period with. If it is less than the natural borrowing constraint, then it is irrelevant; BoroCnstArt=None indicates no artificial bor- rowing constraint.
  • aXtraGrid (np.array) – Array of “extra” end-of-period asset values– assets above the absolute minimum acceptable level.
  • vFuncBool (boolean) – An indicator for whether the value function should be computed and included in the reported solution.
  • CubicBool (boolean) – An indicator for whether the solver should use cubic or linear inter- polation.
Returns:

solution – The solution to the single period consumption-saving problem. Includes a consumption function cFunc (using linear splines), a marginal value function vPfunc, a minimum acceptable level of normalized market re- sources mNrmMin, normalized human wealth hNrm, and bounding MPCs MPCmin and MPCmax. It might also have a value function vFunc. The consumption function is defined over normalized market resources and the preference shock, c = cFunc(m,PrefShk), but the (marginal) value function is defined unconditionally on the shock, just before it is revealed.

Return type:

ConsumerSolution

This module contains models for solving representative agent macroeconomic models. This stands in contrast to all other model modules in HARK, which (unsurprisingly) take a heterogeneous agents approach. In RA models, all attributes are either time invariant or exist on a short cycle; models must be infinite horizon.

class HARK.ConsumptionSaving.ConsRepAgentModel.RepAgentConsumerType(time_flow=True, **kwds)

A class for representing representative agents with inelastic labor supply.

getStates()

Calculates updated values of normalized market resources and permanent income level. Uses pLvlNow, aNrmNow, PermShkNow, TranShkNow.

Parameters:None
Returns:
Return type:None
class HARK.ConsumptionSaving.ConsRepAgentModel.RepAgentMarkovConsumerType(time_flow=True, **kwds)

A class for representing representative agents with inelastic labor supply and a discrete MarkovState

getControls()

Calculates consumption for the representative agent using the consumption functions.

Parameters:None
Returns:
Return type:None
getShocks()

Draws a new Markov state and income shocks for the representative agent.

Parameters:None
Returns:
Return type:None
updateSolutionTerminal()

Update the terminal period solution. This method should be run when a new AgentType is created or when CRRA changes.

Parameters:None
Returns:
Return type:None
HARK.ConsumptionSaving.ConsRepAgentModel.solveConsRepAgent(solution_next, DiscFac, CRRA, IncomeDstn, CapShare, DeprFac, PermGroFac, aXtraGrid)

Solve one period of the simple representative agent consumption-saving model.

Parameters:
  • solution_next (ConsumerSolution) – Solution to the next period’s problem (i.e. previous iteration).
  • DiscFac (float) – Intertemporal discount factor for future utility.
  • CRRA (float) – Coefficient of relative risk aversion.
  • IncomeDstn ([np.array]) – A list containing three arrays of floats, representing a discrete approximation to the income process between the period being solved and the one immediately following (in solution_next). Order: event probabilities, permanent shocks, transitory shocks.
  • CapShare (float) – Capital’s share of income in Cobb-Douglas production function.
  • DeprFac (float) – Depreciation rate of capital.
  • PermGroFac (float) – Expected permanent income growth factor at the end of this period.
  • aXtraGrid (np.array) – Array of “extra” end-of-period asset values– assets above the absolute minimum acceptable level. In this model, the minimum acceptable level is always zero.
Returns:

solution_now – Solution to this period’s problem (new iteration).

Return type:

ConsumerSolution

HARK.ConsumptionSaving.ConsRepAgentModel.solveConsRepAgentMarkov(solution_next, MrkvArray, DiscFac, CRRA, IncomeDstn, CapShare, DeprFac, PermGroFac, aXtraGrid)

Solve one period of the simple representative agent consumption-saving model. This version supports a discrete Markov process.

Parameters:
  • solution_next (ConsumerSolution) – Solution to the next period’s problem (i.e. previous iteration).
  • MrkvArray (np.array) – Markov transition array between this period and next period.
  • DiscFac (float) – Intertemporal discount factor for future utility.
  • CRRA (float) – Coefficient of relative risk aversion.
  • IncomeDstn ([[np.array]]) – A list of lists containing three arrays of floats, representing a discrete approximation to the income process between the period being solved and the one immediately following (in solution_next). Order: event probabilities, permanent shocks, transitory shocks.
  • CapShare (float) – Capital’s share of income in Cobb-Douglas production function.
  • DeprFac (float) – Depreciation rate of capital.
  • PermGroFac ([float]) – Expected permanent income growth factor for each state we could be in next period.
  • aXtraGrid (np.array) – Array of “extra” end-of-period asset values– assets above the absolute minimum acceptable level. In this model, the minimum acceptable level is always zero.
Returns:

solution_now – Solution to this period’s problem (new iteration).

Return type:

ConsumerSolution

Defines and solves the Tractable Buffer Stock model described in lecture notes for “A Tractable Model of Buffer Stock Saving” (henceforth, TBS) available at http://econ.jhu.edu/people/ccarroll/public/lecturenotes/consumption/TractableBufferStock The model concerns an agent with constant relative risk aversion utility making decisions over consumption and saving. He is subject to only a very particular sort of risk: the possibility that he will become permanently unemployed until the day he dies; barring this, his income is certain and grows at a constant rate.

The model has an infinite horizon, but is not solved by backward iteration in a traditional sense. Because of the very specific assumptions about risk, it is possible to find the agent’s steady state or target level of market resources when employed, as well as information about the optimal consumption rule at this target level. The full consumption function can then be constructed by “back- shooting”, inverting the Euler equation to find what consumption must have been in the previous period. The consumption function is thus constructed by repeat- edly adding “stable arm” points to either end of a growing list until specified bounds are exceeded.

Despite the non-standard solution method, the iterative process can be embedded in the HARK framework, as shown below.

class HARK.ConsumptionSaving.TractableBufferStockModel.TractableConsumerSolution(mNrm_list=[], cNrm_list=[], MPC_list=[], cFunc_U=<class 'HARK.utilities.NullFunc'>, cFunc=<class 'HARK.utilities.NullFunc'>)

A class representing the solution to a tractable buffer saving problem. Attributes include a list of money points mNrm_list, a list of consumption points cNrm_list, a list of MPCs MPC_list, a perfect foresight consumption function while employed, and a perfect foresight consumption function while unemployed. The solution includes a consumption function constructed from the lists.

HARK.ConsumptionSaving.TractableBufferStockModel.addToStableArmPoints(solution_next, DiscFac, Rfree, CRRA, PermGroFacCmp, UnempPrb, PFMPC, Rnrm, Beth, mLowerBnd, mUpperBnd)

Adds a one point to the bottom and top of the list of stable arm points if the bounding levels of mLowerBnd (lower) and mUpperBnd (upper) have not yet been met by a stable arm point in mNrm_list. This acts as the “one period solver” / solveOnePeriod in the tractable buffer stock model.

Parameters:
  • solution_next (TractableConsumerSolution) – The solution object from the previous iteration of the backshooting procedure. Not the “next period” solution per se.
  • DiscFac (float) – Intertemporal discount factor on future utility.
  • Rfree (float) – Risk free interest factor on end-of-period assets.
  • CRRA (float) – Coefficient of relative risk aversion.
  • PermGroFacCmp (float) – Permanent income growth factor, compensated for the possibility of permanent unemployment.
  • UnempPrb (float) – Probability of becoming permanently unemployed.
  • PFMPC (float) – The perfect foresight MPC; also the MPC when permanently unemployed.
  • Rnrm (float) – Interest factor normalized by compensated permanent income growth factor.
  • Beth (float) – Damned if I know.
  • mLowerBnd (float) – Lower bound on market resources for the backshooting process. If min(solution_next.mNrm_list) < mLowerBnd, no new bottom point is found.
  • mUpperBnd (float) – Upper bound on market resources for the backshooting process. If max(solution_next.mNrm_list) > mUpperBnd, no new top point is found.
  • Returns
  • ---------
  • solution_now (TractableConsumerSolution) – A new solution object with new points added to the top and bottom. If no new points were added, then the backshooting process is about to end.
HARK.ConsumptionSaving.TractableBufferStockModel.findNextPoint(DiscFac, Rfree, CRRA, PermGroFacCmp, UnempPrb, Rnrm, Beth, cNext, mNext, MPCnext, PFMPC)

Calculates what consumption, market resources, and the marginal propensity to consume must have been in the previous period given model parameters and values of market resources, consumption, and MPC today.

Parameters:
  • DiscFac (float) – Intertemporal discount factor on future utility.
  • Rfree (float) – Risk free interest factor on end-of-period assets.
  • PermGroFacCmp (float) – Permanent income growth factor, compensated for the possibility of permanent unemployment.
  • UnempPrb (float) – Probability of becoming permanently unemployed.
  • Rnrm (float) – Interest factor normalized by compensated permanent income growth factor.
  • Beth (float) – Composite effective discount factor for reverse shooting solution; defined in appendix “Numerical Solution/The Consumption Function” in TBS lecture notes
  • cNext (float) – Normalized consumption in the succeeding period.
  • mNext (float) – Normalized market resources in the succeeding period.
  • MPCnext (float) – The marginal propensity to consume in the succeeding period.
  • PFMPC (float) – The perfect foresight MPC; also the MPC when permanently unemployed.
Returns:

  • mNow (float) – Normalized market resources this period.
  • cNow (float) – Normalized consumption this period.
  • MPCnow (float) – Marginal propensity to consume this period.