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.

HARK.core.disable_logging()#
HARK.core.enable_logging()#
HARK.core.warnings()#
HARK.core.quiet()#
HARK.core.verbose()#
HARK.core.set_verbosity_level(level)#
class HARK.core.Parameters(**parameters: Any)#

Bases: object

A smart container for model parameters that handles age-varying dynamics.

This class stores parameters as an internal dictionary and manages their age-varying properties, providing both attribute-style and dictionary-style access. It is designed to handle the time-varying dynamics of parameters in economic models.

Attributes:
  • _length (int) – The terminal age of the agents in the model.

  • _invariant_params (Set[str]) – A set of parameter names that are invariant over time.

  • _varying_params (Set[str]) – A set of parameter names that vary over time.

  • _parameters (Dict[str, Any]) – The internal dictionary storing all parameters.

keys() Iterator[str]#

Return a view of parameter names.

values() Iterator[Any]#

Return a view of parameter values.

items() Iterator[Tuple[str, Any]]#

Return a view of parameter (name, value) pairs.

to_dict() Dict[str, Any]#

Convert parameters to a plain dictionary.

Returns:

A dictionary containing all parameters.

Return type:

Dict[str, Any]

to_namedtuple() namedtuple#

Convert parameters to a namedtuple.

Returns:

A namedtuple containing all parameters.

Return type:

namedtuple

update(other: Parameters | Dict[str, Any]) None#

Update parameters from another Parameters object or dictionary.

Parameters:

other (Union[Parameters, Dict[str, Any]]) – The source of parameters to update from.

Raises:

TypeError – If the input is neither a Parameters object nor a dictionary.

copy() Parameters#

Create a deep copy of the Parameters object.

Returns:

A new Parameters object with the same contents.

Return type:

Parameters

add_to_time_vary(*params: str) None#

Adds any number of parameters to the time-varying set.

Parameters:

*params (str) – Any number of strings naming parameters to be added to time_vary.

add_to_time_inv(*params: str) None#

Adds any number of parameters to the time-invariant set.

Parameters:

*params (str) – Any number of strings naming parameters to be added to time_inv.

del_from_time_vary(*params: str) None#

Removes any number of parameters from the time-varying set.

Parameters:

*params (str) – Any number of strings naming parameters to be removed from time_vary.

del_from_time_inv(*params: str) None#

Removes any number of parameters from the time-invariant set.

Parameters:

*params (str) – Any number of strings naming parameters to be removed from time_inv.

get(key: str, default: Any = None) Any#

Get a parameter value, returning a default if not found.

Parameters:
  • key (str) – The parameter name.

  • default (Any, optional) – The default value to return if the key is not found.

Returns:

The parameter value or the default.

Return type:

Any

set_many(**kwargs: Any) None#

Set multiple parameters at once.

Parameters:

**kwargs (Keyword arguments representing parameter names and values.)

is_time_varying(key: str) bool#

Check if a parameter is time-varying.

Parameters:

key (str) – The parameter name.

Returns:

True if the parameter is time-varying, False otherwise.

Return type:

bool

class HARK.core.Model#

Bases: object

A class with special handling of parameters assignment.

