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 initialize_sim(self): self.shocks["Mrkv"] = np.zeros(self.AgentCount, dtype=int) IndShockConsumerType.initialize_sim(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["Mrkv"] = np.ones(self.AgentCount) * np.searchsorted( Cutoffs, base_draw).astype(int) self.shocks["Mrkv"] = self.shocks["Mrkv"].astype(int)
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 initialize_sim(self): """ Initialize the state of simulation attributes. Simply calls the same method for IndShockConsumerType, then initializes the new states/shocks Adjust and Share. Parameters ---------- None Returns ------- None """ self.shocks["Adjust"] = np.zeros(self.AgentCount, dtype=bool) IndShockConsumerType.initialize_sim(self)
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].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 )
def initialize_sim(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["Share"] = np.zeros(self.AgentCount) self.shocks['Adjust'] = np.zeros(self.AgentCount, dtype=bool) IndShockConsumerType.initialize_sim(self)
# | 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 `IndShockExample`, so it is ready to simulate. We need to set the `track_vars` attribute to indicate the variables for which we want to record a *history*. # %% IndShockExample.track_vars = ['aNrm', 'mNrm', 'cNrm', 'pLvl'] IndShockExample.initialize_sim() 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['mNrm'], axis=1)) plt.xlabel('Time') plt.ylabel('Mean market resources') plt.show() plt.plot(np.mean(IndShockExample.history['cNrm'], axis=1)) plt.xlabel('Time') plt.ylabel('Mean consumption') plt.show()
"T_age": None, # Age after which simulated agents are automatically killed } # %% 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"}
# # 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.Rfree = 1.2**.25 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] *
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)
"UnempPrbRet": 0.0, "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$,