def test_stable_points(self): # Solve the constrained agent. Stable points exists only with a # borrowing constraint. constrained_agent = PerfForesightConsumerType(cycles=0, BoroCnstArt=0.0) constrained_agent.solve() # Check against pre-computed values. self.assertEqual(constrained_agent.solution[0].mNrmStE, 1.0) # Check that they are both the same, since the problem is deterministic self.assertEqual(constrained_agent.solution[0].mNrmStE, constrained_agent.solution[0].mNrmTrg)
def test_PerfForesightConsumerType(self): try: model = PerfForesightConsumerType() except: self.fail( "PerfForesightConsumerType failed to initialize with Params.init_perfect_foresight." )
def setUp(self): self.agent = PerfForesightConsumerTypeFast() self.agent_slow = PerfForesightConsumerType() self.agent_infinite = PerfForesightConsumerTypeFast(cycles=0) self.agent_infinite_slow = PerfForesightConsumerType(cycles=0) PF_dictionary = { "CRRA": 2.5, "DiscFac": 0.96, "Rfree": 1.03, "LivPrb": [0.98], "PermGroFac": [1.01], "T_cycle": 1, "cycles": 0, "AgentCount": 10000, } self.agent_alt = PerfForesightConsumerTypeFast(**PF_dictionary)
def setUp(self): """ Prepare to compare the models by initializing and solving them """ # Set up and solve infinite type # Define a test dictionary that should have the same solution in the # perfect foresight and idiosyncratic shocks models. test_dictionary = deepcopy(init_idiosyncratic_shocks) test_dictionary["LivPrb"] = [1.0] test_dictionary["DiscFac"] = 0.955 test_dictionary["PermGroFac"] = [1.0] test_dictionary["PermShkStd"] = [0.0] test_dictionary["TranShkStd"] = [0.0] test_dictionary["UnempPrb"] = 0.0 test_dictionary["T_cycle"] = 1 test_dictionary["T_retire"] = 0 test_dictionary["BoroCnstArt"] = None InfiniteType = IndShockConsumerType(**test_dictionary) InfiniteType.cycles = 0 InfiniteType.update_income_process() InfiniteType.solve() InfiniteType.unpack("cFunc") # Make and solve a perfect foresight consumer type with the same parameters PerfectForesightType = PerfForesightConsumerType(**test_dictionary) PerfectForesightType.cycles = 0 PerfectForesightType.solve() PerfectForesightType.unpack("cFunc") self.InfiniteType = InfiniteType self.PerfectForesightType = PerfectForesightType
def __init__(self): PFexample = PerfForesightConsumerType( ) # set up a consumer type and use default parameteres PFexample.cycles = 0 # Make this type have an infinite horizon PFexample.DiscFac = 0.05 PFexample.PermGroFac = [0.7] PFexample.solve() # solve the consumer's problem PFexample.unpackcFunc() # unpack the consumption function self.cFunc = PFexample.solution[0].cFunc self.a0 = self.cFunc(0) self.a1 = self.cFunc(1) - self.cFunc(0)
def reset_rng(self): """ Extended method that ensures random shocks are drawn from the same sequence on each simulation, which is important for structural estimation. This method is called automatically by initialize_sim(). Parameters ---------- None Returns ------- None """ PerfForesightConsumerType.reset_rng(self) # Reset IncShkDstn if it exists (it might not because reset_rng is called at init) if hasattr(self, "IncShkDstn"): T = len(self.IncShkDstn) for t in range(T): for dstn in self.IncShkDstn[t]: dstn.reset()
def setUp(self): """ Prepare to compare the models by initializing and solving them """ # Set up and solve infinite type import HARK.ConsumptionSaving.ConsumerParameters as Params # Define a test dictionary that should have the same solution in the # perfect foresight and idiosyncratic shocks models. test_dictionary = deepcopy(Params.init_idiosyncratic_shocks) test_dictionary['LivPrb'] = [1.] test_dictionary['DiscFac'] = 0.955 test_dictionary['PermGroFac'] = [1.] test_dictionary['PermShkStd'] = [0.] test_dictionary['TranShkStd'] = [0.] test_dictionary['UnempPrb'] = 0. test_dictionary['T_cycle'] = 1 test_dictionary['T_retire'] = 0 test_dictionary['BoroCnstArt'] = None InfiniteType = IndShockConsumerType(**test_dictionary) InfiniteType.cycles = 0 InfiniteType.updateIncomeProcess() InfiniteType.solve() InfiniteType.timeFwd() InfiniteType.unpackcFunc() # Make and solve a perfect foresight consumer type with the same parameters PerfectForesightType = PerfForesightConsumerType(**test_dictionary) PerfectForesightType.cycles = 0 PerfectForesightType.solve() PerfectForesightType.unpackcFunc() PerfectForesightType.timeFwd() self.InfiniteType = InfiniteType self.PerfectForesightType = PerfectForesightType
def setUp(self): self.agent = PerfForesightConsumerType() self.agent_infinite = PerfForesightConsumerType(cycles=0) PF_dictionary = { 'CRRA': 2.5, 'DiscFac': 0.96, 'Rfree': 1.03, 'LivPrb': [0.98], 'PermGroFac': [1.01], 'T_cycle': 1, 'cycles': 0, 'AgentCount': 10000 } self.agent_alt = PerfForesightConsumerType(**PF_dictionary)
from copy import copy from HARK.ConsumptionSaving.ConsIndShockModel import PerfForesightConsumerType fig6_par = copy(base_params) # Replace parameters. fig6_par['Rfree'] = 0.98 fig6_par['DiscFac'] = 1 fig6_par['PermGroFac'] = [0.99] fig6_par['CRRA'] = 2 fig6_par['BoroCnstArt'] = 0 fig6_par['T_cycle'] = 0 fig6_par['cycles'] = 0 fig6_par['quiet'] = False # Create the agent RichButPatientAgent = PerfForesightConsumerType(**fig6_par) # Check conditions RichButPatientAgent.checkConditions(verbose = 3) # Solve RichButPatientAgent.solve() # Plot mPlotMin, mPlotMax = 1, 9.5 plt.figure(figsize = (8,4)) m_grid = np.linspace(mPlotMin,mPlotMax,500) plt.plot(m_grid-1, RichButPatientAgent.solution[0].cFunc(m_grid), color="black") plt.text(mPlotMax-1+0.05,1,r"$b$",fontsize = 26) plt.text(mPlotMin-1,1.017,r"$c$",fontsize = 26) plt.xlim(mPlotMin-1,mPlotMax-1) plt.ylim(mPlotMin,1.016)
def __init__(self, Rfree=1.001, CRRA=2): PFaux = PerfForesightConsumerType( ) # set up a consumer type and use default parameteres PFaux.cycles = 0 # Make this type have an infinite horizon PFaux.DiscFac = 1 / Rfree PFaux.Rfree = Rfree PFaux.LivPrb = [1.0] PFaux.PermGroFac = [1.0] PFaux.CRRA = CRRA PFaux.solve() # solve the consumer's problem PFaux.unpackcFunc() # unpack the consumption function self.cFunc = PFaux.solution[0].cFunc
def plot1(Epsilon, DiscFac, PopGrowth, YearsPerGeneration, Initialk): '''Inputs: Epsilon: Elasticity of output with respect to capital/labour ratio DiscFac: One period discount factor YearPerGeneration: No. of years per generation PopGrowth: Gross growth rate of population in one period''' # kMax = 0.1 # Define some parameters Beta = DiscFac**YearsPerGeneration xi = PopGrowth**YearsPerGeneration Q = (1-Epsilon)*(Beta/(1+Beta))/xi kBar = Q**(1/(1-Epsilon)) # Create an agent that will solve the consumption problem PFagent = PerfForesightConsumerType(**init_perfect_foresight) PFagent.cycles = 1 # let the agent live the cycle of periods just once PFagent.T_cycle = 2 # Number of periods in the cycle PFagent.assign_parameters(PermGroFac = [0.000001]) # Income only in the first period PFagent.LivPrb = [1.] PFagent.DiscFac = Beta # Hark seems to have trouble with log-utility # so pass rho = 1 + something small. PFagent.CRRA = 1.001 PFagent.solve() # Plot the OLG capital accumulation curve and 45 deg line plt.figure(figsize=(9,6)) kt_range = np.linspace(0, kMax, 300) # Analitical solution plot ktp1 = Q*kt_range**Epsilon plt.plot(kt_range, ktp1, 'b-', label='Capital accumulation curve') plt.plot(kt_range, kt_range, 'k-', label='45 Degree line') # Plot the path kt_ar = Initialk ktp1_ar = 0. for i in range(3): # Compute Next Period's capital using HARK wage = (1-Epsilon)*kt_ar**Epsilon c = PFagent.solution[0].cFunc(wage) a = wage - c k1 = a/xi plt.arrow(kt_ar, ktp1_ar, 0., k1-ktp1_ar, length_includes_head=True, lw=0.01, width=0.0005, color='black', edgecolor=None) plt.arrow(kt_ar, k1, k1-kt_ar , 0., length_includes_head=True, lw=0.01, width=0.0005, color='black', edgecolor=None) # Update arrow kt_ar = k1 ktp1_ar = kt_ar # Plot kbar and initial k plt.plot(kBar, kBar, 'ro', label=r'$\bar{k}$') plt.plot(Initialk, 0.0005, 'co', label = '$k_0$') plt.legend() plt.xlim(0 ,kMax) plt.ylim(0, kMax) plt.xlabel('$k_t$') plt.ylabel('$k_{t+1}$') plt.show() return None
class testPerfForesightConsumerType(unittest.TestCase): def setUp(self): self.agent = PerfForesightConsumerType() self.agent_infinite = PerfForesightConsumerType(cycles=0) PF_dictionary = { "CRRA": 2.5, "DiscFac": 0.96, "Rfree": 1.03, "LivPrb": [0.98], "PermGroFac": [1.01], "T_cycle": 1, "cycles": 0, "AgentCount": 10000, } self.agent_alt = PerfForesightConsumerType(**PF_dictionary) def test_default_solution(self): self.agent.solve() c = self.agent.solution[0].cFunc self.assertEqual(c.x_list[0], -0.9805825242718447) self.assertEqual(c.x_list[1], 0.01941747572815533) self.assertEqual(c.y_list[0], 0) self.assertEqual(c.y_list[1], 0.511321002804608) self.assertEqual(c.decay_extrap, False) def test_another_solution(self): self.agent_alt.DiscFac = 0.90 self.agent_alt.solve() self.assertAlmostEqual(self.agent_alt.solution[0].cFunc(10).tolist(), 3.9750093524820787) def test_check_conditions(self): self.agent_infinite.check_conditions() self.assertTrue(self.agent_infinite.conditions["AIC"]) self.assertTrue(self.agent_infinite.conditions["GICRaw"]) self.assertTrue(self.agent_infinite.conditions["RIC"]) self.assertTrue(self.agent_infinite.conditions["FHWC"]) def test_simulation(self): self.agent_infinite.solve() # Create parameter values necessary for simulation SimulationParams = { "AgentCount": 10000, # Number of agents of this type "T_sim": 120, # Number of periods to simulate "aNrmInitMean": -6.0, # Mean of log initial assets "aNrmInitStd": 1.0, # Standard deviation of log initial assets "pLvlInitMean": 0.0, # Mean of log initial permanent income "pLvlInitStd": 0.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 } self.agent_infinite.assign_parameters( **SimulationParams ) # This implicitly uses the assign_parameters method of AgentType # Create PFexample object self.agent_infinite.track_vars = ["mNrm"] self.agent_infinite.initialize_sim() self.agent_infinite.simulate() self.assertAlmostEqual( np.mean(self.agent_infinite.history["mNrm"], axis=1)[40], -23.008063500363942, ) self.assertAlmostEqual( np.mean(self.agent_infinite.history["mNrm"], axis=1)[100], -27.164608851546927, ) ## Try now with the manipulation at time step 80 self.agent_infinite.initialize_sim() self.agent_infinite.simulate(80) # This actually does nothing because aNrmNow is # epiphenomenal. Probably should change mNrmNow instead self.agent_infinite.state_now['aNrm'] += (-5.0) self.agent_infinite.simulate(40) self.assertAlmostEqual( np.mean(self.agent_infinite.history["mNrm"], axis=1)[40], -23.008063500363942, ) self.assertAlmostEqual( np.mean(self.agent_infinite.history["mNrm"], axis=1)[100], -29.140261331951606, ) def test_stable_points(self): # Solve the constrained agent. Stable points exists only with a # borrowing constraint. constrained_agent = PerfForesightConsumerType(cycles=0, BoroCnstArt=0.0) constrained_agent.solve() # Check against pre-computed values. self.assertEqual(constrained_agent.solution[0].mNrmStE, 1.0) # Check that they are both the same, since the problem is deterministic self.assertEqual(constrained_agent.solution[0].mNrmStE, constrained_agent.solution[0].mNrmTrg)
"LivPrb": [0.98], # Survival probability "PermGroFac": [1.01], # Permanent income growth factor "BoroCnstArt": None, # Artificial borrowing constraint "aXtraCount": 200, # Maximum number of gridpoints in consumption function # Parameters that characterize the nature of time "T_cycle": 1, # Number of periods in the cycle for this agent type "cycles": 0, # Number of times the cycle occurs (0 --> infinitely repeated) } # %% [markdown] # ## Solving and examining the solution of the perfect foresight model # # With the dictionary we have just defined, we can create an instance of $\texttt{PerfForesightConsumerType}$ by passing the dictionary to the class (as if the class were a function). This instance can then be solved by invoking its $\texttt{solve}$ method. # %% PFexample = PerfForesightConsumerType(**PerfForesightDict) PFexample.cycles = 0 PFexample.solve() # %% [markdown] # The $\texttt{solve}$ method fills in the instance's attribute $\texttt{solution}$ as a time-varying list of solutions to each period of the consumer's problem. In this case, $\texttt{solution}$ will be a list with exactly one instance of the class $\texttt{ConsumerSolution}$, representing the solution to the infinite horizon model we specified. # %% print(PFexample.solution) # %% [markdown] # Each element of $\texttt{solution}$ has a few attributes. To see all of them, we can use the \texttt{vars} built in function: # # the consumption functions reside in the attribute $\texttt{cFunc}$ of each element of $\texttt{ConsumerType.solution}$. This method creates a (time varying) attribute $\texttt{cFunc}$ that contains a list of consumption functions. # %%
def setUp(self): self.agent = PerfForesightConsumerType() self.agents = 5 * [self.agent]
def FisherPlot2(Y1, Y2, B1, RHi, RLo, c1Max, c2Max): # Basic setup of perfect foresight consumer PFexample = PerfForesightConsumerType( ) # set up a consumer type and use default parameteres PFexample.cycles = 1 # let the agent live the cycle of periods just once PFexample.T_cycle = 2 # Number of periods in the cycle PFexample.PermGroFac = [1.] # No automatic growth in income across periods PFexample.LivPrb = [1.] # No chance of dying before the second period PFexample.aNrmInitStd = 0. PFexample.AgentCount = 1 CRRA = 2. Beta = PFexample.DiscFac # Set the parameters we enter PFexample.aNrmInitMean = B1 # Create two models, one for RfreeHigh and one for RfreeLow PFexampleRHi = deepcopy(PFexample) PFexampleRHi.Rfree = RHi PFexampleRLo = deepcopy(PFexample) PFexampleRLo.Rfree = RLo c1Min = 0. c2Min = 0. # Solve the model for RfreeHigh try: PFexampleRHi.solve() PFexampleRLo.solve() except: print( 'Those parameter values violate a condition required for solution!' ) # Plot the chart plt.figure(figsize=(8, 8)) plt.xlabel('Period 1 Consumption $C_1$') plt.ylabel('Period 2 Consumption $C_2$') plt.ylim([c2Min, c2Max]) plt.xlim([c1Min, c1Max]) # Plot the budget constraints C1_bc_RLo = np.linspace(c1Min, B1 + Y1 + Y2 / RLo, 10, endpoint=True) C2_bc_RLo = (Y1 + B1 - C1_bc_RLo) * RLo + Y2 plt.plot(C1_bc_RLo, C2_bc_RLo, 'k-', label='Budget Constraint R Low') C1_bc_RHi = np.linspace(c1Min, B1 + Y1 + Y2 / RHi, 10, endpoint=True) C2_bc_RHi = (Y1 + B1 - C1_bc_RHi) * RHi + Y2 plt.plot(C1_bc_RHi, C2_bc_RHi, 'k--', label='Budget Constraint R High') # The optimal consumption bundles C1_opt_RLo = PFexampleRLo.solution[0].cFunc(B1 + Y1 + Y2 / RLo) C2_opt_RLo = PFexampleRLo.solution[1].cFunc((Y1 + B1 - C1_opt_RLo) * RLo + Y2) C1_opt_RHi = PFexampleRHi.solution[0].cFunc(B1 + Y1 + Y2 / RHi) C2_opt_RHi = PFexampleRHi.solution[1].cFunc((Y1 + B1 - C1_opt_RHi) * RHi + Y2) # Plot the indifference curves V_RLo = C1_opt_RLo**(1 - CRRA) / (1 - CRRA) + Beta * C2_opt_RLo**( 1 - CRRA) / (1 - CRRA) # Get max utility C1_V_RLo = np.linspace(((1 - CRRA) * V_RLo)**(1 / (1 - CRRA)) + 0.5, c1Max, 1000) C2_V_RLo = (((1 - CRRA) * V_RLo - C1_V_RLo**(1 - CRRA)) / Beta)**(1 / (1 - CRRA)) plt.plot(C1_V_RLo, C2_V_RLo, 'b-', label='Indiferrence Curve R Low') V_RHi = C1_opt_RHi**(1 - CRRA) / (1 - CRRA) + Beta * C2_opt_RHi**( 1 - CRRA) / (1 - CRRA) # Get max utility C1_V_RHi = np.linspace(((1 - CRRA) * V_RHi)**(1 / (1 - CRRA)) + 0.5, c1Max, 1000) C2_V_RHi = (((1 - CRRA) * V_RHi - C1_V_RHi**(1 - CRRA)) / Beta)**(1 / (1 - CRRA)) plt.plot(C1_V_RHi, C2_V_RHi, 'b--', label='Indiferrence Curve R High') # The substitution effect C1_Subs = (V_RHi * (1 - CRRA) / (1 + Beta * (RLo * Beta)**((1 - CRRA) / CRRA)))**(1 / (1 - CRRA)) C2_Subs = C1_Subs * (RLo * Beta)**(1 / CRRA) # The Human wealth effect Y2HW = Y2 * RLo / RHi C1HW = Y2HW / (RLo + (RLo)**(1 / CRRA)) C2HW = C1HW * (RLo * Beta)**(1 / CRRA) C1_bc_HW = np.linspace(c1Min, B1 + Y1 + Y2HW / RLo, 10, endpoint=True) C2_bc_HW = (Y1 + B1 - C1_bc_HW) * RLo + Y2HW plt.plot(C1_bc_HW, C2_bc_HW, 'k:') VHW = (C1HW**(1 - CRRA)) / (1 - CRRA) + (Beta * C2HW** (1 - CRRA)) / (1 - CRRA) C1_V_HW = np.linspace(((1 - CRRA) * VHW)**(1 / (1 - CRRA)) + 0.5, c1Max, 1000) C2_V_HW = (((1 - CRRA) * VHW - C1_V_HW**(1 - CRRA)) / Beta)**(1 / (1 - CRRA)) plt.plot(C1_V_HW, C2_V_HW, 'b:') # Plot the points of interest plt.plot(C1_opt_RLo, C2_opt_RLo, 'ro', label='A: Optimal Consumption R Low') plt.plot(C1_Subs, C2_Subs, 'go', label='B: Income effect DB \n Substitution effect BC') plt.plot(C1_opt_RHi, C2_opt_RHi, 'mo', label='C: Optimal Consumption R High') plt.plot(C1HW, C2HW, 'co', label='D: HW effect AD') plt.legend() plt.show() return None
# %% {"tags": [], "jupyter": {"source_hidden": true}} PFGICRawHoldsFHWCFailsRICFails_par = copy(base_params) # Replace parameters. PFGICRawHoldsFHWCFailsRICFails_par['Rfree'] = 0.98 PFGICRawHoldsFHWCFailsRICFails_par['DiscFac'] = 1 PFGICRawHoldsFHWCFailsRICFails_par['PermGroFac'] = [0.99] PFGICRawHoldsFHWCFailsRICFails_par['CRRA'] = 2 PFGICRawHoldsFHWCFailsRICFails_par['BoroCnstArt'] = 0 PFGICRawHoldsFHWCFailsRICFails_par['T_cycle'] = 0 PFGICRawHoldsFHWCFailsRICFails_par['cycles'] = 0 PFGICRawHoldsFHWCFailsRICFails_par['quiet'] = False # Create the agent RichButPatientPFConstrainedAgent = PerfForesightConsumerType(**PFGICRawHoldsFHWCFailsRICFails_par) # Check conditions RichButPatientPFConstrainedAgent.check_conditions(verbose=3) # Solve RichButPatientPFConstrainedAgent.solve() # Plot mPlotMin, mPlotMax = 1, 9.5 plt.figure(figsize=(8, 4)) m_grid = np.linspace(mPlotMin, mPlotMax, 500) plt.plot(m_grid-1, RichButPatientPFConstrainedAgent.solution[0].cFunc(m_grid), color="black") plt.text(mPlotMax-1+0.05, 1, r"$b$", fontsize=26) plt.text(mPlotMin-1, 1.017, r"$c$", fontsize=26) plt.xlim(mPlotMin-1, mPlotMax-1) plt.ylim(mPlotMin, 1.016)
PFGICRawHoldsFHWCFailsRICFails_par['DiscFac'] = 1.0 PFGICRawHoldsFHWCFailsRICFails_par['PermGroFac'] = [0.99] PFGICRawHoldsFHWCFailsRICFails_par['CRRA'] = 2 PFGICRawHoldsFHWCFailsRICFails_par['BoroCnstArt'] = 0.0 PFGICRawHoldsFHWCFailsRICFails_par['T_cycle'] = 1 # No seasonal cycles PFGICRawHoldsFHWCFailsRICFails_par['T_retire'] = 0 PFGICRawHoldsFHWCFailsRICFails_par['cycles'] = 400 # This many periods PFGICRawHoldsFHWCFailsRICFails_par['MaxKinks'] = 400 PFGICRawHoldsFHWCFailsRICFails_par['quiet'] = False PFGICRawHoldsFHWCFailsRICFails_par['BoroCnstArt'] = 0.0 # Borrowing constraint PFGICRawHoldsFHWCFailsRICFails_par['LivPrb'] = [1.0] # Create the agent HWRichButReturnPatientPFConstrainedAgent = \ PerfForesightConsumerType(**PFGICRawHoldsFHWCFailsRICFails_par, quietly=True ) # Solve and report on conditions this_agent = HWRichButReturnPatientPFConstrainedAgent this_agent.solve(quietly=False, messaging_level=logging.DEBUG) # Plot mPlotMin, mPlotMax = 1, 9.5 plt.figure(figsize=(8, 4)) m_grid = np.linspace(mPlotMin, mPlotMax, 500) plt.plot(m_grid-1, this_agent.solution[0].cFunc(m_grid), color="black") plt.text(mPlotMax-1+0.05, 1, r"$b$", fontsize=26) plt.text(mPlotMin-1, 1.017, r"$c$", fontsize=26) plt.xlim(mPlotMin-1, mPlotMax-1) plt.ylim(mPlotMin, 1.016)
# First we need to set out a dictionary CRRA = 2. # Coefficient of relative risk aversion Rfree = 1.03 # Interest factor on assets DiscFac = 0.97 # Intertemporal discount factor LivPrb = [1.0] # Survival probability PermGroFac = [1.01] # Permanent income growth factor AgentCount = 1 # Number of agents of this type (only matters for simulation) T_cycle = 1 # Number of periods in the cycle for this agent type cycles = 0 # Agent is infinitely lived # Make a dictionary to specify a perfect foresight consumer type dict_wealth = { 'CRRA': CRRA, 'Rfree': Rfree, 'DiscFac': DiscFac, 'LivPrb': LivPrb, 'PermGroFac': PermGroFac, 'AgentCount': AgentCount, 'T_cycle': T_cycle, 'cycles': cycles } # Now lets pass our dictionary to our consumer class PFwealth = PerfForesightConsumerType(**dict_wealth) # %% [markdown] # We can see that consumption is higher for all market resources when R is low, owing to the human wealth effect. And that the saving rate is very sensitive to changes in R (look at when m=1, the savings rate goes from -0.1 to- 0.5 when R moves from 1.06 to 1.03. # %%
"DiscFac" : 0.96, # Default intertemporal discount factor "LivPrb" : [0.98], # Survival probability "PermGroFac" :[1.01], # Permanent income growth factor # Parameters that characterize the nature of time "T_cycle" : 1, # Number of periods in the cycle for this agent type "cycles" : 0 # Number of times the cycle occurs (0 --> infinitely repeated) } # %% [markdown] # ## Inspecting the solution # # With the dictionary we have just defined, we can create an instance of $\texttt{PerfForesightConsumerType}$ by passing the dictionary to the class (as if the class were a function). This instance can then be solved by invoking its $\texttt{solve}$ method. # %% PFexample = PerfForesightConsumerType(**PerfForesightDict) PFexample.cycles = 0 PFexample.solve() # %% [markdown] # The $\texttt{solve}$ method fills in the instance's attribute $\texttt{solution}$ as a time-varying list of solutions to each period of the consumer's problem. In this case, $\texttt{solution}$ will be a list with exactly one instance of the class $\texttt{ConsumerSolution}$, representing the solution to the infinite horizon model we specified. # %% print(PFexample.solution) # %% [markdown] # Each element of $\texttt{solution}$ has a few attributes. To see all of them, we can use the $\texttt{vars}$ built in function: the consumption functions are instantiated in the attribute $\texttt{cFunc}$ of each element of $\texttt{ConsumerType.solution}$. This method creates a (time varying) attribute $\texttt{cFunc}$ that contains a list of consumption functions by age. # %% print(vars(PFexample.solution[0]))
def setUp(self): self.agent = PerfForesightConsumerType() self.agent_infinite = PerfForesightConsumerType(cycles=0)
# Import the machinery for solving the perfect foresight model and the default parameters from HARK.ConsumptionSaving.ConsIndShockModel import PerfForesightConsumerType # Import the consumer type import HARK.ConsumptionSaving.ConsumerParameters as Params # Import default parameters # Now extract the default values of the parameters of interest CRRA = Params.CRRA Rfree = Params.Rfree DiscFac = Params.DiscFac PermGroFac = Params.PermGroFac rfree = Rfree-1 # %% # Now create a perfect foresight consumer example, PFagent = PerfForesightConsumerType(**Params.init_perfect_foresight) PFagent.cycles = 0 # We need the consumer to be infinitely lived PFagent.LivPrb = [1.0] # Suppress the possibility of dying # Solve the agent's problem PFagent.solve() # %% # Plot the consumption function # Remember, after invoking .solve(), the consumption function is stored as PFagent.solution[0].cFunc # Set out some range of market resources that we want to plot consumption for mMin = 0 mMax = 20
def FisherPlot(Y1, Y2, B1, R, c1Max, c2Max): # Basic setup of perfect foresight consumer # We first create an instance of the class # PerfForesightConsumerType, with its standard parameters. PFexample = PerfForesightConsumerType() PFexample.cycles = 1 # let the agent live the cycle of periods just once PFexample.T_cycle = 2 # Number of periods in the cycle PFexample.PermGroFac = [1.] # No automatic growth in income across periods PFexample.LivPrb = [1.] # No chance of dying before the second period PFexample.aNrmInitStd = 0. PFexample.AgentCount = 1 CRRA = PFexample.CRRA Beta = PFexample.DiscFac # Set interest rate and bank balances from input. PFexample.Rfree = R PFexample.aNrmInitMean = B1 # Solve the model: this generates the optimal consumption function. # Try-except blocks "try" to execute the code in the try block. If an # error occurs, the except block is executed and the application does # not halt try: PFexample.solve() except: print( 'Those parameter values violate a condition required for solution!' ) # Create the figure c1Min = 0. c2Min = 0. plt.figure(figsize=(8, 8)) plt.xlabel('Period 1 Consumption $C_1$') plt.ylabel('Period 2 Consumption $C_2$') plt.ylim([c2Min, c2Max]) plt.xlim([c1Min, c1Max]) # Plot the budget constraint C1_bc = np.linspace(c1Min, B1 + Y1 + Y2 / R, 10, endpoint=True) C2_bc = (Y1 + B1 - C1_bc) * R + Y2 plt.plot(C1_bc, C2_bc, 'k-', label='Budget Constraint') # Plot the optimal consumption bundle C1 = PFexample.solution[0].cFunc(B1 + Y1 + Y2 / R) C2 = PFexample.solution[1].cFunc((Y1 + B1 - C1) * R + Y2) plt.plot(C1, C2, 'ro', label='Optimal Consumption') # Plot the indifference curve V = C1**(1 - CRRA) / (1 - CRRA) + Beta * C2**(1 - CRRA) / ( 1 - CRRA) # Get max utility C1_V = np.linspace(((1 - CRRA) * V)**(1 / (1 - CRRA)) + 0.5, c1Max, 1000) C2_V = (((1 - CRRA) * V - C1_V**(1 - CRRA)) / Beta)**(1 / (1 - CRRA)) plt.plot(C1_V, C2_V, 'b-', label='Indiferrence Curve') # Add a legend and display the plot plt.legend() plt.show() return None
def __init__(self, **kwargs): PerfForesightConsumerType.__init__(self, **kwargs) self.solve_one_period = make_one_period_oo_solver(ConsPerfForesightSolverFast)
# Now we need to give our consumer parameter values that allow us to solve the consumer's problem # Invoke it to create a dictionary called Paramod (Params that we will modify) Paramod = deepcopy(init_perfect_foresight) # deepcopy prevents later overwriting # Extract the parameters from the dictionary to make them easy to reference CRRA = Paramod['CRRA'] # Coefficient of relative risk aversion Rfree = Paramod['Rfree'] # Interest factor on assets DiscFac = Paramod['DiscFac'] # Intertemporal discount factor PermGroFac = Paramod['PermGroFac'] # Permanent income growth factor LivPrb = Paramod['LivPrb'] = [1.0] # Survival probability of 100 percent cycles = Paramod['cycles'] = 0 # This says that it is an infinite horizon model # + # Now let's pass our dictionary to our consumer class to create an instance PFagent = PerfForesightConsumerType(**Paramod) # Any parameters we did not modify get their default values # Solve the agent's problem PFagent.solve() # + # Plot the consumption function approximation versus the "true" consumption function # Set out some range of market resources that we want to plot consumption for mMin = 0 mMax = 10 numPoints = 100 m_range = np.linspace(mMin, mMax, numPoints) # This creates an array of points in the given range wealthHmn = PFagent.solution[0].hNrm # normalized human wealth is constructed when we .solve() wealthMkt = m_range # bank balances plus current income
def __init__(self, **kwargs): PerfForesightConsumerType.__init__(self, **kwargs) self.solveOnePeriod = makeOnePeriodOOSolver( ConsPerfForesightSolverFast)
'LivPrb': [0.98], 'PermGroFac': [1.01], 'T_cycle': 1, 'cycles': 0, 'AgentCount': 10000 } # To those curious enough to open this hidden cell, you might notice that we defined # a few extra parameters in that dictionary: T_cycle, cycles, and AgentCount. Don't # worry about these for now. # %% [markdown] # Let's make an **object** named $\texttt{PFexample}$ which is an **instance** of the $\texttt{PerfForesightConsumerType}$ class. The object $\texttt{PFexample}$ will bundle together the abstract mathematical description of the solution embodied in $\texttt{PerfForesightConsumerType}$, and the specific set of parameter values defined in $\texttt{PF_dictionary}$. Such a bundle is created passing $\texttt{PF_dictionary}$ to the class $\texttt{PerfForesightConsumerType}$: # %% PFexample = PerfForesightConsumerType(**PF_dictionary) # the asterisks ** basically say "here come some arguments" to PerfForesightConsumerType # %% [markdown] # In $\texttt{PFexample}$, we now have _defined_ the problem of a particular infinite horizon perfect foresight consumer who knows how to solve this problem. # # ## Solving an Agent's Problem # # To tell the agent actually to solve the problem, we call the agent's $\texttt{solve}$ **method**. (A **method** is essentially a function that an object runs that affects the object's own internal characteristics -- in this case, the method adds the consumption function to the contents of $\texttt{PFexample}$.) # # The cell below calls the $\texttt{solve}$ method for $\texttt{PFexample}$ # %% PFexample.solve() # %% [markdown]
PF_dictionary0 = { 'CRRA' : 1.01, 'DiscFac' : 0.99, 'Rfree' : 1.03, 'LivPrb' : [1.0], 'PermGroFac' : [1.02], 'T_cycle' : 1, 'cycles' : 0, 'AgentCount' : 10000 } # To those curious enough to open this hidden cell, you might notice that we defined # a few extra parameters in that dictionary: T_cycle, cycles, and AgentCount. Don't # worry about these for now. PFexample0 = PerfForesightConsumerType(**PF_dictionary0) # the asterisks ** basically says "here come some arguments" to PerfForesightConsumerType PFexample0.solve() # Solve with those parameters m = 4 # market wealth includes current income p = 1 # normalize permanent income to one # Extract interest and growth factors used in solution R = PFexample0.Rfree PermGroFac0 = PFexample0.PermGroFac[0] h0 = 1/(1-PermGroFac0/R) c0 = np.asscalar(PFexample0.solution[0].cFunc(m)) # Evaluate cFunc at m y0 = 1+(m-1)*(R-1) # Total income = noncapital plus capital income s0 = (y0 - c0)/y0 # print y0,h0,c0,s0 PF_dictionary1 = deepcopy(PF_dictionary0) PermGroFac1 = 1.025
class testPerfForesightConsumerType(unittest.TestCase): def setUp(self): self.agent = PerfForesightConsumerType() self.agent_infinite = PerfForesightConsumerType(cycles=0) PF_dictionary = { 'CRRA': 2.5, 'DiscFac': 0.96, 'Rfree': 1.03, 'LivPrb': [0.98], 'PermGroFac': [1.01], 'T_cycle': 1, 'cycles': 0, 'AgentCount': 10000 } self.agent_alt = PerfForesightConsumerType(**PF_dictionary) def test_default_solution(self): self.agent.solve() c = self.agent.solution[0].cFunc self.assertEqual(c.x_list[0], -0.9805825242718447) self.assertEqual(c.x_list[1], 0.01941747572815533) self.assertEqual(c.y_list[0], 0) self.assertEqual(c.y_list[1], 0.511321002804608) self.assertEqual(c.decay_extrap, False) def test_another_solution(self): self.agent_alt.DiscFac = 0.90 self.agent_alt.solve() self.assertAlmostEqual(self.agent_alt.solution[0].cFunc(10).tolist(), 3.9750093524820787) def test_checkConditions(self): self.agent_infinite.checkConditions() self.assertTrue(self.agent_infinite.conditions['AIC']) self.assertTrue(self.agent_infinite.conditions['GICPF']) self.assertTrue(self.agent_infinite.conditions['RIC']) self.assertTrue(self.agent_infinite.conditions['FHWC']) def test_simulation(self): self.agent_infinite.solve() # Create parameter values necessary for simulation SimulationParams = { "AgentCount": 10000, # Number of agents of this type "T_sim": 120, # Number of periods to simulate "aNrmInitMean": -6.0, # Mean of log initial assets "aNrmInitStd": 1.0, # Standard deviation of log initial assets "pLvlInitMean": 0.0, # Mean of log initial permanent income "pLvlInitStd": 0.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 } self.agent_infinite( **SimulationParams ) # This implicitly uses the assignParameters method of AgentType # Create PFexample object self.agent_infinite.track_vars = ['mNrmNow'] self.agent_infinite.initializeSim() self.agent_infinite.simulate() self.assertAlmostEqual( np.mean(self.agent_infinite.history['mNrmNow'], axis=1)[40], -23.008063500363942) self.assertAlmostEqual( np.mean(self.agent_infinite.history['mNrmNow'], axis=1)[100], -27.164608851546927) ## Try now with the manipulation at time step 80 self.agent_infinite.initializeSim() self.agent_infinite.simulate(80) self.agent_infinite.aNrmNow += -5. # Adjust all simulated consumers' assets downward by 5 self.agent_infinite.simulate(40) self.assertAlmostEqual( np.mean(self.agent_infinite.history['mNrmNow'], axis=1)[40], -23.008063500363942) self.assertAlmostEqual( np.mean(self.agent_infinite.history['mNrmNow'], axis=1)[100], -29.140261331951606)
# %% from HARK.ConsumptionSaving.ConsIndShockModel import ( PerfForesightConsumerType, IndShockConsumerType, KinkedRconsumerType, init_lifecycle, init_cyclical) from HARK.utilities import plotFuncsDer, plotFuncs from time import time # %% mystr = lambda number: "{:.4f}".format(number) # %% do_simulation = True # %% # Make and solve an example perfect foresight consumer PFexample = PerfForesightConsumerType() # Make this type have an infinite horizon PFexample.cycles = 0 # %% start_time = time() PFexample.solve() end_time = time() print("Solving a perfect foresight consumer took " + mystr(end_time - start_time) + " seconds.") PFexample.unpackcFunc() PFexample.timeFwd() # %% # Plot the perfect foresight consumption function print("Perfect foresight consumption function:")
'IncUnemp': 0.3, # ... and income for unemployed people (30 percent of "permanent" income) 'BoroCnstArt': 0.0, # ... and specifying the location of the borrowing constraint (0 means no borrowing is allowed) 'cycles': 0 # signifies an infinite horizon solution (see below) } # %% [markdown] # ## Other Attributes are Inherited from PerfForesightConsumerType # # You can see all the **attributes** of an object in Python by using the `dir()` command. From the output of that command below, you can see that many of the model variables are now attributes of this object, along with many other attributes that are outside the scope of this tutorial. # %% from HARK.ConsumptionSaving.ConsIndShockModel import PerfForesightConsumerType pfc = PerfForesightConsumerType() dir(pfc) # %% [markdown] # In python terminology, `IndShockConsumerType` is a **superclass** of `PerfForesightConsumerType`. This means that it builds on the functionality of its parent type (including, for example, the definition of the utility function). You can find the superclasses of a type in Python using the `__bases__` attribute: # %% from HARK.ConsumptionSaving.ConsIndShockModel import IndShockConsumerType IndShockConsumerType.__bases__ # %% # So, let's create an instance of the IndShockConsumerType IndShockExample = IndShockConsumerType(**IndShockDictionary) # %% [markdown]