Skip to content

Commit

Permalink
Live editing with CDC and WXD
Browse files Browse the repository at this point in the history
Added a few labels, revised default dictionary. One test might fail, will change target values.
  • Loading branch information
mnwhite committed Jun 13, 2024
1 parent 4d70aea commit 455b2c4
Show file tree
Hide file tree
Showing 4 changed files with 166 additions and 174 deletions.
13 changes: 9 additions & 4 deletions HARK/ConsumptionSaving/ConsNewKeynesianModel.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,24 +59,24 @@
# Default parameters to make aXtraGrid using make_assets_grid
default_aXtraGrid_params = {
"aXtraMin": 0.001, # Minimum end-of-period "assets above minimum" value
"aXtraMax": 20, # Maximum end-of-period "assets above minimum" value
"aXtraMax": 50, # Maximum end-of-period "assets above minimum" value
"aXtraNestFac": 3, # Exponential nesting factor for aXtraGrid
"aXtraCount": 48, # Number of points in the grid of "assets above minimum"
"aXtraCount": 100, # Number of points in the grid of "assets above minimum"
"aXtraExtra": None, # Additional other values to add in grid (optional)
}

# Make a dictionary to specify an idiosyncratic income shocks consumer type
init_newkeynesian = {
# BASIC HARK PARAMETERS REQUIRED TO SOLVE THE MODEL
"cycles": 1, # Finite, non-cyclic model
"cycles": 0, # Infinite horizon model
"T_cycle": 1, # Number of periods in the cycle for this agent type
"constructors": newkeynesian_constructor_dict, # See dictionary above
# PRIMITIVE RAW PARAMETERS REQUIRED TO SOLVE THE MODEL
"CRRA": 2.0, # Coefficient of relative risk aversion
"Rfree": 1.03, # Interest factor on retained assets
"DiscFac": 0.96, # Intertemporal discount factor
"LivPrb": [0.98], # Survival probability after each period
"PermGroFac": [1.01], # Permanent income growth factor
"PermGroFac": [1.0], # Permanent income growth factor
"BoroCnstArt": 0.0, # Artificial borrowing constraint
"vFuncBool": False, # Whether to calculate the value function during solution
"CubicBool": False, # Whether to use cubic spline interpolation when True
Expand All @@ -95,6 +95,11 @@
"PerfMITShk": False, # Do Perfect Foresight MIT Shock
# (Forces Newborns to follow solution path of the agent they replaced if True)
"neutral_measure": False, # Whether to use permanent income neutral measure (see Harmenberg 2021)
# ADDITIONAL PARAMETERS FOR GRID-BASED TRANSITION SIMULATION
"mMin": 0.001,
"mMax": 50,
"mCount": 200,
"mFac": 3,
}
init_newkeynesian.update(default_IncShkDstn_params)
init_newkeynesian.update(default_aXtraGrid_params)
Expand Down
52 changes: 4 additions & 48 deletions HARK/ConsumptionSaving/tests/test_ConsNewKeynesianModel.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,59 +5,15 @@
from HARK.ConsumptionSaving.ConsNewKeynesianModel import NewKeynesianConsumerType
from HARK.tests import HARK_PRECISION