assign_parameters(**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.

Return type:

None

get_parameter(name)#

Returns a parameter of this model

Parameters:

name (str) – The name of the parameter to get

Returns:

value

Return type:

The value of the parameter

describe()#
del_param(param_name)#

Deletes a parameter from this instance, removing it both from the object’s namespace (if it’s there) and the parameters dictionary (likewise).

Parameters:

param_name (str) – A string naming a parameter or data to be deleted from this instance. Removes information from self.parameters dictionary and own namespace.

Return type:

None

construct(*args, force=False)#

Top-level method for building constructed inputs. If called without any inputs, construct builds each of the objects named in the keys of the constructors dictionary; it draws inputs for the constructors from the parameters dictionary and adds its results to the same. If passed one or more strings as arguments, the method builds only the named keys. The method will do multiple “passes” over the requested keys, as some cons- tructors require inputs built by other constructors. If any requested constructors failed to build due to missing data, those keys (and the missing data) will be named in self._missing_key_data. Other errors are recorded in the dictionary attribute _constructor_errors.

Parameters:
  • *args (str, optional) – Keys of self.constructors that are requested to be constructed. If no arguments are passed, all elements of the dictionary are implied.

  • force (bool, optional) – When True, the method will force its way past any errors, including missing constructors, missing arguments for constructors, and errors raised during execution of constructors. Information about all such errors is stored in the dictionary attributes described above. When False (default), any errors or exception will be raised.

Return type:

None

describe_constructors(*args)#

Prints to screen a string describing this instance’s constructed objects, including their names, the function that constructs them, the names of those functions inputs, and whether those inputs are present.

Parameters:

*args (str, optional) – Optional list of strings naming constructed inputs to be described. If none are passed, all constructors are described.

Return type:

None

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

Bases: Model

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.

Parameters:
  • solution_terminal (Solution) – A representation of the solution to the terminal period problem of this AgentType instance, or an initial guess of the solution if this is an infinite horizon problem.

  • cycles (int) – The number of times the sequence of periods is experienced by this AgentType in their “lifetime”. cycles=1 corresponds to a lifecycle model, with a certain sequence of one period problems experienced once before terminating. cycles=0 corresponds to an infinite horizon model, with a sequence of one period problems repeating indefinitely.

  • pseudo_terminal (boolean) – Indicates whether solution_terminal isn’t actually part of the solution to the problem (as a known solution to the terminal period problem), but instead represents a “scrap value”-style termination. When True, solution_terminal is not included in the solution; when false, solution_terminal is the last element of the solution.

  • tolerance (float) – Maximum acceptable “distance” between successive solutions to the one period problem in an infinite horizon (cycles=0) model in order for the solution to be considered as having “converged”. Inoperative when cycles>0.

  • seed (int) – A seed for this instance’s random number generator.

Attributes:
  • AgentCount (int) – The number of agents of this type to use in simulation.

  • state_vars (list of string) – The string labels for this AgentType’s model state variables.

state_vars = []#
add_to_time_vary(*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

Return type:

None

add_to_time_inv(*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

Return type:

None

del_from_time_vary(*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

Return type:

None

del_from_time_inv(*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

Return type:

None

unpack(parameter)#

Unpacks a parameter from a solution object for easier access. After the model has been solved, the parameters (like consumption function) reside in the attributes of each element of ConsumerType.solution (e.g. cFunc). This method creates a (time varying) attribute of the given parameter name that contains a list of functions accessible by ConsumerType.parameter.

Parameters:

parameter (str) – Name of the function to unpack from the solution

Return type:

none

solve(verbose=False, presolve=True)#

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 (bool, optional) – If True, solution progress is printed to screen. Default False.

  • presolve (bool, optional) – If True (default), the pre_solve method is run before solving.

Return type:

none

reset_rng()#

Reset the random number generator for this type.

Parameters:

none

Return type:

none

check_elements_of_time_vary_are_lists()#

A method to check that elements of time_vary are lists.

check_restrictions()#

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

pre_solve()#

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

Parameters:

none

Return type:

none

post_solve()#

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

Parameters:

none

Return type:

none

initialize_sim()#

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

Parameters:

None

Return type:

None

sim_one_period()#

Simulates one period for this type. Calls the methods get_mortality(), get_shocks() or read_shocks, get_states(), get_controls(), and get_poststates(). These should be defined for AgentType subclasses, except get_mortality (define its components sim_death and sim_birth instead) and read_shocks.

Parameters:

None

Return type:

None

make_shock_history()#

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 history dictionary self.history[X]. Automatically sets self.read_shocks to True so that these pre-specified shocks are used for all subsequent calls to simulate().

Parameters:

None

Return type:

None

get_mortality()#

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

Parameters:

None

Return type:

None

sim_death()#

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

sim_birth(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”.

Return type:

None

get_shocks()#

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

Parameters:

None

Return type:

None

read_shocks_from_history()#

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

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

Parameters:

None

Return type:

None

get_states()#

Gets values of state variables for the current period. By default, calls transition function and assigns values to the state_now dictionary.

Parameters:

None

Return type:

None

transition()#
Parameters:
  • None

  • [Eventually

  • spec (to match dolo)

  • exogenous_prev

  • endogenous_prev

  • controls

  • exogenous

  • parameters]

Returns:

endogenous_state – Tuple with new values of the endogenous states

Return type:

()

get_controls()#

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

Return type:

None

get_poststates()#

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.

DEPRECATED: New models should use the state now/previous rollover functionality instead of poststates.

Parameters:

None

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 self.history[varname].

Parameters:

None

Returns:

history – The history tracked during the simulation.

Return type:

dict

clear_history()#

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

Parameters:

None

Return type:

None

HARK.core.solve_agent(agent, verbose)#

Solve the dynamic model for one agent type using backwards induction. 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”.

Return type:

[Solution]

HARK.core.solve_one_cycle(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.

Return type:

[Solution]

HARK.core.make_one_period_oo_solver(solver_class)#

Returns a function that solves a single period consumption-saving problem. :param solver_class: A class of Solver to be used. :type solver_class: Solver :param ——-: :param solver_function: A function for solving one period of a problem. :type solver_function: function

class HARK.core.Market(agents=None, sow_vars=None, reap_vars=None, const_vars=None, track_vars=None, dyn_vars=None, mill_rule=None, calc_dynamics=None, act_T=1000, tolerance=1e-06, **kwds)#

Bases: Model

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.

Parameters:
  • agents ([AgentType]) – A list of all the AgentTypes in this market.

  • sow_vars ([string]) – Names of variables generated by the “aggregate market process” that should “sown” to the agents in the market. Aggregate state, etc.

  • reap_vars ([string]) – Names of variables to be collected (“reaped”) from agents in the market to be used in the “aggregate market process”.

  • const_vars ([string]) – Names of attributes of the Market instance that are used in the “aggregate market process” but do not come from agents– they are constant or simply parameters inherent to the process.

  • track_vars ([string]) – Names of variables generated by the “aggregate market process” that should be tracked as a “history” so that a new dynamic rule can be calculated. This is often a subset of sow_vars.

  • dyn_vars ([string]) – Names of variables that constitute a “dynamic rule”.

  • mill_rule (function) – A function that takes inputs named in reap_vars and returns a tuple the same size and order as sow_vars. The “aggregate market process” that transforms individual agent actions/states/data into aggregate data to be sent back to agents.

  • calc_dynamics (function) – A function that takes inputs named in track_vars and returns an object with attributes named in dyn_vars. Looks at histories of aggregate variables and generates a new “dynamic rule” for agents to believe and act on.

  • act_T (int) – The number of times that the “aggregate market process” should be run in order to generate a history of aggregate variables.

  • tolerance (float) – Minimum acceptable distance between “dynamic rules” to consider the Market solution process converged. Distance is a user-defined metric.

solve_agents()#

Solves the microeconomic problem for all AgentTypes in this market.

Parameters:

None

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

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

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

Return type:

none

mill()#

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

Parameters:

none

Return type:

none

cultivate()#

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

Parameters:

none

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

Return type:

none

store()#

Record the current value of each variable X named in track_vars in an dictionary field named history[X].

Parameters:

none

Return type:

none

make_history()#

Runs a loop of sow–>cultivate–>reap–>mill act_T times, tracking the evolution of variables X named in track_vars in dictionary fields history[X].

Parameters:

none

Return type:

none

update_dynamics()#

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

HARK.core.distribute_params(agent, param_name, param_count, distribution)#

Distributes heterogeneous values of one parameter to the AgentTypes in self.agents. :param agent: An agent to clone. :type agent: AgentType :param param_name: Name of the parameter to be assigned. :type param_name: string :param param_count: Number of different values the parameter will take on. :type param_count: int :param distribution: A 1-D distribution. :type distribution: Distribution

Returns:

agent_set – A list of param_count agents, ex ante heterogeneous with respect to param_name. The AgentCount of the original will be split between the agents of the returned list in proportion to the given distribution.

Return type:

[AgentType]

class HARK.core.AgentPopulation(agent_type: AgentType, parameters: dict, seed: int = 0)#

Bases: object

A class for representing a population of ex-ante heterogeneous agents.

agent_type: AgentType#
parameters: dict#
seed: int = 0#
time_var: List[str]#
time_inv: List[str]#
distributed_params: List[str]#
agent_type_count: int | None#
term_age: int | None#
continuous_distributions: Dict[str, Distribution]#
discrete_distributions: Dict[str, Distribution]#
population_parameters: List[Dict[str, List[float] | float]]#
agents: List[AgentType]#
agent_database: DataFrame#
solution: List[Any]#
approx_distributions(approx_params: dict)#

Approximate continuous distributions with discrete ones. If the initial parameters include a Distribution type, then the AgentPopulation is not ready to solve, and stands for an abstract population. To solve the AgentPopulation, we need discretization parameters for each continuous distribution. This method approximates the continuous distributions with discrete ones, and updates the parameters dictionary.

create_distributed_agents()#

Parses the parameters dictionary and creates a list of agents with the appropriate parameters. Also sets the seed for each agent.

create_database()#

Optionally creates a pandas DataFrame with the parameters for each agent.

solve()#

Solves each agent of the population serially.

unpack_solutions()#

Unpacks the solutions of each agent into an attribute of the population.

initialize_sim()#

Initializes the simulation for each agent.

simulate()#

Simulates each agent of the population serially.