def updateSolutionTerminal(self): ''' Update the terminal period solution. This method should be run when a new AgentType is created or when CRRA changes. Parameters ---------- none Returns ------- none ''' IndShockConsumerType.updateSolutionTerminal(self) # Make replicated terminal period solution: consume all resources, no human wealth, minimum m is 0 StateCount = self.MrkvArray.shape[0] self.solution_terminal.cFunc = StateCount*[self.cFunc_terminal_] self.solution_terminal.vFunc = StateCount*[self.solution_terminal.vFunc] self.solution_terminal.vPfunc = StateCount*[self.solution_terminal.vPfunc] self.solution_terminal.vPPfunc = StateCount*[self.solution_terminal.vPPfunc] self.solution_terminal.mNrmMin = np.zeros(StateCount) self.solution_terminal.hRto = np.zeros(StateCount) self.solution_terminal.MPCmax = np.ones(StateCount) self.solution_terminal.MPCmin = np.ones(StateCount)
def __init__(self, cycles=1, time_flow=True, **kwds): ''' Instantiate a new ConsumerType with given data. See ConsumerParameters.init_idiosyncratic_shocks for a dictionary of the keywords that should be passed to the constructor. Parameters ---------- cycles : int Number of times the sequence of periods should be solved. time_flow : boolean Whether time is currently "flowing" forward for this instance. Returns ------- None ''' # Initialize a basic AgentType IndShockConsumerType.__init__(self, cycles=cycles, time_flow=time_flow, **kwds) # Add consumer-type specific objects, copying to create independent versions self.solveOnePeriod = solvePrefLaborShock # idiosyncratic shocks solver self.update() # Make assets grid, income process, terminal solution
def advanceIncShks(self): ''' Advance the permanent and transitory income shocks to the next period of the shock history objects, after first advancing the preference shocks. Parameters ---------- none Returns ------- none ''' self.PrefShkNow = self.PrefShkHist[self.Shk_idx,:] IndShockConsumerType.advanceIncShks(self)
def advanceIncShks(self): ''' Advance the permanent and transitory income shocks to the next period of the shock history objects. Parameters ---------- none Returns ------- none ''' self.MrkvNow = self.MrkvHist[self.Shk_idx,:] IndShockConsumerType.advanceIncShks(self)
def getShocks(self): ''' Finds the effective permanent and transitory shocks this period by combining the aggregate and idiosyncratic shocks of each type. Parameters ---------- None Returns ------- None ''' IndShockConsumerType.getShocks(self) # Update idiosyncratic shocks self.TranShkNow = self.TranShkNow*self.TranShkAggNow*self.wRteNow self.PermShkNow = self.PermShkNow*self.PermShkAggNow
def getShocks(self): ''' Finds the effective permanent and transitory shocks this period by combining the aggregate and idiosyncratic shocks of each type. Parameters ---------- None Returns ------- None ''' IndShockConsumerType.getShocks(self) # Update idiosyncratic shocks self.TranShkNow = self.TranShkNow * self.TranShkAggNow * self.wRteNow self.PermShkNow = self.PermShkNow * self.PermShkAggNow
def update(self): ''' Updates the assets grid, income process, terminal period solution, and preference shock process. A very slight extension of IndShockConsumerType.update() for the preference shock model. Parameters ---------- None Returns ------- None ''' IndShockConsumerType.update(self) # Update assets grid, income process, terminal solution self.updatePrefShockProcess() # Update the discrete preference shock process
def __init__(self,time_flow=True,**kwds): ''' Make a new instance of a representative agent. Parameters ---------- time_flow : boolean Whether time is currently "flowing" forward for this instance. Returns ------- None ''' IndShockConsumerType.__init__(self,cycles=0,time_flow=time_flow,**kwds) self.AgentCount = 1 # Hardcoded, because this is rep agent self.solveOnePeriod = solveConsRepAgent self.delFromTimeInv('Rfree','BoroCnstArt','vFuncBool','CubicBool')
def perturbParameterToGetcPlotList(base_dictionary, param_name, param_min, param_max, N=20, time_vary=False): param_vec = np.linspace( param_min, param_max, num=N, endpoint=True ) # vector of alternative values of the parameter to examine thisConsumer = IndShockConsumerType( **my_dictionary) # create an instance of the consumer type thisConsumer.cycles = 0 # Make this type have an infinite horizon x = np.linspace( mMinVal, mMaxVal, xPoints, endpoint=True ) # Define a vector of x values that span the range from the minimum to the maximum values of m for j in range( N): # loop from the first to the last values of the parameter if time_vary: # Some parameters are time-varying; others are not setattr(thisConsumer, param_name, [param_vec[j]]) else: setattr(thisConsumer, param_name, param_vec[j]) thisConsumer.update( ) # set up the preliminaries required to solve the problem thisConsumer.solve() # solve the problem y = thisConsumer.solution[0].cFunc( x ) # Get the values of the consumption function at the points in the vector of x points pylab.plot( x, y, label=str(round(param_vec[j], 3)) ) # plot it and generate a label indicating the rounded value of the parameter pylab.legend(loc='upper right') # put the legend in the upper right return pylab # return the figure
def getShocks(self): ''' Gets permanent and transitory income shocks for this period as well as preference shocks. Parameters ---------- None Returns ------- None ''' IndShockConsumerType.getShocks(self) # Get permanent and transitory income shocks PrefShkNow = np.zeros(self.AgentCount) # Initialize shock array for t in range(self.T_cycle): these = t == self.t_cycle N = np.sum(these) if N > 0: PrefShkNow[these] = self.RNG.permutation(approxMeanOneLognormal(N,sigma=self.PrefShkStd[t])[1]) self.PrefShkNow = PrefShkNow
def __init__(self,cycles=1,time_flow=True,**kwds): ''' Instantiate a new ConsumerType with given data, and construct objects to be used during solution (income distribution, assets grid, etc). See ConsumerParameters.init_pref_shock for a dictionary of the keywords that should be passed to the constructor. Parameters ---------- cycles : int Number of times the sequence of periods should be solved. time_flow : boolean Whether time is currently "flowing" forward for this instance. Returns ------- None ''' IndShockConsumerType.__init__(self,**kwds) self.solveOnePeriod = solveConsPrefShock # Choose correct solver
def __init__(self, cycles=1, time_flow=True, **kwds): ''' Instantiate a new ConsumerType with given data, and construct objects to be used during solution (income distribution, assets grid, etc). See ConsumerParameters.init_pref_shock for a dictionary of the keywords that should be passed to the constructor. Parameters ---------- cycles : int Number of times the sequence of periods should be solved. time_flow : boolean Whether time is currently "flowing" forward for this instance. Returns ------- None ''' IndShockConsumerType.__init__(self, **kwds) self.solveOnePeriod = solveConsPrefShock # Choose correct solver
def simBirth(self,which_agents): ''' Makes new consumers for the given indices. Initialized variables include aNrm and pLvl, as well as time variables t_age and t_cycle. Normalized assets and permanent income levels are drawn from lognormal distributions given by aNrmInitMean and aNrmInitStd (etc). Parameters ---------- which_agents : np.array(Bool) Boolean array of size self.AgentCount indicating which agents should be "born". Returns ------- None ''' IndShockConsumerType.simBirth(self,which_agents) if hasattr(self,'aLvlNow'): self.aLvlNow[which_agents] = self.aNrmNow[which_agents]*self.pLvlNow[which_agents] else: self.aLvlNow = self.aNrmNow*self.pLvlNow
def simBirth(self, which_agents): ''' Makes new consumers for the given indices. Initialized variables include aNrm and pLvl, as well as time variables t_age and t_cycle. Normalized assets and permanent income levels are drawn from lognormal distributions given by aNrmInitMean and aNrmInitStd (etc). Parameters ---------- which_agents : np.array(Bool) Boolean array of size self.AgentCount indicating which agents should be "born". Returns ------- None ''' IndShockConsumerType.simBirth(self, which_agents) if hasattr(self, 'aLvlNow'): self.aLvlNow[which_agents] = self.aNrmNow[ which_agents] * self.pLvlNow[which_agents] else: self.aLvlNow = self.aNrmNow * self.pLvlNow
end_time = clock() print('Solving a perfect foresight consumer took ' + mystr(end_time - start_time) + ' seconds.') PFexample.unpackcFunc() PFexample.timeFwd() # Plot the perfect foresight consumption function print('Linear consumption function:') mMin = PFexample.solution[0].mNrmMin #plotFuncs(PFexample.cFunc[0],mMin,mMin+10) ############################################################################### # Make and solve an example consumer with idiosyncratic income shocks IndShockExample = IndShockConsumerType(**Params.init_idiosyncratic_shocks) IndShockExample.cycles = 0 # Make this type have an infinite horizon start_time = clock() IndShockExample.solve() end_time = clock() print('Solving a consumer with idiosyncratic shocks took ' + mystr(end_time - start_time) + ' seconds.') IndShockExample.unpackcFunc() IndShockExample.timeFwd() # Plot the consumption function and MPC for the infinite horizon consumer #print('Concave consumption function:') #plotFuncs(IndShockExample.cFunc[0],IndShockExample.solution[0].mNrmMin,5) #print('Marginal consumption function:') #plotFuncsDer(IndShockExample.cFunc[0],IndShockExample.solution[0].mNrmMin,5)
def setUp(self): """ Prepare to compare the models by initializing and solving them """ # Set up and solve infinite type import ConsumerParameters as Params InfiniteType = IndShockConsumerType(**Params.init_idiosyncratic_shocks) InfiniteType.assignParameters(LivPrb = [1.], DiscFac = 0.955, PermGroFac = [1.], PermShkStd = [0.], TempShkStd = [0.], T_total = 1, T_retire = 0, BoroCnstArt = None, UnempPrb = 0., cycles = 0) # This is what makes the type infinite horizon InfiniteType.updateIncomeProcess() InfiniteType.solve() InfiniteType.timeFwd() InfiniteType.unpackcFunc() # Make and solve a perfect foresight consumer type with the same parameters PerfectForesightType = deepcopy(InfiniteType) PerfectForesightType.solveOnePeriod = solvePerfForesight PerfectForesightType.solve() PerfectForesightType.unpackcFunc() PerfectForesightType.timeFwd() self.InfiniteType = InfiniteType self.PerfectForesightType = PerfectForesightType
sys.path.insert(0, os.path.abspath("../")) # Path to ConsumptionSaving folder sys.path.insert(0, os.path.abspath("../../")) ## Import the HARK ConsumerType we want ## Here, we bring in an agent making a consumption/savings decision every period, subject ## to transitory and permanent income shocks. from ConsIndShockModel import IndShockConsumerType ## Import the default parameter values import ConsumerParameters as Params ## Now, create an instance of the consumer type using the default parameter values ## We create the instance of the consumer type by calling IndShockConsumerType() ## We use the default parameter values by passing **Params.init_idiosyncratic_shocks as an argument BaselineExample = IndShockConsumerType(**Params.init_idiosyncratic_shocks) ## Note: we've created an instance of a very standard consumer type, and many assumptions go ## into making this kind of consumer. As with any structural model, these assumptions matter. ## For example, this consumer pays the same interest rate on ## debt as she earns on savings. If instead we wanted to solve the problem of a consumer ## who pays a higher interest rate on debt than she earns on savings, this would be really easy, ## since this is a model that is also solved in HARK. All we would have to do is import that model ## and instantiate an instance of that ConsumerType instead. As a homework assignment, we leave it ## to you to uncomment the two lines of code below, and see how the results change! # from ConsIndShockModel import KinkedRconsumerType # BaselineExample = KinkedRconsumerType(**Params.init_kinked_R) #################################################################################################### ####################################################################################################
# Make an initialization dictionary on an annual basis base_params = deepcopy(init_infinite) base_params['LivPrb'] = [0.975] base_params['Rfree'] = 1.04 / base_params['LivPrb'][0] base_params['PermShkStd'] = [0.1] base_params['TranShkStd'] = [0.1] base_params[ 'T_age'] = T_kill # Kill off agents if they manage to achieve T_kill working years base_params['AgentCount'] = 10000 base_params['pLvlInitMean'] = np.log( 23.72) # From Table 1, in thousands of USD base_params[ 'T_sim'] = T_kill # No point simulating past when agents would be killed off # Make several consumer types to be used during estimation BaseType = IndShockConsumerType(**base_params) EstTypeList = [] for j in range(TypeCount): EstTypeList.append(deepcopy(BaseType)) EstTypeList[-1](seed=j) # Define the objective function def FagerengObjFunc(center, spread, verbose=False): ''' Objective function for the quick and dirty structural estimation to fit Fagereng, Holm, and Natvik's Table 9 results with a basic infinite horizon consumption-saving model (with permanent and transitory income shocks). Parameters ----------
import os sys.path.insert(0, os.path.abspath('../')) #Path to ConsumptionSaving folder sys.path.insert(0, os.path.abspath('../../')) sys.path.insert(0, os.path.abspath('../../cstwMPC')) #Path to cstwMPC folder # Now, bring in what we need from cstwMPC import cstwMPC import SetupParamsCSTW as cstwParams ## Import the HARK ConsumerType we want ## Here, we bring in an agent making a consumption/savings decision every period, subject ## to transitory and permanent income shocks. from ConsIndShockModel import IndShockConsumerType # Now initialize a baseline consumer type, using default parameters from infinite horizon cstwMPC BaselineType = IndShockConsumerType(**cstwParams.init_infinite) #################################################################################################### #################################################################################################### """ Now, add in ex-ante heterogeneity in consumers' discount factors """ # The cstwMPC parameters do not define a discount factor, since there is ex-ante heterogeneity # in the discount factor. To prepare to create this ex-ante heterogeneity, first create # the desired number of consumer types from copy import deepcopy num_consumer_types = 7 # declare the number of types we want ConsumerTypes = [] # initialize an empty list for nn in range(num_consumer_types):
import os sys.path.insert(0, os.path.abspath('../')) #Path to ConsumptionSaving folder sys.path.insert(0, os.path.abspath('../../')) ## Import the HARK ConsumerType we want ## Here, we bring in an agent making a consumption/savings decision every period, subject ## to transitory and permanent income shocks. from ConsIndShockModel import IndShockConsumerType ## Import the default parameter values import ConsumerParameters as Params ## Now, create an instance of the consumer type using the default parameter values ## We create the instance of the consumer type by calling IndShockConsumerType() ## We use the default parameter values by passing **Params.init_idiosyncratic_shocks as an argument BaselineExample = IndShockConsumerType(**Params.init_idiosyncratic_shocks) ## Note: we've created an instance of a very standard consumer type, and many assumptions go ## into making this kind of consumer. As with any structural model, these assumptions matter. ## For example, this consumer pays the same interest rate on ## debt as she earns on savings. If instead we wanted to solve the problem of a consumer ## who pays a higher interest rate on debt than she earns on savings, this would be really easy, ## since this is a model that is also solved in HARK. All we would have to do is import that model ## and instantiate an instance of that ConsumerType instead. As a homework assignment, we leave it ## to you to uncomment the two lines of code below, and see how the results change! #from ConsIndShockModel import KinkedRconsumerType #BaselineExample = KinkedRconsumerType(**Params.init_kinked_R) ####################################################################################################
def makeNonFarmerHist(stdPerm, stdTran, numAgents, numPeriods): NonFarmerParams = { 'BoroCnstArt': 0.0, 'CRRA': np.inf, 'CubicBool': True, 'DiscFac': 0.5, 'IncUnemp': 0.0, 'IncUnempRet': 0.0, 'LivPrb': [0.98], 'Nagents': 100, 'PermGroFac': [1.01], 'PermShkCount': 20, 'PermShkStd': [stdPerm], 'Rfree': 1.0, 'T_retire': 0, 'T_total': 1, 'TranShkCount': numAgents, 'TranShkStd': [stdTran], 'UnempPrb': 0.0, 'UnempPrbRet': 0.00, 'aXtraCount': 12, 'aXtraExtra': [None], 'aXtraMax': 20, 'aXtraMin': 0.001, 'aXtraNestFac': 3, 'tax_rate': 0.0, 'vFuncBool': False } PerfForNonFarmer = PerfForesightConsumerType(**NonFarmerParams) PerfForNonFarmer.solve() NonFarmer = IndShockConsumerType(**NonFarmerParams) NonFarmer.solution = copy.deepcopy(PerfForNonFarmer.solution) NonFarmer.addToTimeVary('solution') NonFarmer.sim_periods = numPeriods NonFarmer.initializeSim(sim_prds=NonFarmer.sim_periods) NonFarmer.makeIncShkHist() NonFarmer.simConsHistory() NonFarmer.IncHist = np.multiply(NonFarmer.PermShkHist, NonFarmer.TranShkHist) NonFarmer.IncHist = np.reshape( NonFarmer.IncHist, (NonFarmer.Nagents * NonFarmer.sim_periods, 1)) NonFarmer.cHist = np.reshape( NonFarmer.cHist, (NonFarmer.Nagents * NonFarmer.sim_periods, 1)) NonFarmer.IncHist = list(itertools.chain.from_iterable(NonFarmer.IncHist)) NonFarmer.cHist = list(itertools.chain.from_iterable(NonFarmer.cHist)) return (NonFarmer.IncHist, NonFarmer.cHist)
for the queue to clear. ''' queue.finish() if __name__ == '__main__': import ConsumerParameters as Params from ConsIndShockModel import IndShockConsumerType import matplotlib.pyplot as plt from copy import deepcopy from time import clock from HARK.parallel import multiThreadCommands, multiThreadCommandsFake # Set up a baseline IndShockConsumerType, which will be replicated. # In this case, we use a completely arbitrary 10 period lifecycle. TestType = IndShockConsumerType(**Params.init_lifecycle) TestType.TestVar = np.empty( TestType.AgentCount ) # This is for making an empty buffer for diagnostics TestType.CubicBool = True # Cubic interpolation must be on, because that's what's used in OpenCL version T_sim = 10 # Choose simulation length AgentCount = 100 # Chose number of agents in each type TestType.T_sim = T_sim # Choose number of periods to simulate TestType.AgentCount = AgentCount TestType.initializeSim() # Set up some objects for simulation # Make a list with many copies of the baseline agent type, each with a different CRRA. TypeCount = 100 CRRAmin = 1.0 CRRAmax = 5.0 CRRAset = np.linspace(CRRAmin, CRRAmax, TypeCount)
import os sys.path.insert(0, os.path.abspath('../')) #Path to ConsumptionSaving folder sys.path.insert(0, os.path.abspath('../../')) sys.path.insert(0, os.path.abspath('../../cstwMPC')) #Path to cstwMPC folder # Now, bring in what we need from the cstwMPC parameters import SetupParamsCSTWnew as cstwParams from HARKutilities import approxUniform ## Import the HARK ConsumerType we want ## Here, we bring in an agent making a consumption/savings decision every period, subject ## to transitory and permanent income shocks. from ConsIndShockModel import IndShockConsumerType # Now initialize a baseline consumer type, using default parameters from infinite horizon cstwMPC BaselineType = IndShockConsumerType(**cstwParams.init_infinite) BaselineType.AgentCount = 10000 # Assign the baseline consumer type to have many agents in simulation #################################################################################################### #################################################################################################### """ Now, add in ex-ante heterogeneity in consumers' discount factors """ # The cstwMPC parameters do not define a discount factor, since there is ex-ante heterogeneity # in the discount factor. To prepare to create this ex-ante heterogeneity, first create # the desired number of consumer types from copy import deepcopy num_consumer_types = 7 # declare the number of types we want ConsumerTypes = [] # initialize an empty list
# Remove TimeBefore periods cAggImpulseResponse = cAggImpulseResponse[TimeBefore:] return cAggImpulseResponse ############################################################################### if __name__ == '__main__': import ConsumerParameters as Params from time import clock mystr = lambda number: "{:.4f}".format(number) # Make and solve an example consumer with idiosyncratic income shocks IndShockExample = IndShockConsumerType(**Params.init_idiosyncratic_shocks) IndShockExample.cycles = 0 # Make this type have an infinite horizon IndShockExample.DiePrb = 1 - IndShockExample.LivPrb[ 0] # Not sure why this is not already in the object start_time = clock() IndShockExample.solve() end_time = clock() print('Solving a consumer with idiosyncratic shocks took ' + mystr(end_time - start_time) + ' seconds.') IndShockExample.unpackcFunc() IndShockExample.timeFwd() PermShk = 1.1 TranShk = 1 cPermImpulseResponse = AggCons_impulseResponseInd(IndShockExample, PermShk,
class Compare_PerfectForesight_and_Infinite(unittest.TestCase): def setUp(self): # Set up and solve infinite type <<<<<<< HEAD import SetupConsumerParameters as Params InfiniteType = ConsumerType(**Params.init_consumer_objects) InfiniteType.solveOnePeriod = consumptionSavingSolverENDG InfiniteType.assignParameters(LivPrb = [1.], DiscFac = [0.955], ======= import ConsumerParameters as Params InfiniteType = IndShockConsumerType(**Params.init_idiosyncratic_shocks) InfiniteType.assignParameters(LivPrb = [1.], DiscFac = 0.955, >>>>>>> eeb37f24755d0c683c9d9efbe5e7447425c98b86 PermGroFac = [1.], PermShkStd = [0.], TempShkStd = [0.], T_total = 1, T_retire = 0, BoroCnstArt = None, UnempPrb = 0., cycles = 0) # This is what makes the type infinite horizon InfiniteType.updateIncomeProcess() InfiniteType.solve() InfiniteType.timeFwd() <<<<<<< HEAD InfiniteType.unpack_cFunc() =======
def setUp(self): # Set up and solve infinite type import ConsumerParameters as Params InfiniteType = IndShockConsumerType(**Params.init_idiosyncratic_shocks) InfiniteType.assignParameters( LivPrb=[1.], DiscFac=0.955, PermGroFac=[1.], PermShkStd=[0.], TempShkStd=[0.], T_total=1, T_retire=0, BoroCnstArt=None, UnempPrb=0., cycles=0) # This is what makes the type infinite horizon InfiniteType.updateIncomeProcess() InfiniteType.solve() InfiniteType.timeFwd() InfiniteType.unpackcFunc() # Make and solve a perfect foresight consumer type PerfectForesightType = deepcopy(InfiniteType) PerfectForesightType.solveOnePeriod = solvePerfForesight PerfectForesightType.solve() PerfectForesightType.unpackcFunc() PerfectForesightType.timeFwd() self.InfiniteType = InfiniteType self.PerfectForesightType = PerfectForesightType
def __init__(self,cycles=1,time_flow=True,**kwds): IndShockConsumerType.__init__(self,cycles=1,time_flow=True,**kwds) self.solveOnePeriod = solveConsMarkov