jacobian_test_dict = {
# Parameters shared with the perfect foresight model
"CRRA": 2, # Coefficient of relative risk aversion
"Rfree": 1.04**0.25, # Interest factor on assets
"DiscFac": 0.9735, # Intertemporal discount factor
"LivPrb": [0.99375], # Survival probability
"PermGroFac": [1.00], # Permanent income growth factor
# Parameters that specify the income distribution over the lifecycle
"PermShkStd": [
0.06
], # [(0.01*4/11)**0.5], # Standard deviation of log permanent shocks to income
"PermShkCount": 5, # Number of points in discrete approximation to permanent income shocks
"TranShkStd": [0.3], # Standard deviation of log transitory shocks to income
"TranShkCount": 5, # Number of points in discrete approximation to transitory income shocks
"UnempPrb": 0.07, # Probability of unemployment while working
"IncUnemp": 0.3, # Unemployment benefits replacement rate
"UnempPrbRet": 0.0005, # Probability of "unemployment" while retired
"IncUnempRet": 0.0, # "Unemployment" benefits when retired
"T_retire": 0, # Period of retirement (0 --> no retirement)
# Parameters for constructing the "assets above minimum" grid
"aXtraMin": 0.001, # Minimum end-of-period "assets above minimum" value
"aXtraMax": 20, # Maximum end-of-period "assets above minimum" value
"aXtraCount": 48, # Number of points in the base grid of "assets above minimum"
"aXtraNestFac": 3, # Exponential nesting factor when constructing "assets above minimum" grid
"aXtraExtra": None, # Additional values to add to aXtraGrid
# A few other parameters
"BoroCnstArt": 0.0, # Artificial borrowing constraint; imposed minimum level of end-of period assets
"vFuncBool": True, # Whether to calculate the value function during solution
"CubicBool": False, # Preference shocks currently only compatible with linear cFunc
"T_cycle": 1, # Number of periods in the cycle for this agent type
# Parameters only used in simulation
"AgentCount": 500, # Number of agents of this type
"T_sim": 100, # Number of periods to simulate
"aNrmInitMean": np.log(1.3) - (0.5**2) / 2, # Mean of log initial assets
"aNrmInitStd": 0.5, # Standard deviation of log initial assets
"pLvlInitMean": 0, # Mean of log initial permanent income
"pLvlInitStd": 0, # Standard deviation of log initial permanent income
"PermGroFacAgg": 1.0, # Aggregate permanent income growth factor
"T_age": None, # Age after which simulated agents are automatically killed
# Parameters for Transition Matrix Simulation
"mMin": 0.001,
"mMax": 20,
"mCount": 48,
"mFac": 3,
}


# %% Test Transition Matrix Methods

# Uses class default values


class test_Transition_Matrix_Methods(unittest.TestCase):
def test_calc_tran_matrix(self):
example1 = NewKeynesianConsumerType(**jacobian_test_dict)
example1 = NewKeynesianConsumerType()
example1.cycles = 0
example1.solve()

Expand Down Expand Up @@ -92,7 +48,7 @@ def test_calc_tran_matrix(self):

class test_Jacobian_methods(unittest.TestCase):
def test_calc_jacobian(self):
Agent = NewKeynesianConsumerType(**jacobian_test_dict)
Agent = NewKeynesianConsumerType()
Agent.compute_steady_state()
CJAC_Perm, AJAC_Perm = Agent.calc_jacobian("PermShkStd", 50)

Expand Down
133 changes: 107 additions & 26 deletions examples/SSJ-Example/KS-HARK-presentation.ipynb

Large diffs are not rendered by default.

