HARK.core

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]