def initializeSim(self): IndShockConsumerType.initializeSim(self) if self.global_markov: #Need to initialize markov state to be the same for all agents base_draw = drawUniform(1,seed=self.RNG.randint(0,2**31-1)) Cutoffs = np.cumsum(np.array(self.MrkvPrbsInit)) self.MrkvNow = np.ones(self.AgentCount)*np.searchsorted(Cutoffs,base_draw).astype(int) self.MrkvNow = self.MrkvNow.astype(int)
def initializeSim(self): self.shocks["MrkvNow"] = np.zeros(self.AgentCount, dtype=int) IndShockConsumerType.initializeSim(self) if (self.global_markov ): # Need to initialize markov state to be the same for all agents base_draw = Uniform(seed=self.RNG.randint(0, 2**31 - 1)).draw(1) Cutoffs = np.cumsum(np.array(self.MrkvPrbsInit)) self.shocks["MrkvNow"] = np.ones( self.AgentCount) * np.searchsorted(Cutoffs, base_draw).astype(int) self.shocks["MrkvNow"] = self.shocks["MrkvNow"].astype(int)
def initializeSim(self): ''' Initialize the state of simulation attributes. Simply calls the same method for IndShockConsumerType, then sets the type of AdjustNow to bool. Parameters ---------- None Returns ------- None ''' IndShockConsumerType.initializeSim(self) self.AdjustNow = self.AdjustNow.astype(bool)
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 initializeSim(self): """ Initialize the state of simulation attributes. Simply calls the same method for IndShockConsumerType, then sets the type of AdjustNow to bool. Parameters ---------- None Returns ------- None """ # these need to be set because "post states", # but are a control variable and shock, respectively self.controls["ShareNow"] = np.zeros(self.AgentCount) self.shocks['AdjustNow'] = np.zeros(self.AgentCount, dtype=bool) IndShockConsumerType.initializeSim(self)
def test_getShocks(self): agent = IndShockConsumerType( AgentCount = 2, T_sim = 10 ) agent.solve() agent.initializeSim() agent.simBirth(np.array([True,False])) agent.simOnePeriod() agent.simBirth(np.array([False,True])) agent.getShocks() self.assertEqual(agent.PermShkNow[0], 1.0050166461586711) self.assertEqual(agent.PermShkNow[1], 1.0050166461586711) self.assertEqual(agent.TranShkNow[0], 1.1176912196531754)
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 consumers of this type | $\texttt{AgentCount}$ | $10000$ | # | 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()
if IndShockExample.vFuncBool: 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()
estimate_by_wealth = False 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')