142 changes: 46 additions & 96 deletions examples/SSJ-Example/SSJ_example.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,13 @@
"\n",
"</br>\n",
"\n",
"- SSJ was created to solve HANK models with incredibly speed and ease\n",
"- SSJ was created to solve HANK models with incredible speed and ease\n",
"\n",
"- Connecting HARK to SSJ allows us to solve macro models with richer micro features.\n"
"- The SSJ method and toolkit (Auclert et al) is utterly fantastic and game-changing\n",
"\n",
"- Big insight: Solving the microeconomic model (in steady state) can be *independent* of working out macroeconomic dynamics\n",
"\n",
"- Connecting HARK to SSJ allows us to solve macro models with richer micro features\n"
]
},
{
Expand Down Expand Up @@ -115,7 +119,7 @@
"source": [
"### Microeconomic Agent Parameters\n",
"\n",
"To make our microeconomic agents in HARK, we need a dictionary of parameters, defined below. All of these parameters have default values if they were not specified, but we list them here for completeness."
"To make our microeconomic agents in HARK, we need a dictionary of parameters, defined below. There are additional parameters that fully specify a NewKeynesianConsumerType, but we can leave them at their default values by not specifying them."
]
},
{
Expand All @@ -128,30 +132,11 @@
"outputs": [],
"source": [
"HANK_dict = {\n",
" \"cycles\": 0, # Infinite horizon problem\n",
" # Parameters shared with the perfect foresight model\n",
" \"Rfree\": 1.0 + r_ss, # Interest factor on assets\n",
" \"LivPrb\": [0.99375], # Survival probability\n",
" # Parameters that specify the income distribution over the lifecycle\n",
" \"PermShkStd\": [0.06], # Standard deviation of log permanent shocks to income\n",
" \"PermShkCount\": 5, # Number of points in discrete approximation to permanent income shocks\n",
" \"TranShkStd\": [0.2], # Standard deviation of log transitory shocks to income\n",
" \"TranShkCount\": 5, # Number of points in discrete approximation to transitory income shocks\n",
" # HANK parameters\n",
" \"tax_rate\": [0.0], # Assume that labor here is actually after tax income\n",
" \"labor\": [Z_ss], # Will be solving the micro model in steady state\n",
" \"wage\": [1.0], #\n",
" \"UnempPrb\": 0.0, # Probability of unemployment while working\n",
" \"IncUnemp\": 0.0, # Unemployment benefits replacement rate\n",
" # Parameters for constructing the \"assets above minimum\" grid\n",
" \"aXtraMax\": 50, # Maximum end-of-period \"assets above minimum\" value\n",
" \"aXtraCount\": 100, # Number of points in the base grid of \"assets above minimum\"\n",
" \"BoroCnstArt\": 0.0,\n",
" # Transition matrix simulation parameters\n",
" \"mCount\": 500,\n",
" \"mMax\": 100,\n",
" \"mMin\": 1e-5,\n",
" \"mFac\": 3,\n",
"}"
]
},
Expand Down Expand Up @@ -226,7 +211,9 @@
"source": [
"## Compute Jacobian Matrices\n",
"\n",
"We can now calculate the Jacobian matrices that characterize consumption and asset responses to an exogenous change in the interest factor (Rfree) or labor supply (labor) that will occur in the future. This is accomplished in HARK with the calc_jacobian method, passing as arguments the name of the parameter that will be changed and the maximum number of periods in the future that a (marginal) change could occur.\n",
"A deep insight that has recently made a large impact for our ability to handle heterogeneous agents models with rich microeconomic heterogeneity is that the macroeconomy can be well approximated by linearization, which makes it possible to calculate the dynamics of the model with response to perfect foresight ``MIT shocks'', as opposed to needing to develop more complicated functions. The key to this is to compute the response of the microeconomic model to small future disturbances-- the Jacobian matrix.\n",
"\n",
"HARK has a tool for calculating the Jacobian matrices that characterize consumption and asset responses to an exogenous *transitory* change in the interest factor (Rfree) or labor income (labor) that will occur in the future. This is accomplished with the calc_jacobian method, passing as arguments the name of the parameter that will be changed and the maximum number of periods in the future that a (marginal) change could occur.\n",
"\n",
"The outputs of this method are objects that represent the sensitivity of aggregate consumption and asset holdings (respectively) in each period to the *advance knowledge* of an exogenous change in each parameter."
]
Expand Down Expand Up @@ -278,9 +265,9 @@
" ]\n",
")\n",
"plt.xlim(-2, 120)\n",
"plt.title(\"Consumption Response to Future Change in Interest Factor\")\n",
"plt.title(\"Consumption Response to Change in Interest Factor\")\n",
"plt.xlabel(\"Time\")\n",
"plt.ylabel(\"What is the scale here?\")\n",
"plt.yticks([])\n",
"plt.show()"
]
},
Expand All @@ -303,9 +290,9 @@
" ]\n",
")\n",
"plt.xlim(-2, 120)\n",
"plt.title(\"Consumption Response to Future Change in Labor Income\")\n",
"plt.title(\"Consumption Response to Change in Labor Income\")\n",
"plt.xlabel(\"Time\")\n",
"plt.ylabel(\"What is the scale here?\")\n",
"plt.yticks([])\n",
"plt.show()"
]
},
Expand Down Expand Up @@ -349,7 +336,7 @@
"outputs": [],
"source": [
"# Store Jacobians in JacobianDict Object\n",
"Jacobian_dict = JacobianDict({\"C\": {\"Z\": CJACZ}, \"A\": {\"Z\": AJACZ}})"
"Jacobian_dict = JacobianDict({\"C\": {\"Z\": dCdZ}, \"A\": {\"Z\": dAdZ}})"
]
},
{
Expand Down Expand Up @@ -386,18 +373,22 @@
"metadata": {},
"outputs": [],
"source": [
"# Create the model by combining three blocks:\n",
"# (1) microeconomic responses to macroeconomic news (Jacobians)\n",
"# (2) fiscal authority behavior\n",
"# (3) market clearing conditions\n",
"ha_lin = sj.create_model([Jacobian_dict, fiscal, mkt_clearing], name=\"HA Model\")\n",
"\n",
"# Choose aggregate shock parameters for the simulation\n",
"T = 300 # <-- the length of the IRF\n",
"rho_G = 0.8 # peristence of shock\n",
"dG = 0.01 * rho_G ** np.arange(T)\n",
"shocks = {\"G\": dG}\n",
"\n",
"# Obtain impulse responses\n",
"unknowns_td = [\"Y\"]\n",
"targets_td = [\"asset_mkt\"]\n",
"\n",
"# Create model\n",
"ha_lin = sj.create_model([Jacobian_dict, fiscal, mkt_clearing], name=\"HA Model\")\n",
"\n",
"# obtain impulse responses\n",
"irfs_G_lin = ha_lin.solve_impulse_linear(\n",
" SteadyState_dict, unknowns_td, targets_td, shocks\n",
")"
Expand All @@ -412,6 +403,7 @@
},
"outputs": [],
"source": [
"# Define a function that can plot impulse response functions\n",
"def show_irfs(\n",
" irfs_list,\n",
" variables,\n",
Expand Down Expand Up @@ -451,15 +443,15 @@
"metadata": {},
"outputs": [],
"source": [
"show_irfs([irfs_G_lin], [\"G\", \"Y\", \"T\"])"
"show_irfs([irfs_G_lin], [\"G\", \"Y\", \"T\"], labels=[\"balanced budget\"])"
]
},
{
"cell_type": "markdown",
"id": "d6b166b2",
"metadata": {},
"source": [
"## Government Spending shock (deficit financed)"
"## Government spending shock (deficit financed)"
]
},
{
Expand All @@ -469,6 +461,7 @@
"metadata": {},
"outputs": [],
"source": [
"# Define a fiscal rule\n",
"rho_B = 0.9\n",
"dB = np.cumsum(dG) * rho_B ** np.arange(T)\n",
"shocks_B = {\"G\": dG, \"B\": dB}\n",
Expand All @@ -482,81 +475,30 @@
"cell_type": "code",
"execution_count": null,
"id": "332b34b6",
"metadata": {
"jupyter": {
"source_hidden": true
}
},
"metadata": {},
"outputs": [],
"source": [
"# Show government spending, output, and taxes\n",
"show_irfs(\n",
" [irfs_G_lin, irfs_B_lin],\n",
" [\"G\", \"Y\", \"T\", \"deficit\", \"goods_mkt\"],\n",
" [\"G\", \"Y\", \"T\"],\n",
" labels=[\"balanced budget\", \"deficit financed\"],\n",
")"
]
},
{
"cell_type": "markdown",
"id": "e5030fdc",
"metadata": {},
"source": [
"## Nonlinear Impulse Responses"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "9f7d1534",
"id": "b0560df9-6428-4a31-921b-8637ef57107e",
"metadata": {},
"outputs": [],
"source": [
"# NOTE: These cells have been commented out because they rely on files that are not present in the HARK repo.\n",
"\n",
"# def hh(Z):\n",
"# C,A = Agent_GE.calc_agg_path(Z,300)\n",
"# return C,A"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "29783be3",
"metadata": {},
"outputs": [],
"source": [
"# from Misc_Utilities.simple_block import exog # import wrapper so SSJ can identify HARK household object\n",
"\n",
"# hh_block = exog(Jacobian_dict,hh,hh)\n",
"# hh_block.name = hh\n",
"\n",
"# ha = sj.create_model([hh_block,fiscal,mkt_clearing], name=\"HA Model\")\n",
"# irfs_G_nonlin = ha.solve_impulse_nonlinear(SteadyState_dict, unknowns_td, targets_td, shocks)\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "a327b50f",
"metadata": {},
"outputs": [],
"source": [
"# plt.plot(irfs_G_nonlin['Y'], label ='nonlinear')\n",
"# plt.plot(irfs_G_lin['Y'], label = 'linear', linestyle='--')\n",
"# plt.xlim(-1,50)\n",
"# plt.legend()\n",
"# plt.title('Nonlinear Impulse responses of output')\n",
"# plt.show()"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "558d31cc",
"metadata": {},
"outputs": [],
"source": [
"# show_irfs([irfs_G_lin,irfs_G_nonlin], ['G', 'Y','T'], ['Linear', 'Nonlinear'])"
"# Show the deficit and consumption\n",
"show_irfs(\n",
" [irfs_G_lin, irfs_B_lin],\n",
" [\"deficit\", \"C\"],\n",
" labels=[\"balanced budget\", \"deficit financed\"],\n",
")"
]
},
{
Expand Down Expand Up @@ -801,6 +743,14 @@
"axes[2].set_xlabel(\"Quarters\")\n",
"fig.tight_layout()"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "c22f17b7-a56c-4219-839a-23ffb1b56bd8",
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
Expand All @@ -819,7 +769,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.9.19"
"version": "3.10.14"
}
},
"nbformat": 4,
Expand Down

0 comments on commit 455b2c4

Please sign in to comment.