def test_NewbornStatesAndShocks(self): # Make agent, shock and initial condition histories agent = IndShockConsumerType(**self.base_params) agent.make_shock_history() # Find indices of agents and time periods that correspond to deaths # this will be non-nan indices of newborn_init_history for states # that are used in initializing the agent. aNrm is one of them. idx = np.logical_not(np.isnan(agent.newborn_init_history["aNrm"])) # Change the values a_init_newborns = 20 agent.newborn_init_history["aNrm"][idx] = a_init_newborns # Also change the shocks of newborns pshk_newborns = 0.5 agent.shock_history["PermShk"][idx] = pshk_newborns agent.shock_history["TranShk"][idx] = 0.0 # Solve and simulate the agent agent.solve() agent.initialize_sim() agent.simulate() # Given our manipulation of initial wealth and permanent shocks, # agents of age == 1 should have starting resources a_init_newborns/pshk_newborns # (no interest, no deterministic growth and no transitory shock) age = agent.history["t_age"] self.assertTrue( np.all(agent.history["bNrm"][age == 1] == a_init_newborns / pshk_newborns))
def test_Harmenberg_mtd(self): example = IndShockConsumerType(**dict_harmenberg, verbose=0) example.cycles = 0 example.track_vars = ['aNrm', 'mNrm', 'cNrm', 'pLvl', 'aLvl'] example.T_sim = 20000 example.solve() example.neutral_measure = True example.update_income_process() example.initialize_sim() example.simulate() Asset_list = [] Consumption_list = [] M_list = [] for i in range(example.T_sim): Assetagg = np.mean(example.history['aNrm'][i]) Asset_list.append(Assetagg) ConsAgg = np.mean(example.history['cNrm'][i]) Consumption_list.append(ConsAgg) Magg = np.mean(example.history['mNrm'][i]) M_list.append(Magg) ######################################################### example2 = IndShockConsumerType(**dict_harmenberg, verbose=0) example2.cycles = 0 example2.track_vars = ['aNrm', 'mNrm', 'cNrm', 'pLvl', 'aLvl'] example2.T_sim = 20000 example2.solve() example2.initialize_sim() example2.simulate() Asset_list2 = [] Consumption_list2 = [] M_list2 = [] for i in range(example2.T_sim): Assetagg = np.mean(example2.history['aLvl'][i]) Asset_list2.append(Assetagg) ConsAgg = np.mean(example2.history['cNrm'][i] * example2.history['pLvl'][i]) Consumption_list2.append(ConsAgg) Magg = np.mean(example2.history['mNrm'][i] * example2.history['pLvl'][i]) M_list2.append(Magg) c_std2 = np.std(Consumption_list2) c_std1 = np.std(Consumption_list) c_std_ratio = c_std2 / c_std1 self.assertAlmostEqual(c_std2, 0.03768819564871894) self.assertAlmostEqual(c_std1, 0.004411745897568616) self.assertAlmostEqual(c_std_ratio, 8.542694099741672)
def test_cyclical(self): CyclicalExample = IndShockConsumerType(**CyclicalDict) CyclicalExample.cycles = 0 # Make this consumer type have an infinite horizon CyclicalExample.solve() self.assertAlmostEqual(CyclicalExample.solution[3].cFunc(3).tolist(), 1.5958390056965004) CyclicalExample.initialize_sim() CyclicalExample.simulate() self.assertAlmostEqual(CyclicalExample.state_now['aLvl'][1], 0.41839957)
def test_infinite_horizon(self): IndShockExample = IndShockConsumerType(**IdiosyncDict) IndShockExample.cycles = 0 # Make this type have an infinite horizon IndShockExample.solve() self.assertAlmostEqual(IndShockExample.solution[0].mNrmSS, 1.5488165705077026) self.assertAlmostEqual(IndShockExample.solution[0].cFunc.functions[0].x_list[0], -0.25017509) IndShockExample.track_vars = ['aNrmNow','mNrmNow','cNrmNow','pLvlNow'] IndShockExample.initializeSim() IndShockExample.simulate() self.assertAlmostEqual(IndShockExample.mNrmNow_hist[0][0], 1.0170176090252379)
def test_infinite_horizon(self): IndShockExample = IndShockConsumerType(**IdiosyncDict) IndShockExample.assign_parameters( cycles=0) # Make this type have an infinite horizon IndShockExample.solve() self.assertAlmostEqual(IndShockExample.solution[0].mNrmStE, 1.5488165705077026) self.assertAlmostEqual( IndShockExample.solution[0].cFunc.functions[0].x_list[0], -0.25017509) IndShockExample.track_vars = ['aNrm', "mNrm", "cNrm", 'pLvl'] IndShockExample.initialize_sim() IndShockExample.simulate() self.assertAlmostEqual(IndShockExample.history["mNrm"][0][0], 1.0170176090252379)
class testIndShockConsumerType(unittest.TestCase): def setUp(self): self.agent = IndShockConsumerType(AgentCount=2, T_sim=10) self.agent.solve() def test_getShocks(self): self.agent.initializeSim() self.agent.simBirth(np.array([True, False])) self.agent.simOnePeriod() self.agent.simBirth(np.array([False, True])) self.agent.getShocks() self.assertEqual(self.agent.shocks["PermShkNow"][0], 1.0427376294215103) self.assertEqual(self.agent.shocks["PermShkNow"][1], 0.9278094171517413) self.assertEqual(self.agent.shocks["TranShkNow"][0], 0.881761797501595) def test_ConsIndShockSolverBasic(self): LifecycleExample = IndShockConsumerType(**init_lifecycle) LifecycleExample.cycles = 1 LifecycleExample.solve() # test the solution_terminal self.assertAlmostEqual(LifecycleExample.solution[10].cFunc(2).tolist(), 2) self.assertAlmostEqual(LifecycleExample.solution[9].cFunc(1), 0.97769632) self.assertAlmostEqual(LifecycleExample.solution[8].cFunc(1), 0.96624445) self.assertAlmostEqual(LifecycleExample.solution[7].cFunc(1), 0.95691449) self.assertAlmostEqual(LifecycleExample.solution[0].cFunc(1).tolist(), 0.87362789) self.assertAlmostEqual(LifecycleExample.solution[1].cFunc(1).tolist(), 0.9081621) self.assertAlmostEqual(LifecycleExample.solution[2].cFunc(1).tolist(), 0.9563899) solver = ConsIndShockSolverBasic( LifecycleExample.solution[1], LifecycleExample.IncomeDstn[0], LifecycleExample.LivPrb[0], LifecycleExample.DiscFac, LifecycleExample.CRRA, LifecycleExample.Rfree, LifecycleExample.PermGroFac[0], LifecycleExample.BoroCnstArt, LifecycleExample.aXtraGrid, LifecycleExample.vFuncBool, LifecycleExample.CubicBool, ) solver.prepareToSolve() self.assertAlmostEqual(solver.DiscFacEff, 0.9503999999999999) self.assertAlmostEqual(solver.PermShkMinNext, 0.850430160026919) self.assertAlmostEqual(solver.cFuncNowCnst(4).tolist(), 4.0) self.assertAlmostEqual(solver.prepareToCalcEndOfPrdvP()[0], -0.2491750859108316) self.assertAlmostEqual(solver.prepareToCalcEndOfPrdvP()[-1], 19.74982491408914) EndOfPrdvP = solver.calcEndOfPrdvP() self.assertAlmostEqual(EndOfPrdvP[0], 6622.251864311334) self.assertAlmostEqual(EndOfPrdvP[-1], 0.026301061207747087) solution = solver.makeBasicSolution(EndOfPrdvP, solver.aNrmNow, solver.makeLinearcFunc) solver.addMPCandHumanWealth(solution) self.assertAlmostEqual(solution.cFunc(4).tolist(), 1.7391265696400773) def test_simulated_values(self): self.agent.initializeSim() self.agent.simulate() self.assertAlmostEqual(self.agent.MPCnow[1], 0.5711503906043797) self.assertAlmostEqual(self.agent.aLvlNow[1], 0.18438326264597635)
class testIndShockConsumerType(unittest.TestCase): def setUp(self): self.agent = IndShockConsumerType( AgentCount = 2, T_sim = 10 ) self.agent.solve() def test_getShocks(self): self.agent.initializeSim() self.agent.simBirth(np.array([True,False])) self.agent.simOnePeriod() self.agent.simBirth(np.array([False,True])) self.agent.getShocks() self.assertEqual(self.agent.PermShkNow[0], 1.0050166461586711) self.assertEqual(self.agent.PermShkNow[1], 1.0050166461586711) self.assertEqual(self.agent.TranShkNow[0], 1.1176912196531754) def test_ConsIndShockSolverBasic(self): LifecycleExample = IndShockConsumerType( **Params.init_lifecycle) LifecycleExample.cycles = 1 LifecycleExample.solve() solver = ConsIndShockSolverBasic(LifecycleExample.solution[1], LifecycleExample.IncomeDstn[0], LifecycleExample.LivPrb[0], LifecycleExample.DiscFac, LifecycleExample.CRRA, LifecycleExample.Rfree, LifecycleExample.PermGroFac[0], LifecycleExample.BoroCnstArt, LifecycleExample.aXtraGrid, LifecycleExample.vFuncBool, LifecycleExample.CubicBool) solver.prepareToSolve() self.assertAlmostEqual(solver.DiscFacEff, 0.9503999999999999) self.assertAlmostEqual(solver.PermShkMinNext, 0.850430160026919) self.assertAlmostEqual(solver.cFuncNowCnst(4).tolist(), 4.0) self.assertAlmostEqual(solver.prepareToCalcEndOfPrdvP()[0], -0.2491750859108316) self.assertAlmostEqual(solver.prepareToCalcEndOfPrdvP()[-1], 19.74982491408914) EndOfPrdvP = solver.calcEndOfPrdvP() self.assertAlmostEqual(EndOfPrdvP[0], 6622.251864311334) self.assertAlmostEqual(EndOfPrdvP[-1], 0.026301061207747087) solution = solver.makeBasicSolution(EndOfPrdvP, solver.aNrmNow, solver.makeLinearcFunc) solver.addMPCandHumanWealth(solution) self.assertAlmostEqual(solution.cFunc(4).tolist(), 1.7391265696400773) def test_simulated_values(self): self.agent.initializeSim() self.agent.simulate() print(self.agent.aLvlNow) self.assertAlmostEqual(self.agent.MPCnow[1], 0.5535801655448935) self.assertAlmostEqual(self.agent.aLvlNow[1], 0.18832361)
# | Number of periods to simulate | $\texttt{T_sim}$ | $120$ | # | Mean of initial log (normalized) assets | $\texttt{aNrmInitMean}$ | $-6.0$ | # | Stdev of initial log (normalized) assets | $\texttt{aNrmInitStd}$ | $1.0$ | # | Mean of initial log permanent income | $\texttt{pLvlInitMean}$ | $0.0$ | # | Stdev of initial log permanent income | $\texttt{pLvlInitStd}$ | $0.0$ | # | Aggregrate productivity growth factor | $\texttt{PermGroFacAgg}$ | $1.0$ | # | Age after which consumers are automatically killed | $\texttt{T_age}$ | $None$ | # # Here, we will simulate 10,000 consumers for 120 periods. All newly born agents will start with permanent income of exactly $P_t = 1.0 = \exp(\texttt{pLvlInitMean})$, as $\texttt{pLvlInitStd}$ has been set to zero; they will have essentially zero assets at birth, as $\texttt{aNrmInitMean}$ is $-6.0$; assets will be less than $1\%$ of permanent income at birth. # # These example parameter values were already passed as part of the parameter dictionary that we used to create $\texttt{IndShockExample}$, so it is ready to simulate. We need to set the $\texttt{track_vars}$ attribute to indicate the variables for which we want to record a *history*. # %% IndShockExample.track_vars = ['aNrmNow','mNrmNow','cNrmNow','pLvlNow'] IndShockExample.initializeSim() IndShockExample.simulate() # %% [markdown] # We can now look at the simulated data in aggregate or at the individual consumer level. Like in the perfect foresight model, we can plot average (normalized) market resources over time, as well as average consumption: # %% plt.plot(np.mean(IndShockExample.history['mNrmNow'],axis=1)) plt.xlabel('Time') plt.ylabel('Mean market resources') plt.show() plt.plot(np.mean(IndShockExample.history['cNrmNow'],axis=1)) plt.xlabel('Time') plt.ylabel('Mean consumption') plt.show()
print("Value functions for perfect foresight vs idiosyncratic shocks:") plotFuncs( [PFexample.solution[0].vFunc, IndShockExample.solution[0].vFunc], IndShockExample.solution[0].mNrmMin + 0.5, 10, ) # %% # Simulate some data; results stored in mNrmNow_hist, cNrmNow_hist, and pLvlNow_hist if do_simulation: IndShockExample.T_sim = 120 IndShockExample.track_vars = ["mNrmNow", "cNrmNow", "pLvlNow"] IndShockExample.makeShockHistory( ) # This is optional, simulation will draw shocks on the fly if it isn't run. IndShockExample.initializeSim() IndShockExample.simulate() # %% # Make and solve an idiosyncratic shocks consumer with a finite lifecycle LifecycleExample = IndShockConsumerType(**init_lifecycle) LifecycleExample.cycles = ( 1) # Make this consumer live a sequence of periods exactly once # %% start_time = time() LifecycleExample.solve() end_time = time() print("Solving a lifecycle consumer took " + mystr(end_time - start_time) + " seconds.") LifecycleExample.unpackcFunc() LifecycleExample.timeFwd()
} # %% slideshow={"slide_type": "slide"} from HARK.ConsumptionSaving.ConsIndShockModel import IndShockConsumerType IndShockSimExample = IndShockConsumerType(**IdiosyncDict) IndShockSimExample.cycles = 0 # Make this type have an infinite horizon IndShockSimExample.solve() plot_funcs(IndShockSimExample.solution[0].cFunc, IndShockSimExample.solution[0].mNrmMin, 5) # simulation IndShockSimExample.track_vars = ['aNrm', 'mNrm', 'cNrm', 'pLvl'] IndShockSimExample.initialize_sim() IndShockSimExample.simulate() # %% slideshow={"slide_type": "slide"} # distribution of cash on hand density = np.histogram(IndShockSimExample.history['mNrm'], density=True) #print(density) n, bins, patches = plt.hist(IndShockSimExample.history['mNrm'], density=True) # %% slideshow={"slide_type": "slide"} df1 = pd.DataFrame(IndShockSimExample.history['mNrm'], columns=['beta = 0.9941' ]) #Converting array to pandas DataFrame df1.plot(kind='density', title='distribution of cash on hand') # %% slideshow={"slide_type": "skip"} # circumstances view
# First, we simulate using the traditional approach. # %% tags=[] # Base simulation # Start assets at m balanced growth (levels) point try: # Accommodate syntax for old and new versions of HARK Bilt = popn.solution[0].Bilt popn.aNrmInitMean = np.log(Bilt.mBalLvl - 1) except: popn.aNrmInitMean = np.log(popn.solution[0].mNrmStE - 1) popn.aNrmInitStd = 0. popn.initialize_sim() popn.simulate() # Retrieve history mNrm_popn = popn.history['mNrm'] mLvl_popn = popn.history['mNrm'] * popn.history['pLvl'] cLvl_popn = popn.history['cNrm'] * popn.history['pLvl'] # %% [markdown] # Update and simulate using Harmenberg's strategy. This time, not multiplying by permanent income. # %% tags=[] # Harmenberg permanent income neutral simulation # Start by duplicating the previous setup ntrl = deepcopy(popn)
fast.PermGroFac = [1.02] fast.tolerance = fast.tolerance / 100 fast.track_vars = ['cNrm', 'pLvl'] fast.solve(verbose=False) # %% [markdown] # # Calculate Patience Conditions # %% collapsed=true jupyter={"outputs_hidden": true} fast.check_conditions(verbose=True) # %% jupyter={"source_hidden": true} # Simulate a population fast.initialize_sim() fast.simulate() print('done') # %% jupyter={"source_hidden": true} # Compute paths of cNrm, pLvl, cLvl, and cov(cNrm,pLvl) cLvl_avg_lst = [] # Path of mean consumption level pLvl_avg_lst = [] # Path of mean consumption level cNrm_avg_lst = [] # Path of mean consumption normed cNrm_pLvl_cov_lst = [] for i in range(fast.T_sim): cNrm_avg_now = np.mean(fast.history['cNrm'][i]) # mean cNrm pLvl_avg_now = np.mean(fast.history['pLvl'][i]) # mean pLvl cLvl_avg_now = np.mean(fast.history['cNrm'][i] * fast.history['pLvl'][i]) # mean cLvl
class testIndShockConsumerType(unittest.TestCase): def setUp(self): self.agent = IndShockConsumerType(AgentCount=2, T_sim=10) self.agent.solve() def test_get_shocks(self): self.agent.initialize_sim() self.agent.sim_birth(np.array([True, False])) self.agent.sim_one_period() self.agent.sim_birth(np.array([False, True])) self.agent.get_shocks() self.assertEqual(self.agent.shocks['PermShk'][0], 1.0427376294215103) self.assertAlmostEqual(self.agent.shocks['PermShk'][1], 0.9278094171517413) self.assertAlmostEqual(self.agent.shocks['TranShk'][0], 0.881761797501595) def test_ConsIndShockSolverBasic(self): LifecycleExample = IndShockConsumerType(**init_lifecycle) LifecycleExample.cycles = 1 LifecycleExample.solve() # test the solution_terminal self.assertAlmostEqual(LifecycleExample.solution[-1].cFunc(2).tolist(), 2) self.assertAlmostEqual(LifecycleExample.solution[9].cFunc(1), 0.79429538) self.assertAlmostEqual(LifecycleExample.solution[8].cFunc(1), 0.79391692) self.assertAlmostEqual(LifecycleExample.solution[7].cFunc(1), 0.79253095) self.assertAlmostEqual(LifecycleExample.solution[0].cFunc(1).tolist(), 0.7506184692092213) self.assertAlmostEqual(LifecycleExample.solution[1].cFunc(1).tolist(), 0.7586358637239385) self.assertAlmostEqual(LifecycleExample.solution[2].cFunc(1).tolist(), 0.7681247572911291) solver = ConsIndShockSolverBasic( LifecycleExample.solution[1], LifecycleExample.IncShkDstn[0], LifecycleExample.LivPrb[0], LifecycleExample.DiscFac, LifecycleExample.CRRA, LifecycleExample.Rfree, LifecycleExample.PermGroFac[0], LifecycleExample.BoroCnstArt, LifecycleExample.aXtraGrid, LifecycleExample.vFuncBool, LifecycleExample.CubicBool, ) solver.prepare_to_solve() self.assertAlmostEqual(solver.DiscFacEff, 0.9586233599999999) self.assertAlmostEqual(solver.PermShkMinNext, 0.6554858756904397) self.assertAlmostEqual(solver.cFuncNowCnst(4).tolist(), 4.0) self.assertAlmostEqual(solver.prepare_to_calc_EndOfPrdvP()[0], -0.19792871012285213) self.assertAlmostEqual(solver.prepare_to_calc_EndOfPrdvP()[-1], 19.801071289877118) EndOfPrdvP = solver.calc_EndOfPrdvP() self.assertAlmostEqual(EndOfPrdvP[0], 6657.839372100613) self.assertAlmostEqual(EndOfPrdvP[-1], 0.2606075215645896) solution = solver.make_basic_solution(EndOfPrdvP, solver.aNrmNow, solver.make_linear_cFunc) solver.add_MPC_and_human_wealth(solution) self.assertAlmostEqual(solution.cFunc(4).tolist(), 1.0028005137373956) def test_simulated_values(self): self.agent.initialize_sim() self.agent.simulate() self.assertAlmostEqual(self.agent.MPCnow[1], 0.5711503906043797) self.assertAlmostEqual(self.agent.state_now['aLvl'][1], 0.18438326264597635)
estimate_by_MPC = True if make_simple_plots: # Make some agents to play with TestType = IndShockConsumerType(**temp_dict) DiscFac_vec = np.linspace(0.1,0.98,101) MPC_vec = np.zeros_like(DiscFac_vec) Wealth_vec = np.zeros_like(DiscFac_vec) t_start = clock() for j in range(DiscFac_vec.size): TestType(DiscFac = DiscFac_vec[j]) TestType.solve() TestType.initializeSim() TestType.simulate() MPC_vec[j] = np.mean(TestType.MPCnow) Wealth_vec[j] = np.mean(TestType.aNrmNow) print('Finished DiscFac=' + str(DiscFac_vec[j])) t_end = clock() print('Solving and simulating ' + str(DiscFac_vec.size) + ' types took ' + str(t_end-t_start) + ' seconds.') plt.plot(DiscFac_vec,MPC_vec) plt.xlabel('Discount factor') plt.ylabel('Average marginal propensity to consume') plt.show() plt.plot(DiscFac_vec,Wealth_vec) plt.xlabel('Discount factor') plt.ylabel('Average assets to income ratio')
"track_vars": ["pLvl", "t_age", "PermShk", "TranShk"], "AgentCount": 200, "T_sim": 500, }) Agent = IndShockConsumerType(**params) Agent.solve() # %% Create and solve agent [markdown] # We simulate a population of agents # %% Simulation tags=[] # %%capture # Run the simulations Agent.initialize_sim() Agent.simulate() # %% [markdown] # # $\newcommand{\Ex}{\mathbb{E}}$ # $\newcommand{\PermShk}{\psi}$ # $\newcommand{\pLvl}{\mathbf{p}}$ # $\newcommand{\pLvl}{P}$ # $\newcommand{\yLvl}{\mathbf{y}}$ # $\newcommand{\yLvl}{Y}$ # $\newcommand{\PermGroFac}{\Gamma}$ # $\newcommand{\UnempPrb}{\wp}$ # $\newcommand{\TranShk}{\theta}$ # # We assume a standard income process with transitory and permanent shocks: The consumer's Permanent noncapital income $\pLvl$ grows by a predictable factor $\PermGroFac$ and is subject to an unpredictable multiplicative shock $\Ex_{t}[\PermShk_{t+1}]=1$, #