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 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 __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 __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 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 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
'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 PF_dictionary1['PermGroFac'] = [PermGroFac1]
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)
"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. # %% print(vars(PFexample.solution[0]))
# 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) make('PFGICHoldsFHWCFailsRICFails') # %%
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)
# %% 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] # Running the $\texttt{solve}$ method creates the **attribute** of $\texttt{PFexample}$ named $\texttt{solution}.$ In fact, every subclass of $\texttt{AgentType}$ works the same way: The class definition contains the abstract algorithm that knows how to solve the model, but to obtain the particular solution for a specific instance (paramterization/configuration), that instance must be instructed to $\texttt{solve()}$ its problem. # # The $\texttt{solution}$ attribute is always a _list_ of solutions to a single period of the problem. In the case of an infinite horizon model like the one here, there is just one element in that list -- the solution to all periods of the infinite horizon problem. The consumption function stored as the first element (element 0) of the solution list can be retrieved by: # %% PFexample.solution[0].cFunc # %% [markdown] # One of the results proven in the associated [the lecture notes](http://econ.jhu.edu/people/ccarroll/public/lecturenotes/consumption/PerfForesightCRRA/) is that, for the specific problem defined above, there is a solution in which the _ratio_ $c = C/P$ is a linear function of the _ratio_ of market resources to permanent income, $m = M/P$. # # This is why $\texttt{cFunc}$ can be represented by a linear interpolation. It can be plotted using the command below: #
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 wealthTot = wealthHmn+wealthMkt # Total wealth is the sum of human and market # Feed our range of market resources into our consumption function in order to get consumption at each point
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
# 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) make('PFGICRawHoldsFHWCFailsRICFails')
# 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 numPoints = 100 m_range = np.linspace(mMin, mMax, numPoints) # This creates an array of points in the given range # Feed our range of market resources into our consumption function in order to get consumption at each point