Solving Heterogeneous Agent Models with Aggregate Shocks using Deep Reinforcement Learning and Price-Based Observations
Abstract:
This document details a computational framework for solving heterogeneous agent macroeconomic models, specifically a Krusell-Smith (1998) type economy, using deep reinforcement learning techniques. The approach emphasizes agents learning from locally available information (their own state and aggregate prices) and using recurrent neural networks (LSTMs) to build a representation of relevant history, inspired by methods that aim to “sidestep the Master Equation”. We describe the economic environment, the agent’s learning problem, the neural network architectures for policy and value functions, the training algorithms, and an iterative procedure for approximating a Mean-Field Equilibrium.
1. Introduction
Heterogeneous Agent New Keynesian (HANK) models and related frameworks with aggregate uncertainty traditionally pose significant computational challenges. Standard rational expectations solutions often involve solving a high-dimensional “Master Equation,” where the entire cross-sectional distribution of agents is a state variable. This paper outlines an alternative computational approach where agents are modeled as learning entities that form expectations and make decisions based on a limited set of observed variables, primarily their idiosyncratic state and aggregate prices. This aligns with the idea that agents in the economy do not observe the full distribution of states but rather react to and forecast low-dimensional aggregate price signals. Our implementation uses deep learning tools to approximate optimal policies and value functions.
2. The Economic Model (Krusell-Smith Type)
We consider a discrete-time economy populated by a continuum of ex-ante identical agents (approximated by agents in simulation) facing both idiosyncratic and aggregate shocks.
2.1 Agents, States, and Shocks
- Individual State (): For agent at time , the idiosyncratic state relevant for decision making is , where:
- is the agent’s capital (wealth) at the beginning of period .
- is the agent’s idiosyncratic employment/income shock status (e.g., for employed, for unemployed, or different productivity levels).
- Aggregate State (): There is an aggregate productivity shock (good/bad state), which follows a two-state first-order Markov chain with transition matrix . In the implementation, takes values .
- Idiosyncratic Shock Evolution: The idiosyncratic shock also follows a first-order Markov process. Its transition probability depends on its current state , the current aggregate state , and the previous aggregate state . For example, is given by model parameters (e.g.,
p_bb_eu, etc., inparams.py).
2.2 Production and Prices
A representative firm uses a Cobb-Douglas production function with aggregate capital and aggregate labor :
Aggregate capital is the sum of individual capital holdings: .
Aggregate labor is determined by the aggregate state and an average labor endowment per employed agent, e.g., , where is the employment rate in state .
Factor prices are determined by competitive markets:
- Net interest rate:
- Wage rate:
The vector of prices relevant to the agent is .
2.3 Agent’s Problem and State Evolution
Each agent chooses consumption to maximize expected lifetime utility, subject to a budget constraint. The utility function is logarithmic: . The agent’s problem is:
- Wealth Evolution (Resources before consumption/saving):
where is the labor income tax rate (which may depend on to finance unemployment benefits) and represents unemployment benefits. is the indicator function. - Capital Accumulation:
- No-Borrowing Constraint:
(In implementation, and for small ).
The evolution of the full system state , where is the cross-sectional distribution of , follows a complex law of motion (a Fokker-Planck type equation for ).
3. Learning Framework: Agent’s Observational Learning
Instead of assuming agents know and solve the Master Equation, we model them as learning from a limited set of observations.
3.1 Agent’s Observation Vector
At each time , agent observes:
- Its own idiosyncratic capital:
- Its own idiosyncratic shock:
- Aggregate prices:
The observation vector is . This vector is normalized before being fed to neural networks.
3.2 Policy Network Architecture ()
The agent’s policy determines the share of wealth to consume. Since the price process is not Markovian when is unobserved, we use a Long Short-Term Memory (LSTM) network to allow the policy to depend on the history of observations.
- Input at time : Current normalized observation and the previous hidden state of the policy LSTM.
- LSTM Update:
- Output Layer: The LSTM’s output is fed through a Feedforward Network (FFN) to produce a pre-sigmoid parameter for the consumption share:
- Action (Consumption Share):
where is the sigmoid function and is a scaling parameter (sgm_scale).
The total policy network parameters are .
3.3 Value Network Architectures ()
We implement two types of value networks:
- LSTM Value Network ():
- Input: A sequence of normalized observations and an initial hidden state .
- LSTM Update: Similar to the policy network, it processes the sequence.
- Output Layer: The LSTM’s final hidden state for the sequence, , is fed through an FFN :
- Purpose: To estimate based on the history encoded in .
- FFN Value Network ():
- Input: A “researcher’s state” , normalized. This state is assumed to be Markovian or a good approximation.
- Output Layer: .
- Purpose: Primarily used to provide a terminal value in the policy optimization objective, assuming is a sufficient statistic for future rewards from that point.
4. Computational Implementation
4.1 Data Preprocessing and Normalization
All features input to neural networks ( or ) are normalized by subtracting the mean and dividing by the standard deviation. These statistics are computed once from an initial long simulation using a fixed, simple policy (e.g., constant consumption share). Value targets are also normalized.
4.2 Policy Network Training (KSPolicyTrainer)
The policy network is trained to maximize the expected sum of discounted future utilities.
- Objective Function: For a starting state , and given initial hidden state , the objective is to maximize:
where is the unroll horizon (t_unroll), actions are derived from , and is the terminal value estimated by an FFN value network. - Training Process:
- Sample a batch of initial agent states from a replay buffer (
policy_ds). - For each sample, simulate steps forward:
a. At each step :
i. Given current agent capital (initially ), aggregate capital , aggregate shock , and idiosyncratic shock .
ii. Calculate prices .
iii.Form observation (normalized).
iv. Get consumption share and new LSTM hidden state from .
v. Calculate actual consumption using and current wealth . Ensure .
vi. Calculate next capital . Ensure .
vii.Store .
viii.Draw next shocks . - Calculate the terminal value using the FFN Value Network.
- Compute the loss .
- Update using gradients via Adam optimizer and Backpropagation Through Time (BPTT).
- Sample a batch of initial agent states from a replay buffer (
4.3 Value Network Training (ValueTrainer)
Value networks are trained to approximate the expected discounted utility.
- Objective Function: Minimize Mean Squared Error (MSE):
- : A Monte Carlo estimate of the value function. For a path simulated with policy for steps, .
- Training Process:
- Generate a dataset of pairs by simulating trajectories with a given policy (e.g., the current policy from
KSPolicyTraineror a benchmark policy). - For the LSTM Value Network:
- is a sequence of observations .
- is typically the MC value at time of that sequence (i.e., ).
- For the FFN Value Network:
- is a single state .
- is .
- Update using gradients via Adam optimizer.
- Generate a dataset of pairs by simulating trajectories with a given policy (e.g., the current policy from
4.4 Data Generation (KSInitDataSet)
_calculate_normalization_stats: Runs an initial simulation with a fixed policy (e.g., constant consumption share) for periods. From these paths, it computes and stores the mean and standard deviation for:- Agent observations (key: “obs”).
- Researcher states (key: “ffn_state”).
- Monte Carlo value targets (key: “value”).
get_valuedataset(policy, policy_type, use_lstm): Simulates trajectories of length using the providedpolicy.- If
use_lstm=True, it prepares sequences of normalized and corresponding for the LSTM value net. - If
use_lstm=False, it prepares normalized and corresponding for the FFN value net.
- If
get_policydataset(policy, policy_type, update_init): Provides initial states for policy training.- If
update_init=False, uses a fixed set of states. - If
update_init=True, simulates for steps using the givenpolicyand returns the states at as the new initial states.
- If
5. Iterative Training for Mean-Field Equilibrium
To approximate an MFE, where the policy is optimal given the aggregate dynamics it induces, and those dynamics are consistent with agents playing that policy, we use an iterative loop:
5.1 The MFE Algorithm
For mfe_epoch = 1 to :
- Policy Optimization: Train the
KSPolicyTrainerforpolicy_steps_per_mfesteps. The policy network uses the current set of value networks (specifically, an FFN one frommfe_vtrainersfor ). - Obtain Current Policy: Extract a callable function
current_learned_policy_for_simfrom the updatedmfe_ptrainer. - Value Function Update:
a. Generate a new dataset for value training by callinginit_ds.get_valuedatasetusingcurrent_learned_policy_for_sim. This ensures value targets reflect the current policy.
b. Re-train all value networks inmfe_vtrainers(both primary LSTM/FFN and auxiliary FFN if used) forvalue_epochs_per_mfeon this new data. - Update Policy Starting States (Optional but Recommended): Update
mfe_ptrainer.policy_dsby callinginit_ds.get_policydatasetwithupdate_init=Trueandpolicy=current_learned_policy_for_sim. This ensures the policy trainer samples initial states from a distribution more consistent with its current behavior. - Collect Convergence Metrics.
- Save model checkpoints.
5.2 Convergence Metrics
- Distribution Stability:
- After each MFE epoch, simulate paths for steps using
current_learned_policy_for_sim. - Calculate the mean and variance of the aggregate capital at the end of these long simulations.
- Track the series of and over MFE epochs. Convergence is indicated if these moments stabilize.
- After each MFE epoch, simulate paths for steps using
- Bellman Error for the Primary Value Function:
- Sample a batch of initial states from
mfe_ptrainer.policy_ds. - For each sample, simulate one step forward:
a. Calculate prices based on and .
b. Form observation .
c. Policy (frommfe_ptrainer) gives and .
d. Calculate ; Reward .
e. Calculate next capital .
f. Simulate next shocks .
g. Calculate prices based on and .
h. Form next observation . - Get value estimates:
- If primary value net is LSTM: gives and ; gives .
- If primary value net is FFN: and where .
- Calculate squared Bellman error: .
- Average over the batch and track this average over MFE epochs.
- Sample a batch of initial states from
6. Code Structure Overview
params.py: DefinesKSParamclass holding all economic model parameters.simulation_ks.py: Containssimul_shocks(for ) andsimul_k(for simulating paths of given a policy).models.py: Defines neural network architectures (FeedforwardModel,ValueNetwork(FFN),PolicyNetworkLSTM,ValueNetworkLSTM).data_processing.py: ContainsKSInitDataSetfor managing data generation, normalization, and providingDataLoaderinstances for training. IncludesKSPolicyDatasetfor batching policy training start states.training.py: ContainsValueTrainerandKSPolicyTrainerclasses that manage the training loops, loss calculations, and optimizer steps for the respective networks.jupyter_notebook_script.py(ormain.py): Orchestrates the overall process: configuration, initialization of objects, and the MFE iterative training loop.
7. Conclusion and Future Directions
This framework provides a flexible way to explore solutions to heterogeneous agent models by framing the agent’s problem as one of learning from local information and price signals. The use of LSTMs is crucial for handling the non-Markovian nature of observed prices. The iterative MFE training loop aims to find a consistent equilibrium. Future work could involve more sophisticated exploration strategies, different utility functions, richer idiosyncratic state spaces, or alternative network architectures for belief state approximation.
Aftermath: How to Interpret the Learned Equilibrium
Once you have a converged model from this more sophisticated setup, here’s how you, as an economist, can interpret the results:
1. Policy Function Analysis (ki,yi,hagg→cshare)
The learned policy is a complex function, but you can analyze its properties by feeding it controlled inputs.
- Marginal Propensity to Consume (MPC): How does the consumption share change with an agent’s own capital, ki?
- Method: Fix the aggregate state representation hagg (e.g., to its average or steady-state value). Then, plot the policy network’s output (consumption share) as a function of ki for an employed agent (yi=1) and an unemployed agent (yi=0).
- Expected Result: You should see a highly concave policy function. Agents with low capital (low ki) should have a high consumption share (high MPC). Wealthy agents should have a low consumption share. Unemployed agents should have a higher consumption share than employed agents at the same level of capital. This validates the model’s ability to learn precautionary savings motives.
- Response to Aggregate State: How does the policy change depending on the economy’s state (as summarized by hagg)?
- Method: Simulate two price histories: one representing a persistent “good state” (high wages, high interest rates) and one representing a “bad state” (low wages, low interest rates). This generates two different aggregate hidden states, hgood and hbad. Plot the policy function (consumption share vs. ki) for both of these fixed aggregate states.
- Expected Result: You might find that in bad times (hbad), agents become more cautious and lower their consumption share at all levels of capital (increasing precautionary savings).
2. Dynamic Analysis: Impulse Response Functions (IRFs)
IRFs are a cornerstone of macroeconomic analysis. You can generate them from your learned model.
- Method:
- Start the economy in its stationary (stochastic steady-state) distribution by running a very long simulation with the converged policy.
- From this stationary state, apply a one-time, unexpected aggregate shock (e.g., switch Zt from good to bad for one period, then let it evolve according to its transition matrix).
- Track the average path of key aggregate variables (aggregate capital Kt, output Yt, investment It, aggregate consumption Ct, interest rate rt, wage wt) over time following the shock.
- The percentage deviation of these paths from their pre-shock steady-state values constitutes the IRFs.
- What to Look For: Do your IRFs match empirical evidence or the results from standard HANK models? For example, does aggregate consumption fall persistently after a negative productivity shock? Is the response different from a representative-agent model (e.g., is it amplified by precautionary savings motives)?
3. Interpreting the LSTM’s Hidden State (hagg)
The LSTM’s hidden state is a “black box,” but we can probe it to understand what it has learned.
- Correlating hagg with True States:
- Method: Run a simulation and record the history of prices (r,w) fed to the LSTM, the resulting hidden state htagg at each step, and the true underlying aggregate state (Kt,Zt) from the simulator.
- Run a regression of the true states on the elements of the hidden state vector: Kt=β0+β1ht,1agg+… and Zt=γ0+γ1ht,1agg+…
- Interpretation: If you find high R-squared values, it means the LSTM has successfully learned to encode the true, unobserved aggregate state variables into its hidden state vector. You can identify which dimensions of hagg correspond most closely to Kt vs. Zt.
- Visualizing Hidden State Trajectories:
- Method: Plot the elements of htagg over time alongside the paths of Kt and Zt.
- Interpretation: You might visually see that certain elements of the hidden state track the true aggregate capital stock, while others jump discretely when the aggregate shock Zt switches states. This provides strong evidence that the LSTM is learning the structure of the economy.
4. Welfare and Inequality Analysis
- Method: Use the learned value function V(hcombined) to analyze welfare.
- You can calculate the average welfare across the stationary distribution.
- More interestingly, you can analyze the welfare effects of different policies. For example, introduce a new tax-and-transfer policy, find the new MFE, and compare the average welfare under both regimes.
- You can also examine how welfare changes across the distribution of agents (e.g., are low-wealth agents better or worse off under a new policy?).
- Method for Inequality: From the long-run simulation, you can compute standard measures of inequality, such as the Gini coefficient or wealth shares (e.g., top 1%, 10%) for the stationary capital distribution, and see if they match empirical data.