code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
''' Slightly extends the base version of this method by recalculating aLvlNow to account for the consumer's (potential) misperception about their productivity level. Parameters ---------- None Returns ------- None ''' RepAgentConsumerType.getPostStates(self) self.aLvlNow = self.mLvlTrue - self.cLvlNow # This is true self.aNrmNow = self.aLvlNow/self.pLvlTrue
def getPostStates(self)
Slightly extends the base version of this method by recalculating aLvlNow to account for the consumer's (potential) misperception about their productivity level. Parameters ---------- None Returns ------- None
14.187102
3.42709
4.139694
''' Finds the representative agent's (average) perceived productivity level. Average perception of productivity gets UpdatePrb weight on the true level, for those that update, and (1-UpdatePrb) weight on the previous average perception times expected aggregate growth, for those that don't update. Parameters ---------- None Returns ------- pLvlPcvd : np.array Size 1 array with average perception of productivity level. ''' pLvlPcvd = self.UpdatePrb*self.pLvlTrue + (1.0-self.UpdatePrb)*(self.pLvlNow*self.PermGroFac[self.t_cycle[0]-1]) return pLvlPcvd
def getpLvlPcvd(self)
Finds the representative agent's (average) perceived productivity level. Average perception of productivity gets UpdatePrb weight on the true level, for those that update, and (1-UpdatePrb) weight on the previous average perception times expected aggregate growth, for those that don't update. Parameters ---------- None Returns ------- pLvlPcvd : np.array Size 1 array with average perception of productivity level.
9.208049
1.852534
4.970516
''' Makes new consumers for the given indices. Slightly extends base method by also setting pLvlTrue = 1.0 in the very first simulated period, as well as initializing the perception of aggregate productivity for each Markov state. The representative agent begins with the correct perception of the Markov state. Parameters ---------- which_agents : np.array(Bool) Boolean array of size self.AgentCount indicating which agents should be "born". Returns ------- None ''' if which_agents==np.array([True]): RepAgentMarkovConsumerType.simBirth(self,which_agents) if self.t_sim == 0: # Initialize perception distribution for Markov state self.pLvlTrue = np.ones(self.AgentCount) self.aLvlNow = self.aNrmNow*self.pLvlTrue StateCount = self.MrkvArray.shape[0] self.pLvlNow = np.ones(StateCount) # Perceived productivity level by Markov state self.MrkvPcvd = np.zeros(StateCount) # Distribution of perceived Markov state self.MrkvPcvd[self.MrkvNow[0]] = 1.0
def simBirth(self,which_agents)
Makes new consumers for the given indices. Slightly extends base method by also setting pLvlTrue = 1.0 in the very first simulated period, as well as initializing the perception of aggregate productivity for each Markov state. The representative agent begins with the correct perception of the Markov state. Parameters ---------- which_agents : np.array(Bool) Boolean array of size self.AgentCount indicating which agents should be "born". Returns ------- None
7.464926
2.664964
2.801136
''' Finds the representative agent's (average) perceived productivity level for each Markov state, as well as the distribution of the representative agent's perception of the Markov state. Parameters ---------- None Returns ------- pLvlPcvd : np.array Array with average perception of productivity level by Markov state. ''' StateCount = self.MrkvArray.shape[0] t = self.t_cycle[0] i = self.MrkvNow[0] dont_mass = self.MrkvPcvd*(1.-self.UpdatePrb) # pmf of non-updaters update_mass = np.zeros(StateCount) update_mass[i] = self.UpdatePrb # pmf of updaters dont_pLvlPcvd = self.pLvlNow*self.PermGroFac[t-1] # those that don't update think pLvl grows at PermGroFac for last observed state update_pLvlPcvd = np.zeros(StateCount) update_pLvlPcvd[i] = self.pLvlTrue # those that update see the true pLvl # Combine updaters and non-updaters to get average pLvl perception by Markov state self.MrkvPcvd = dont_mass + update_mass # Total mass of agent in each state pLvlPcvd = (dont_mass*dont_pLvlPcvd + update_mass*update_pLvlPcvd)/self.MrkvPcvd pLvlPcvd[self.MrkvPcvd==0.] = 1.0 # Fix division by zero problem when MrkvPcvd[i]=0 return pLvlPcvd
def getpLvlPcvd(self)
Finds the representative agent's (average) perceived productivity level for each Markov state, as well as the distribution of the representative agent's perception of the Markov state. Parameters ---------- None Returns ------- pLvlPcvd : np.array Array with average perception of productivity level by Markov state.
5.079797
3.573633
1.421466
''' Calculates consumption for the representative agent using the consumption functions. Takes the weighted average of cLvl across perceived Markov states. Parameters ---------- None Returns ------- None ''' StateCount = self.MrkvArray.shape[0] t = self.t_cycle[0] cNrmNow = np.zeros(StateCount) # Array of chosen cNrm by Markov state for i in range(StateCount): cNrmNow[i] = self.solution[t].cFunc[i](self.mNrmNow[i]) self.cNrmNow = cNrmNow self.cLvlNow = np.dot(cNrmNow*self.pLvlNow,self.MrkvPcvd)
def getControls(self)
Calculates consumption for the representative agent using the consumption functions. Takes the weighted average of cLvl across perceived Markov states. Parameters ---------- None Returns ------- None
7.878986
3.57502
2.2039
''' Function to calculate the capital to labor ratio, interest factor, and wage rate based on each agent's current state. Just calls calcRandW() and adds the Markov state index. See documentation for calcRandW for more information. ''' MrkvNow = self.MrkvNow_hist[self.Shk_idx] temp = self.calcRandW(aLvlNow,pLvlTrue) temp(MrkvNow = MrkvNow) # Overwrite MaggNow, wRteNow, and RfreeNow if requested if self.overwrite_hist: t = self.Shk_idx-1 temp(MaggNow = self.MaggNow_overwrite[t]) temp(wRteNow = self.wRteNow_overwrite[t]) temp(RfreeNow = self.RfreeNow_overwrite[t]) return temp
def millRule(self,aLvlNow,pLvlTrue)
Function to calculate the capital to labor ratio, interest factor, and wage rate based on each agent's current state. Just calls calcRandW() and adds the Markov state index. See documentation for calcRandW for more information.
7.643661
3.343161
2.286357
''' Executes the list of commands in command_list for each AgentType in agent_list in an ordinary, single-threaded loop. Each command should be a method of that AgentType subclass. This function exists so as to easily disable multithreading, as it uses the same syntax as multithreadCommands. Parameters ---------- agent_list : [AgentType] A list of instances of AgentType on which the commands will be run. command_list : [string] A list of commands to run for each AgentType. num_jobs : None Dummy input to match syntax of multiThreadCommands. Does nothing. Returns ------- none ''' for agent in agent_list: for command in command_list: exec('agent.' + command)
def multiThreadCommandsFake(agent_list,command_list,num_jobs=None)
Executes the list of commands in command_list for each AgentType in agent_list in an ordinary, single-threaded loop. Each command should be a method of that AgentType subclass. This function exists so as to easily disable multithreading, as it uses the same syntax as multithreadCommands. Parameters ---------- agent_list : [AgentType] A list of instances of AgentType on which the commands will be run. command_list : [string] A list of commands to run for each AgentType. num_jobs : None Dummy input to match syntax of multiThreadCommands. Does nothing. Returns ------- none
5.354573
1.313635
4.07615
''' Executes the list of commands in command_list for each AgentType in agent_list using a multithreaded system. Each command should be a method of that AgentType subclass. Parameters ---------- agent_list : [AgentType] A list of instances of AgentType on which the commands will be run. command_list : [string] A list of commands to run for each AgentType in agent_list. Returns ------- None ''' if len(agent_list) == 1: multiThreadCommandsFake(agent_list,command_list) return None # Default umber of parallel jobs is the smaller of number of AgentTypes in # the input and the number of available cores. if num_jobs is None: num_jobs = min(len(agent_list),multiprocessing.cpu_count()) # Send each command in command_list to each of the types in agent_list to be run agent_list_out = Parallel(n_jobs=num_jobs)(delayed(runCommands)(*args) for args in zip(agent_list, len(agent_list)*[command_list])) # Replace the original types with the output from the parallel call for j in range(len(agent_list)): agent_list[j] = agent_list_out[j]
def multiThreadCommands(agent_list,command_list,num_jobs=None)
Executes the list of commands in command_list for each AgentType in agent_list using a multithreaded system. Each command should be a method of that AgentType subclass. Parameters ---------- agent_list : [AgentType] A list of instances of AgentType on which the commands will be run. command_list : [string] A list of commands to run for each AgentType in agent_list. Returns ------- None
3.463756
2.392358
1.447842
''' Stores the progress of a parallel Nelder-Mead search in a text file so that it can be resumed later (after manual termination or a crash). Parameters ---------- name : string Name of the txt file in which to store search progress. simplex : np.array The current state of the simplex of parameter guesses. fvals : np.array The objective function value at each row of simplex. iters : int The number of completed Nelder-Mead iterations. evals : int The cumulative number of function evaluations in the search process. Returns ------- none ''' f = open(name + '.txt','w') my_writer = csv.writer(f,delimiter=' ') my_writer.writerow(simplex.shape) my_writer.writerow([iters, evals]) my_writer.writerow(simplex.flatten()) my_writer.writerow(fvals) f.close()
def saveNelderMeadData(name, simplex, fvals, iters, evals)
Stores the progress of a parallel Nelder-Mead search in a text file so that it can be resumed later (after manual termination or a crash). Parameters ---------- name : string Name of the txt file in which to store search progress. simplex : np.array The current state of the simplex of parameter guesses. fvals : np.array The objective function value at each row of simplex. iters : int The number of completed Nelder-Mead iterations. evals : int The cumulative number of function evaluations in the search process. Returns ------- none
3.2934
1.521959
2.163922
''' Reads the progress of a parallel Nelder-Mead search from a text file, as created by saveNelderMeadData(). Parameters ---------- name : string Name of the txt file from which to read search progress. Returns ------- simplex : np.array The current state of the simplex of parameter guesses. fvals : np.array The objective function value at each row of simplex. iters : int The number of completed Nelder-Mead iterations. evals : int The cumulative number of function evaluations in the search process. ''' f = open(name + '.txt','rb') my_reader = csv.reader(f,delimiter=' ') my_shape_txt = next(my_reader) shape0 = int(my_shape_txt[0]) shape1 = int(my_shape_txt[1]) my_nums_txt = next(my_reader) iters = int(my_nums_txt[0]) evals = int(my_nums_txt[1]) simplex_flat = np.array(next(my_reader),dtype=float) simplex = np.reshape(simplex_flat,(shape0,shape1)) fvals = np.array(next(my_reader),dtype=float) f.close() return simplex, fvals, iters, evals
def loadNelderMeadData(name)
Reads the progress of a parallel Nelder-Mead search from a text file, as created by saveNelderMeadData(). Parameters ---------- name : string Name of the txt file from which to read search progress. Returns ------- simplex : np.array The current state of the simplex of parameter guesses. fvals : np.array The objective function value at each row of simplex. iters : int The number of completed Nelder-Mead iterations. evals : int The cumulative number of function evaluations in the search process.
2.816689
1.600793
1.759559
''' Minimizes the objective function using the Nelder-Mead simplex algorithm, starting from an initial parameter guess. Parameters ---------- objectiveFunction : function The function to be minimized. It should take only a single argument, which should be a list representing the parameters to be estimated. parameter_guess : [float] A starting point for the Nelder-Mead algorithm, which must be a valid input for objectiveFunction. verbose : boolean A flag for the amount of output to print. Returns ------- xopt : [float] The values that minimize objectiveFunction. ''' # Execute the minimization, starting from the given parameter guess t0 = time() # Time the process OUTPUT = fmin(objectiveFunction, parameter_guess, full_output=1, maxiter=1000, disp=verbose, **kwargs) t1 = time() # Extract values from optimization output: xopt = OUTPUT[0] # Parameters that minimize function. fopt = OUTPUT[1] # Value of function at minimum: ``fopt = func(xopt)``. optiter = OUTPUT[2] # Number of iterations performed. funcalls = OUTPUT[3] # Number of function calls made. warnflag = OUTPUT[4] # warnflag : int # 1 : Maximum number of function evaluations made. # 2 : Maximum number of iterations reached. # Check that optimization succeeded: if warnflag != 0: warnings.warn("Minimization failed! xopt=" + str(xopt) + ', fopt=' + str(fopt) + ', optiter=' + str(optiter) +', funcalls=' + str(funcalls) + ', warnflag=' + str(warnflag)) # Display and return the results: if verbose: print("Time to estimate is " + str(t1-t0) + " seconds.") return xopt
def minimizeNelderMead(objectiveFunction, parameter_guess, verbose=False, **kwargs)
Minimizes the objective function using the Nelder-Mead simplex algorithm, starting from an initial parameter guess. Parameters ---------- objectiveFunction : function The function to be minimized. It should take only a single argument, which should be a list representing the parameters to be estimated. parameter_guess : [float] A starting point for the Nelder-Mead algorithm, which must be a valid input for objectiveFunction. verbose : boolean A flag for the amount of output to print. Returns ------- xopt : [float] The values that minimize objectiveFunction.
3.125792
2.291865
1.363864
''' Minimizes the objective function using a derivative-free Powell algorithm, starting from an initial parameter guess. Parameters ---------- objectiveFunction : function The function to be minimized. It should take only a single argument, which should be a list representing the parameters to be estimated. parameter_guess : [float] A starting point for the Powell algorithm, which must be a valid input for objectiveFunction. verbose : boolean A flag for the amount of output to print. Returns ------- xopt : [float] The values that minimize objectiveFunction. ''' # Execute the minimization, starting from the given parameter guess t0 = time() # Time the process OUTPUT = fmin_powell(objectiveFunction, parameter_guess, full_output=1, maxiter=1000, disp=verbose) t1 = time() # Extract values from optimization output: xopt = OUTPUT[0] # Parameters that minimize function. fopt = OUTPUT[1] # Value of function at minimum: ``fopt = func(xopt)``. direc = OUTPUT[2] optiter = OUTPUT[3] # Number of iterations performed. funcalls = OUTPUT[4] # Number of function calls made. warnflag = OUTPUT[5] # warnflag : int # 1 : Maximum number of function evaluations made. # 2 : Maximum number of iterations reached. # Check that optimization succeeded: if warnflag != 0: warnings.warn("Minimization failed! xopt=" + str(xopt) + ', fopt=' + str(fopt) + ', direc=' + str(direc) + ', optiter=' + str(optiter) +', funcalls=' + str(funcalls) +', warnflag=' + str(warnflag)) # Display and return the results: if verbose: print("Time to estimate is " + str(t1-t0) + " seconds.") return xopt
def minimizePowell(objectiveFunction, parameter_guess, verbose=False)
Minimizes the objective function using a derivative-free Powell algorithm, starting from an initial parameter guess. Parameters ---------- objectiveFunction : function The function to be minimized. It should take only a single argument, which should be a list representing the parameters to be estimated. parameter_guess : [float] A starting point for the Powell algorithm, which must be a valid input for objectiveFunction. verbose : boolean A flag for the amount of output to print. Returns ------- xopt : [float] The values that minimize objectiveFunction.
3.225044
2.335406
1.380935
''' Samples rows from the input array of data, generating a new data array with an equal number of rows (records). Rows are drawn with equal probability by default, but probabilities can be specified with weights (must sum to 1). Parameters ---------- data : np.array An array of data, with each row representing a record. weights : np.array A weighting array with length equal to data.shape[0]. seed : int A seed for the random number generator. Returns ------- new_data : np.array A resampled version of input data. ''' # Set up the random number generator RNG = np.random.RandomState(seed) N = data.shape[0] # Set up weights if weights is not None: cutoffs = np.cumsum(weights) else: cutoffs = np.linspace(0,1,N) # Draw random indices indices = np.searchsorted(cutoffs,RNG.uniform(size=N)) # Create a bootstrapped sample new_data = deepcopy(data[indices,]) return new_data
def bootstrapSampleFromData(data,weights=None,seed=0)
Samples rows from the input array of data, generating a new data array with an equal number of rows (records). Rows are drawn with equal probability by default, but probabilities can be specified with weights (must sum to 1). Parameters ---------- data : np.array An array of data, with each row representing a record. weights : np.array A weighting array with length equal to data.shape[0]. seed : int A seed for the random number generator. Returns ------- new_data : np.array A resampled version of input data.
3.293011
1.813921
1.81541
''' Calculates what consumption, market resources, and the marginal propensity to consume must have been in the previous period given model parameters and values of market resources, consumption, and MPC today. Parameters ---------- DiscFac : float Intertemporal discount factor on future utility. Rfree : float Risk free interest factor on end-of-period assets. PermGroFacCmp : float Permanent income growth factor, compensated for the possibility of permanent unemployment. UnempPrb : float Probability of becoming permanently unemployed. Rnrm : float Interest factor normalized by compensated permanent income growth factor. Beth : float Composite effective discount factor for reverse shooting solution; defined in appendix "Numerical Solution/The Consumption Function" in TBS lecture notes cNext : float Normalized consumption in the succeeding period. mNext : float Normalized market resources in the succeeding period. MPCnext : float The marginal propensity to consume in the succeeding period. PFMPC : float The perfect foresight MPC; also the MPC when permanently unemployed. Returns ------- mNow : float Normalized market resources this period. cNow : float Normalized consumption this period. MPCnow : float Marginal propensity to consume this period. ''' uPP = lambda x : utilityPP(x,gam=CRRA) cNow = PermGroFacCmp*(DiscFac*Rfree)**(-1.0/CRRA)*cNext*(1 + UnempPrb*((cNext/(PFMPC*(mNext-1.0)))**CRRA-1.0))**(-1.0/CRRA) mNow = (PermGroFacCmp/Rfree)*(mNext - 1.0) + cNow cUNext = PFMPC*(mNow-cNow)*Rnrm # See TBS Appendix "E.1 The Consumption Function" natural = Beth*Rnrm*(1.0/uPP(cNow))*((1.0-UnempPrb)*uPP(cNext)*MPCnext + UnempPrb*uPP(cUNext)*PFMPC) # Convenience variable MPCnow = natural / (natural + 1) return mNow, cNow, MPCnow
def findNextPoint(DiscFac,Rfree,CRRA,PermGroFacCmp,UnempPrb,Rnrm,Beth,cNext,mNext,MPCnext,PFMPC)
Calculates what consumption, market resources, and the marginal propensity to consume must have been in the previous period given model parameters and values of market resources, consumption, and MPC today. Parameters ---------- DiscFac : float Intertemporal discount factor on future utility. Rfree : float Risk free interest factor on end-of-period assets. PermGroFacCmp : float Permanent income growth factor, compensated for the possibility of permanent unemployment. UnempPrb : float Probability of becoming permanently unemployed. Rnrm : float Interest factor normalized by compensated permanent income growth factor. Beth : float Composite effective discount factor for reverse shooting solution; defined in appendix "Numerical Solution/The Consumption Function" in TBS lecture notes cNext : float Normalized consumption in the succeeding period. mNext : float Normalized market resources in the succeeding period. MPCnext : float The marginal propensity to consume in the succeeding period. PFMPC : float The perfect foresight MPC; also the MPC when permanently unemployed. Returns ------- mNow : float Normalized market resources this period. cNow : float Normalized consumption this period. MPCnow : float Marginal propensity to consume this period.
5.282934
2.193279
2.408692
''' This method adds consumption at m=0 to the list of stable arm points, then constructs the consumption function as a cubic interpolation over those points. Should be run after the backshooting routine is complete. Parameters ---------- none Returns ------- none ''' # Add bottom point to the stable arm points self.solution[0].mNrm_list.insert(0,0.0) self.solution[0].cNrm_list.insert(0,0.0) self.solution[0].MPC_list.insert(0,self.MPCmax) # Construct an interpolation of the consumption function from the stable arm points self.solution[0].cFunc = CubicInterp(self.solution[0].mNrm_list,self.solution[0].cNrm_list,self.solution[0].MPC_list,self.PFMPC*(self.h-1.0),self.PFMPC) self.solution[0].cFunc_U = lambda m : self.PFMPC*m
def postSolve(self)
This method adds consumption at m=0 to the list of stable arm points, then constructs the consumption function as a cubic interpolation over those points. Should be run after the backshooting routine is complete. Parameters ---------- none Returns ------- none
5.806431
2.77635
2.09139
''' Makes new consumers for the given indices. Initialized variables include aNrm, as well as time variables t_age and t_cycle. Normalized assets are drawn from a lognormal distributions given by aLvlInitMean and aLvlInitStd. Parameters ---------- which_agents : np.array(Bool) Boolean array of size self.AgentCount indicating which agents should be "born". Returns ------- None ''' # Get and store states for newly born agents N = np.sum(which_agents) # Number of new consumers to make self.aLvlNow[which_agents] = drawLognormal(N,mu=self.aLvlInitMean,sigma=self.aLvlInitStd,seed=self.RNG.randint(0,2**31-1)) self.eStateNow[which_agents] = 1.0 # Agents are born employed self.t_age[which_agents] = 0 # How many periods since each agent was born self.t_cycle[which_agents] = 0 # Which period of the cycle each agent is currently in return None
def simBirth(self,which_agents)
Makes new consumers for the given indices. Initialized variables include aNrm, as well as time variables t_age and t_cycle. Normalized assets are drawn from a lognormal distributions given by aLvlInitMean and aLvlInitStd. Parameters ---------- which_agents : np.array(Bool) Boolean array of size self.AgentCount indicating which agents should be "born". Returns ------- None
5.694027
2.422893
2.350094
''' Trivial function that returns boolean array of all False, as there is no death. Parameters ---------- None Returns ------- which_agents : np.array(bool) Boolean array of size AgentCount indicating which agents die. ''' # Nobody dies in this model which_agents = np.zeros(self.AgentCount,dtype=bool) return which_agents
def simDeath(self)
Trivial function that returns boolean array of all False, as there is no death. Parameters ---------- None Returns ------- which_agents : np.array(bool) Boolean array of size AgentCount indicating which agents die.
7.303961
2.084615
3.503747
''' Determine which agents switch from employment to unemployment. All unemployed agents remain unemployed until death. Parameters ---------- None Returns ------- None ''' employed = self.eStateNow == 1.0 N = int(np.sum(employed)) newly_unemployed = drawBernoulli(N,p=self.UnempPrb,seed=self.RNG.randint(0,2**31-1)) self.eStateNow[employed] = 1.0 - newly_unemployed
def getShocks(self)
Determine which agents switch from employment to unemployment. All unemployed agents remain unemployed until death. Parameters ---------- None Returns ------- None
6.201181
3.4244
1.810881
''' Calculate market resources for all agents this period. Parameters ---------- None Returns ------- None ''' self.bLvlNow = self.Rfree*self.aLvlNow self.mLvlNow = self.bLvlNow + self.eStateNow
def getStates(self)
Calculate market resources for all agents this period. Parameters ---------- None Returns ------- None
10.117438
4.911678
2.059874
''' Calculate consumption for each agent this period. Parameters ---------- None Returns ------- None ''' employed = self.eStateNow == 1.0 unemployed = np.logical_not(employed) cLvlNow = np.zeros(self.AgentCount) cLvlNow[employed] = self.solution[0].cFunc(self.mLvlNow[employed]) cLvlNow[unemployed] = self.solution[0].cFunc_U(self.mLvlNow[unemployed]) self.cLvlNow = cLvlNow
def getControls(self)
Calculate consumption for each agent this period. Parameters ---------- None Returns ------- None
4.036493
2.827651
1.427508
''' Evaluate the derivative of consumption and medical care with respect to market resources at given levels of market resources, permanent income, and medical need shocks. Parameters ---------- mLvl : np.array Market resource levels. pLvl : np.array Permanent income levels; should be same size as mLvl. MedShk : np.array Medical need shocks; should be same size as mLvl. Returns ------- dcdm : np.array Derivative of consumption with respect to market resources for each point in (xLvl,MedShk). dMeddm : np.array Derivative of medical care with respect to market resources for each point in (xLvl,MedShk). ''' xLvl = self.xFunc(mLvl,pLvl,MedShk) dxdm = self.xFunc.derivativeX(mLvl,pLvl,MedShk) dcdx = self.cFunc.derivativeX(xLvl,MedShk) dcdm = dxdm*dcdx dMeddm = (dxdm - dcdm)/self.MedPrice return dcdm,dMeddm
def derivativeX(self,mLvl,pLvl,MedShk)
Evaluate the derivative of consumption and medical care with respect to market resources at given levels of market resources, permanent income, and medical need shocks. Parameters ---------- mLvl : np.array Market resource levels. pLvl : np.array Permanent income levels; should be same size as mLvl. MedShk : np.array Medical need shocks; should be same size as mLvl. Returns ------- dcdm : np.array Derivative of consumption with respect to market resources for each point in (xLvl,MedShk). dMeddm : np.array Derivative of medical care with respect to market resources for each point in (xLvl,MedShk).
2.4914
1.460056
1.706373
''' Evaluate the derivative of consumption and medical care with respect to permanent income at given levels of market resources, permanent income, and medical need shocks. Parameters ---------- mLvl : np.array Market resource levels. pLvl : np.array Permanent income levels; should be same size as mLvl. MedShk : np.array Medical need shocks; should be same size as mLvl. Returns ------- dcdp : np.array Derivative of consumption with respect to permanent income for each point in (xLvl,MedShk). dMeddp : np.array Derivative of medical care with respect to permanent income for each point in (xLvl,MedShk). ''' xLvl = self.xFunc(mLvl,pLvl,MedShk) dxdp = self.xFunc.derivativeY(mLvl,pLvl,MedShk) dcdx = self.cFunc.derivativeX(xLvl,MedShk) dcdp = dxdp*dcdx dMeddp = (dxdp - dcdp)/self.MedPrice return dcdp,dMeddp
def derivativeY(self,mLvl,pLvl,MedShk)
Evaluate the derivative of consumption and medical care with respect to permanent income at given levels of market resources, permanent income, and medical need shocks. Parameters ---------- mLvl : np.array Market resource levels. pLvl : np.array Permanent income levels; should be same size as mLvl. MedShk : np.array Medical need shocks; should be same size as mLvl. Returns ------- dcdp : np.array Derivative of consumption with respect to permanent income for each point in (xLvl,MedShk). dMeddp : np.array Derivative of medical care with respect to permanent income for each point in (xLvl,MedShk).
2.525996
1.474414
1.71322
''' Evaluate the derivative of consumption and medical care with respect to medical need shock at given levels of market resources, permanent income, and medical need shocks. Parameters ---------- mLvl : np.array Market resource levels. pLvl : np.array Permanent income levels; should be same size as mLvl. MedShk : np.array Medical need shocks; should be same size as mLvl. Returns ------- dcdShk : np.array Derivative of consumption with respect to medical need for each point in (xLvl,MedShk). dMeddShk : np.array Derivative of medical care with respect to medical need for each point in (xLvl,MedShk). ''' xLvl = self.xFunc(mLvl,pLvl,MedShk) dxdShk = self.xFunc.derivativeZ(mLvl,pLvl,MedShk) dcdx = self.cFunc.derivativeX(xLvl,MedShk) dcdShk = dxdShk*dcdx + self.cFunc.derivativeY(xLvl,MedShk) dMeddShk = (dxdShk - dcdShk)/self.MedPrice return dcdShk,dMeddShk
def derivativeZ(self,mLvl,pLvl,MedShk)
Evaluate the derivative of consumption and medical care with respect to medical need shock at given levels of market resources, permanent income, and medical need shocks. Parameters ---------- mLvl : np.array Market resource levels. pLvl : np.array Permanent income levels; should be same size as mLvl. MedShk : np.array Medical need shocks; should be same size as mLvl. Returns ------- dcdShk : np.array Derivative of consumption with respect to medical need for each point in (xLvl,MedShk). dMeddShk : np.array Derivative of medical care with respect to medical need for each point in (xLvl,MedShk).
2.535303
1.489784
1.701792
''' Update the income process, the assets grid, the permanent income grid, the medical shock distribution, and the terminal solution. Parameters ---------- none Returns ------- none ''' self.updateIncomeProcess() self.updateAssetsGrid() self.updatepLvlNextFunc() self.updatepLvlGrid() self.updateMedShockProcess() self.updateSolutionTerminal()
def update(self)
Update the income process, the assets grid, the permanent income grid, the medical shock distribution, and the terminal solution. Parameters ---------- none Returns ------- none
9.686079
2.655675
3.647314
''' Constructs discrete distributions of medical preference shocks for each period in the cycle. Distributions are saved as attribute MedShkDstn, which is added to time_vary. Parameters ---------- None Returns ------- None ''' MedShkDstn = [] # empty list for medical shock distribution each period for t in range(self.T_cycle): MedShkAvgNow = self.MedShkAvg[t] # get shock distribution parameters MedShkStdNow = self.MedShkStd[t] MedShkDstnNow = approxLognormal(mu=np.log(MedShkAvgNow)-0.5*MedShkStdNow**2,\ sigma=MedShkStdNow,N=self.MedShkCount, tail_N=self.MedShkCountTail, tail_bound=[0,0.9]) MedShkDstnNow = addDiscreteOutcomeConstantMean(MedShkDstnNow,0.0,0.0,sort=True) # add point at zero with no probability MedShkDstn.append(MedShkDstnNow) self.MedShkDstn = MedShkDstn self.addToTimeVary('MedShkDstn')
def updateMedShockProcess(self)
Constructs discrete distributions of medical preference shocks for each period in the cycle. Distributions are saved as attribute MedShkDstn, which is added to time_vary. Parameters ---------- None Returns ------- None
4.770729
3.138014
1.520302
''' Update the grid of permanent income levels. Currently only works for infinite horizon models (cycles=0) and lifecycle models (cycles=1). Not clear what to do about cycles>1. Identical to version in persistent shocks model, but pLvl=0 is manually added to the grid (because there is no closed form lower-bounding cFunc for pLvl=0). Parameters ---------- None Returns ------- None ''' # Run basic version of this method PersistentShockConsumerType.updatepLvlGrid(self) for j in range(len(self.pLvlGrid)): # Then add 0 to the bottom of each pLvlGrid this_grid = self.pLvlGrid[j] self.pLvlGrid[j] = np.insert(this_grid,0,0.0001)
def updatepLvlGrid(self)
Update the grid of permanent income levels. Currently only works for infinite horizon models (cycles=0) and lifecycle models (cycles=1). Not clear what to do about cycles>1. Identical to version in persistent shocks model, but pLvl=0 is manually added to the grid (because there is no closed form lower-bounding cFunc for pLvl=0). Parameters ---------- None Returns ------- None
7.202684
2.037005
3.535918
''' Gets permanent and transitory income shocks for this period as well as medical need shocks and the price of medical care. Parameters ---------- None Returns ------- None ''' PersistentShockConsumerType.getShocks(self) # Get permanent and transitory income shocks MedShkNow = np.zeros(self.AgentCount) # Initialize medical shock array MedPriceNow = np.zeros(self.AgentCount) # Initialize relative price array for t in range(self.T_cycle): these = t == self.t_cycle N = np.sum(these) if N > 0: MedShkAvg = self.MedShkAvg[t] MedShkStd = self.MedShkStd[t] MedPrice = self.MedPrice[t] MedShkNow[these] = self.RNG.permutation(approxLognormal(N,mu=np.log(MedShkAvg)-0.5*MedShkStd**2,sigma=MedShkStd)[1]) MedPriceNow[these] = MedPrice self.MedShkNow = MedShkNow self.MedPriceNow = MedPriceNow
def getShocks(self)
Gets permanent and transitory income shocks for this period as well as medical need shocks and the price of medical care. Parameters ---------- None Returns ------- None
3.475124
2.722493
1.276449
''' Calculates consumption and medical care for each consumer of this type using the consumption and medical care functions. Parameters ---------- None Returns ------- None ''' cLvlNow = np.zeros(self.AgentCount) + np.nan MedNow = np.zeros(self.AgentCount) + np.nan for t in range(self.T_cycle): these = t == self.t_cycle cLvlNow[these], MedNow[these] = self.solution[t].policyFunc(self.mLvlNow[these],self.pLvlNow[these],self.MedShkNow[these]) self.cLvlNow = cLvlNow self.MedNow = MedNow return None
def getControls(self)
Calculates consumption and medical care for each consumer of this type using the consumption and medical care functions. Parameters ---------- None Returns ------- None
4.914814
3.021294
1.626725
''' Calculates end-of-period assets for each consumer of this type. Parameters ---------- None Returns ------- None ''' self.aLvlNow = self.mLvlNow - self.cLvlNow - self.MedPriceNow*self.MedNow return None
def getPostStates(self)
Calculates end-of-period assets for each consumer of this type. Parameters ---------- None Returns ------- None
13.459542
5.370462
2.506217
''' Unpacks some of the inputs (and calculates simple objects based on them), storing the results in self for use by other methods. These include: income shocks and probabilities, medical shocks and probabilities, next period's marginal value function (etc), the probability of getting the worst income shock next period, the patience factor, human wealth, and the bounding MPCs. Parameters ---------- solution_next : ConsumerSolution The solution to next period's one period problem. IncomeDstn : [np.array] A list containing three arrays of floats, representing a discrete approximation to the income process between the period being solved and the one immediately following (in solution_next). Order: event probabilities, permanent shocks, transitory shocks. LivPrb : float Survival probability; likelihood of being alive at the beginning of the succeeding period. DiscFac : float Intertemporal discount factor for future utility. Returns ------- None ''' # Run basic version of this method ConsGenIncProcessSolver.setAndUpdateValues(self,self.solution_next,self.IncomeDstn, self.LivPrb,self.DiscFac) # Also unpack the medical shock distribution self.MedShkPrbs = self.MedShkDstn[0] self.MedShkVals = self.MedShkDstn[1]
def setAndUpdateValues(self,solution_next,IncomeDstn,LivPrb,DiscFac)
Unpacks some of the inputs (and calculates simple objects based on them), storing the results in self for use by other methods. These include: income shocks and probabilities, medical shocks and probabilities, next period's marginal value function (etc), the probability of getting the worst income shock next period, the patience factor, human wealth, and the bounding MPCs. Parameters ---------- solution_next : ConsumerSolution The solution to next period's one period problem. IncomeDstn : [np.array] A list containing three arrays of floats, representing a discrete approximation to the income process between the period being solved and the one immediately following (in solution_next). Order: event probabilities, permanent shocks, transitory shocks. LivPrb : float Survival probability; likelihood of being alive at the beginning of the succeeding period. DiscFac : float Intertemporal discount factor for future utility. Returns ------- None
3.627634
1.590467
2.280861
''' Defines CRRA utility function for this period (and its derivatives, and their inverses), saving them as attributes of self for other methods to use. Extends version from ConsIndShock models by also defining inverse marginal utility function over medical care. Parameters ---------- none Returns ------- none ''' ConsGenIncProcessSolver.defUtilityFuncs(self) # Do basic version self.uMedPinv = lambda Med : utilityP_inv(Med,gam=self.CRRAmed) self.uMed = lambda Med : utility(Med,gam=self.CRRAmed) self.uMedPP = lambda Med : utilityPP(Med,gam=self.CRRAmed)
def defUtilityFuncs(self)
Defines CRRA utility function for this period (and its derivatives, and their inverses), saving them as attributes of self for other methods to use. Extends version from ConsIndShock models by also defining inverse marginal utility function over medical care. Parameters ---------- none Returns ------- none
10.063264
3.138224
3.206674
''' Defines the constrained portion of the consumption function as cFuncNowCnst, an attribute of self. Uses the artificial and natural borrowing constraints. Parameters ---------- BoroCnstArt : float or None Borrowing constraint for the minimum allowable (normalized) assets to end the period with. If it is less than the natural borrowing constraint at a particular permanent income level, then it is irrelevant; BoroCnstArt=None indicates no artificial borrowing constraint. Returns ------- None ''' # Find minimum allowable end-of-period assets at each permanent income level PermIncMinNext = self.PermShkMinNext*self.pLvlNextFunc(self.pLvlGrid) IncLvlMinNext = PermIncMinNext*self.TranShkMinNext aLvlMin = (self.solution_next.mLvlMin(PermIncMinNext) - IncLvlMinNext)/self.Rfree # Make a function for the natural borrowing constraint by permanent income BoroCnstNat = LinearInterp(np.insert(self.pLvlGrid,0,0.0),np.insert(aLvlMin,0,0.0)) self.BoroCnstNat = BoroCnstNat # Define the minimum allowable level of market resources by permanent income if self.BoroCnstArt is not None: BoroCnstArt = LinearInterp([0.0,1.0],[0.0,self.BoroCnstArt]) self.mLvlMinNow = UpperEnvelope(BoroCnstNat,BoroCnstArt) else: self.mLvlMinNow = BoroCnstNat # Make the constrained total spending function: spend all market resources trivial_grid = np.array([0.0,1.0]) # Trivial grid spendAllFunc = TrilinearInterp(np.array([[[0.0,0.0],[0.0,0.0]],[[1.0,1.0],[1.0,1.0]]]),\ trivial_grid,trivial_grid,trivial_grid) self.xFuncNowCnst = VariableLowerBoundFunc3D(spendAllFunc,self.mLvlMinNow) self.mNrmMinNow = 0.0 # Needs to exist so as not to break when solution is created self.MPCmaxEff = 0.0
def defBoroCnst(self,BoroCnstArt)
Defines the constrained portion of the consumption function as cFuncNowCnst, an attribute of self. Uses the artificial and natural borrowing constraints. Parameters ---------- BoroCnstArt : float or None Borrowing constraint for the minimum allowable (normalized) assets to end the period with. If it is less than the natural borrowing constraint at a particular permanent income level, then it is irrelevant; BoroCnstArt=None indicates no artificial borrowing constraint. Returns ------- None
4.355576
2.953595
1.474669
''' Finds endogenous interpolation points (x,m) for the expenditure function. Parameters ---------- EndOfPrdvP : np.array Array of end-of-period marginal values. aLvlNow : np.array Array of end-of-period asset values that yield the marginal values in EndOfPrdvP. Returns ------- x_for_interpolation : np.array Total expenditure points for interpolation. m_for_interpolation : np.array Corresponding market resource points for interpolation. p_for_interpolation : np.array Corresponding permanent income points for interpolation. ''' # Get size of each state dimension mCount = aLvlNow.shape[1] pCount = aLvlNow.shape[0] MedCount = self.MedShkVals.size # Calculate endogenous gridpoints and controls cLvlNow = np.tile(np.reshape(self.uPinv(EndOfPrdvP),(1,pCount,mCount)),(MedCount,1,1)) MedBaseNow = np.tile(np.reshape(self.uMedPinv(self.MedPrice*EndOfPrdvP),(1,pCount,mCount)), (MedCount,1,1)) MedShkVals_tiled = np.tile(np.reshape(self.MedShkVals**(1.0/self.CRRAmed),(MedCount,1,1)), (1,pCount,mCount)) MedLvlNow = MedShkVals_tiled*MedBaseNow aLvlNow_tiled = np.tile(np.reshape(aLvlNow,(1,pCount,mCount)),(MedCount,1,1)) xLvlNow = cLvlNow + self.MedPrice*MedLvlNow mLvlNow = xLvlNow + aLvlNow_tiled # Limiting consumption is zero as m approaches the natural borrowing constraint x_for_interpolation = np.concatenate((np.zeros((MedCount,pCount,1)),xLvlNow),axis=-1) temp = np.tile(self.BoroCnstNat(np.reshape(self.pLvlGrid,(1,self.pLvlGrid.size,1))), (MedCount,1,1)) m_for_interpolation = np.concatenate((temp,mLvlNow),axis=-1) # Make a 3D array of permanent income for interpolation p_for_interpolation = np.tile(np.reshape(self.pLvlGrid,(1,pCount,1)),(MedCount,1,mCount+1)) # Store for use by cubic interpolator self.cLvlNow = cLvlNow self.MedLvlNow = MedLvlNow self.MedShkVals_tiled = np.tile(np.reshape(self.MedShkVals,(MedCount,1,1)),(1,pCount,mCount)) return x_for_interpolation, m_for_interpolation, p_for_interpolation
def getPointsForInterpolation(self,EndOfPrdvP,aLvlNow)
Finds endogenous interpolation points (x,m) for the expenditure function. Parameters ---------- EndOfPrdvP : np.array Array of end-of-period marginal values. aLvlNow : np.array Array of end-of-period asset values that yield the marginal values in EndOfPrdvP. Returns ------- x_for_interpolation : np.array Total expenditure points for interpolation. m_for_interpolation : np.array Corresponding market resource points for interpolation. p_for_interpolation : np.array Corresponding permanent income points for interpolation.
2.998577
2.330377
1.286735
''' Constructs a basic solution for this period, including the consumption function and marginal value function. Parameters ---------- xLvl : np.array Total expenditure points for interpolation. mLvl : np.array Corresponding market resource points for interpolation. pLvl : np.array Corresponding permanent income level points for interpolation. MedShk : np.array Corresponding medical need shocks for interpolation. interpolator : function A function that constructs and returns a consumption function. Returns ------- solution_now : ConsumerSolution The solution to this period's consumption-saving problem, with a consumption function, marginal value function, and minimum m. ''' # Construct the unconstrained total expenditure function xFuncNowUnc = interpolator(mLvl,pLvl,MedShk,xLvl) xFuncNowCnst = self.xFuncNowCnst xFuncNow = LowerEnvelope3D(xFuncNowUnc,xFuncNowCnst) # Transform the expenditure function into policy functions for consumption and medical care aug_factor = 2 xLvlGrid = makeGridExpMult(np.min(xLvl),np.max(xLvl),aug_factor*self.aXtraGrid.size,8) policyFuncNow = MedShockPolicyFunc(xFuncNow,xLvlGrid,self.MedShkVals,self.MedPrice, self.CRRA,self.CRRAmed,xLvlCubicBool=self.CubicBool) cFuncNow = cThruXfunc(xFuncNow,policyFuncNow.cFunc) MedFuncNow = MedThruXfunc(xFuncNow,policyFuncNow.cFunc,self.MedPrice) # Make the marginal value function (and the value function if vFuncBool=True) vFuncNow, vPfuncNow = self.makevAndvPfuncs(policyFuncNow) # Pack up the solution and return it solution_now = ConsumerSolution(cFunc=cFuncNow, vFunc=vFuncNow, vPfunc=vPfuncNow,\ mNrmMin=self.mNrmMinNow) solution_now.MedFunc = MedFuncNow solution_now.policyFunc = policyFuncNow return solution_now
def usePointsForInterpolation(self,xLvl,mLvl,pLvl,MedShk,interpolator)
Constructs a basic solution for this period, including the consumption function and marginal value function. Parameters ---------- xLvl : np.array Total expenditure points for interpolation. mLvl : np.array Corresponding market resource points for interpolation. pLvl : np.array Corresponding permanent income level points for interpolation. MedShk : np.array Corresponding medical need shocks for interpolation. interpolator : function A function that constructs and returns a consumption function. Returns ------- solution_now : ConsumerSolution The solution to this period's consumption-saving problem, with a consumption function, marginal value function, and minimum m.
4.13458
2.834554
1.458635
''' Constructs the (unconstrained) expenditure function for this period using bilinear interpolation (over permanent income and the medical shock) among an array of linear interpolations over market resources. Parameters ---------- mLvl : np.array Corresponding market resource points for interpolation. pLvl : np.array Corresponding permanent income level points for interpolation. MedShk : np.array Corresponding medical need shocks for interpolation. xLvl : np.array Expenditure points for interpolation, corresponding to those in mLvl, pLvl, and MedShk. Returns ------- xFuncUnc : BilinearInterpOnInterp1D Unconstrained total expenditure function for this period. ''' # Get state dimensions pCount = mLvl.shape[1] MedCount = mLvl.shape[0] # Loop over each permanent income level and medical shock and make a linear xFunc xFunc_by_pLvl_and_MedShk = [] # Initialize the empty list of lists of 1D xFuncs for i in range(pCount): temp_list = [] pLvl_i = pLvl[0,i,0] mLvlMin_i = self.BoroCnstNat(pLvl_i) for j in range(MedCount): m_temp = mLvl[j,i,:] - mLvlMin_i x_temp = xLvl[j,i,:] temp_list.append(LinearInterp(m_temp,x_temp)) xFunc_by_pLvl_and_MedShk.append(deepcopy(temp_list)) # Combine the nested list of linear xFuncs into a single function pLvl_temp = pLvl[0,:,0] MedShk_temp = MedShk[:,0,0] xFuncUncBase = BilinearInterpOnInterp1D(xFunc_by_pLvl_and_MedShk,pLvl_temp,MedShk_temp) xFuncUnc = VariableLowerBoundFunc3D(xFuncUncBase,self.BoroCnstNat) return xFuncUnc
def makeLinearxFunc(self,mLvl,pLvl,MedShk,xLvl)
Constructs the (unconstrained) expenditure function for this period using bilinear interpolation (over permanent income and the medical shock) among an array of linear interpolations over market resources. Parameters ---------- mLvl : np.array Corresponding market resource points for interpolation. pLvl : np.array Corresponding permanent income level points for interpolation. MedShk : np.array Corresponding medical need shocks for interpolation. xLvl : np.array Expenditure points for interpolation, corresponding to those in mLvl, pLvl, and MedShk. Returns ------- xFuncUnc : BilinearInterpOnInterp1D Unconstrained total expenditure function for this period.
3.366503
2.122409
1.586171
''' Given end of period assets and end of period marginal value, construct the basic solution for this period. Parameters ---------- EndOfPrdvP : np.array Array of end-of-period marginal values. aLvl : np.array Array of end-of-period asset values that yield the marginal values in EndOfPrdvP. interpolator : function A function that constructs and returns a consumption function. Returns ------- solution_now : ConsumerSolution The solution to this period's consumption-saving problem, with a consumption function, marginal value function, and minimum m. ''' xLvl,mLvl,pLvl = self.getPointsForInterpolation(EndOfPrdvP,aLvl) MedShk_temp = np.tile(np.reshape(self.MedShkVals,(self.MedShkVals.size,1,1)),\ (1,mLvl.shape[1],mLvl.shape[2])) solution_now = self.usePointsForInterpolation(xLvl,mLvl,pLvl,MedShk_temp,interpolator) return solution_now
def makeBasicSolution(self,EndOfPrdvP,aLvl,interpolator)
Given end of period assets and end of period marginal value, construct the basic solution for this period. Parameters ---------- EndOfPrdvP : np.array Array of end-of-period marginal values. aLvl : np.array Array of end-of-period asset values that yield the marginal values in EndOfPrdvP. interpolator : function A function that constructs and returns a consumption function. Returns ------- solution_now : ConsumerSolution The solution to this period's consumption-saving problem, with a consumption function, marginal value function, and minimum m.
3.907602
1.923744
2.031248
''' Solves a one period consumption saving problem with risky income and shocks to medical need. Parameters ---------- None Returns ------- solution : ConsumerSolution The solution to the one period problem, including a consumption function, medical spending function ( both defined over market re- sources, permanent income, and medical shock), a marginal value func- tion (defined over market resources and permanent income), and human wealth as a function of permanent income. ''' aLvl,trash = self.prepareToCalcEndOfPrdvP() EndOfPrdvP = self.calcEndOfPrdvP() if self.vFuncBool: self.makeEndOfPrdvFunc(EndOfPrdvP) if self.CubicBool: interpolator = self.makeCubicxFunc else: interpolator = self.makeLinearxFunc solution = self.makeBasicSolution(EndOfPrdvP,aLvl,interpolator) solution = self.addMPCandHumanWealth(solution) if self.CubicBool: solution = self.addvPPfunc(solution) return solution
def solve(self)
Solves a one period consumption saving problem with risky income and shocks to medical need. Parameters ---------- None Returns ------- solution : ConsumerSolution The solution to the one period problem, including a consumption function, medical spending function ( both defined over market re- sources, permanent income, and medical shock), a marginal value func- tion (defined over market resources and permanent income), and human wealth as a function of permanent income.
7.730379
2.743941
2.817254
''' Find the borrowing constraint for each current state and save it as an attribute of self for use by other methods. Parameters ---------- none Returns ------- none ''' self.BoroCnstNatAll = np.zeros(self.StateCount) + np.nan # Find the natural borrowing constraint conditional on next period's state for j in range(self.StateCount): PermShkMinNext = np.min(self.IncomeDstn_list[j][1]) TranShkMinNext = np.min(self.IncomeDstn_list[j][2]) self.BoroCnstNatAll[j] = (self.solution_next.mNrmMin[j] - TranShkMinNext)*\ (self.PermGroFac_list[j]*PermShkMinNext)/self.Rfree_list[j] self.BoroCnstNat_list = np.zeros(self.StateCount) + np.nan self.mNrmMin_list = np.zeros(self.StateCount) + np.nan self.BoroCnstDependency = np.zeros((self.StateCount,self.StateCount)) + np.nan # The natural borrowing constraint in each current state is the *highest* # among next-state-conditional natural borrowing constraints that could # occur from this current state. for i in range(self.StateCount): possible_next_states = self.MrkvArray[i,:] > 0 self.BoroCnstNat_list[i] = np.max(self.BoroCnstNatAll[possible_next_states]) # Explicitly handle the "None" case: if self.BoroCnstArt is None: self.mNrmMin_list[i] = self.BoroCnstNat_list[i] else: self.mNrmMin_list[i] = np.max([self.BoroCnstNat_list[i],self.BoroCnstArt]) self.BoroCnstDependency[i,:] = self.BoroCnstNat_list[i] == self.BoroCnstNatAll
def defBoundary(self)
Find the borrowing constraint for each current state and save it as an attribute of self for use by other methods. Parameters ---------- none Returns ------- none
3.3894
2.877092
1.178064
''' Temporarily assume that a particular Markov state will occur in the succeeding period, and condition solver attributes on this assumption. Allows the solver to construct the future-state-conditional marginal value function (etc) for that future state. Parameters ---------- state_index : int Index of the future Markov state to condition on. Returns ------- none ''' # Set future-state-conditional values as attributes of self self.IncomeDstn = self.IncomeDstn_list[state_index] self.Rfree = self.Rfree_list[state_index] self.PermGroFac = self.PermGroFac_list[state_index] self.vPfuncNext = self.solution_next.vPfunc[state_index] self.mNrmMinNow = self.mNrmMin_list[state_index] self.BoroCnstNat = self.BoroCnstNatAll[state_index] self.setAndUpdateValues(self.solution_next,self.IncomeDstn,self.LivPrb,self.DiscFac) self.DiscFacEff = self.DiscFac # survival probability LivPrb represents probability from # *current* state, so DiscFacEff is just DiscFac for now # These lines have to come after setAndUpdateValues to override the definitions there self.vPfuncNext = self.solution_next.vPfunc[state_index] if self.CubicBool: self.vPPfuncNext= self.solution_next.vPPfunc[state_index] if self.vFuncBool: self.vFuncNext = self.solution_next.vFunc[state_index]
def conditionOnState(self,state_index)
Temporarily assume that a particular Markov state will occur in the succeeding period, and condition solver attributes on this assumption. Allows the solver to construct the future-state-conditional marginal value function (etc) for that future state. Parameters ---------- state_index : int Index of the future Markov state to condition on. Returns ------- none
5.388177
3.163668
1.703142
''' Calculates end-of-period marginal marginal value using a pre-defined array of next period market resources in self.mNrmNext. Parameters ---------- none Returns ------- EndOfPrdvPP : np.array End-of-period marginal marginal value of assets at each value in the grid of assets. ''' EndOfPrdvPP = self.DiscFacEff*self.Rfree*self.Rfree*self.PermGroFac**(-self.CRRA-1.0)*\ np.sum(self.PermShkVals_temp**(-self.CRRA-1.0)*self.vPPfuncNext(self.mNrmNext) *self.ShkPrbs_temp,axis=0) return EndOfPrdvPP
def calcEndOfPrdvPP(self)
Calculates end-of-period marginal marginal value using a pre-defined array of next period market resources in self.mNrmNext. Parameters ---------- none Returns ------- EndOfPrdvPP : np.array End-of-period marginal marginal value of assets at each value in the grid of assets.
4.913976
2.201867
2.231732
''' Construct the end-of-period value function conditional on next period's state. NOTE: It might be possible to eliminate this method and replace it with ConsIndShockSolver.makeEndOfPrdvFunc, but the self.X_cond variables must be renamed. Parameters ---------- none Returns ------- EndofPrdvFunc_cond : ValueFunc The end-of-period value function conditional on a particular state occuring in the next period. ''' VLvlNext = (self.PermShkVals_temp**(1.0-self.CRRA)* self.PermGroFac**(1.0-self.CRRA))*self.vFuncNext(self.mNrmNext) EndOfPrdv_cond = self.DiscFacEff*np.sum(VLvlNext*self.ShkPrbs_temp,axis=0) EndOfPrdvNvrs_cond = self.uinv(EndOfPrdv_cond) EndOfPrdvNvrsP_cond = self.EndOfPrdvP_cond*self.uinvP(EndOfPrdv_cond) EndOfPrdvNvrs_cond = np.insert(EndOfPrdvNvrs_cond,0,0.0) EndOfPrdvNvrsP_cond = np.insert(EndOfPrdvNvrsP_cond,0,EndOfPrdvNvrsP_cond[0]) aNrm_temp = np.insert(self.aNrm_cond,0,self.BoroCnstNat) EndOfPrdvNvrsFunc_cond = CubicInterp(aNrm_temp,EndOfPrdvNvrs_cond,EndOfPrdvNvrsP_cond) EndofPrdvFunc_cond = ValueFunc(EndOfPrdvNvrsFunc_cond,self.CRRA) return EndofPrdvFunc_cond
def makeEndOfPrdvFuncCond(self)
Construct the end-of-period value function conditional on next period's state. NOTE: It might be possible to eliminate this method and replace it with ConsIndShockSolver.makeEndOfPrdvFunc, but the self.X_cond variables must be renamed. Parameters ---------- none Returns ------- EndofPrdvFunc_cond : ValueFunc The end-of-period value function conditional on a particular state occuring in the next period.
3.725549
2.283157
1.631753
''' Construct the end-of-period marginal value function conditional on next period's state. Parameters ---------- None Returns ------- EndofPrdvPfunc_cond : MargValueFunc The end-of-period marginal value function conditional on a particular state occuring in the succeeding period. ''' # Get data to construct the end-of-period marginal value function (conditional on next state) self.aNrm_cond = self.prepareToCalcEndOfPrdvP() self.EndOfPrdvP_cond= self.calcEndOfPrdvPcond() EndOfPrdvPnvrs_cond = self.uPinv(self.EndOfPrdvP_cond) # "decurved" marginal value if self.CubicBool: EndOfPrdvPP_cond = self.calcEndOfPrdvPP() EndOfPrdvPnvrsP_cond = EndOfPrdvPP_cond*self.uPinvP(self.EndOfPrdvP_cond) # "decurved" marginal marginal value # Construct the end-of-period marginal value function conditional on the next state. if self.CubicBool: EndOfPrdvPnvrsFunc_cond = CubicInterp(self.aNrm_cond,EndOfPrdvPnvrs_cond, EndOfPrdvPnvrsP_cond,lower_extrap=True) else: EndOfPrdvPnvrsFunc_cond = LinearInterp(self.aNrm_cond,EndOfPrdvPnvrs_cond, lower_extrap=True) EndofPrdvPfunc_cond = MargValueFunc(EndOfPrdvPnvrsFunc_cond,self.CRRA) # "recurve" the interpolated marginal value function return EndofPrdvPfunc_cond
def makeEndOfPrdvPfuncCond(self)
Construct the end-of-period marginal value function conditional on next period's state. Parameters ---------- None Returns ------- EndofPrdvPfunc_cond : MargValueFunc The end-of-period marginal value function conditional on a particular state occuring in the succeeding period.
3.647224
2.785828
1.309207
''' Calculates end of period marginal value (and marginal marginal) value at each aXtra gridpoint for each current state, unconditional on the future Markov state (i.e. weighting conditional end-of-period marginal value by transition probabilities). Parameters ---------- none Returns ------- none ''' # Find unique values of minimum acceptable end-of-period assets (and the # current period states for which they apply). aNrmMin_unique, state_inverse = np.unique(self.BoroCnstNat_list,return_inverse=True) self.possible_transitions = self.MrkvArray > 0 # Calculate end-of-period marginal value (and marg marg value) at each # asset gridpoint for each current period state EndOfPrdvP = np.zeros((self.StateCount,self.aXtraGrid.size)) EndOfPrdvPP = np.zeros((self.StateCount,self.aXtraGrid.size)) for k in range(aNrmMin_unique.size): aNrmMin = aNrmMin_unique[k] # minimum assets for this pass which_states = state_inverse == k # the states for which this minimum applies aGrid = aNrmMin + self.aXtraGrid # assets grid for this pass EndOfPrdvP_all = np.zeros((self.StateCount,self.aXtraGrid.size)) EndOfPrdvPP_all = np.zeros((self.StateCount,self.aXtraGrid.size)) for j in range(self.StateCount): if np.any(np.logical_and(self.possible_transitions[:,j],which_states)): # only consider a future state if one of the relevant states could transition to it EndOfPrdvP_all[j,:] = self.EndOfPrdvPfunc_list[j](aGrid) if self.CubicBool: # Add conditional end-of-period (marginal) marginal value to the arrays EndOfPrdvPP_all[j,:] = self.EndOfPrdvPfunc_list[j].derivative(aGrid) # Weight conditional marginal (marginal) values by transition probs # to get unconditional marginal (marginal) value at each gridpoint. EndOfPrdvP_temp = np.dot(self.MrkvArray,EndOfPrdvP_all) EndOfPrdvP[which_states,:] = EndOfPrdvP_temp[which_states,:] # only take the states for which this asset minimum applies if self.CubicBool: EndOfPrdvPP_temp = np.dot(self.MrkvArray,EndOfPrdvPP_all) EndOfPrdvPP[which_states,:] = EndOfPrdvPP_temp[which_states,:] # Store the results as attributes of self, scaling end of period marginal value by survival probability from each current state LivPrb_tiled = np.tile(np.reshape(self.LivPrb,(self.StateCount,1)),(1,self.aXtraGrid.size)) self.EndOfPrdvP = LivPrb_tiled*EndOfPrdvP if self.CubicBool: self.EndOfPrdvPP = LivPrb_tiled*EndOfPrdvPP
def calcEndOfPrdvP(self)
Calculates end of period marginal value (and marginal marginal) value at each aXtra gridpoint for each current state, unconditional on the future Markov state (i.e. weighting conditional end-of-period marginal value by transition probabilities). Parameters ---------- none Returns ------- none
3.620886
2.859316
1.266347
''' Calculates human wealth and the maximum and minimum MPC for each current period state, then stores them as attributes of self for use by other methods. Parameters ---------- none Returns ------- none ''' # Upper bound on MPC at lower m-bound WorstIncPrb_array = self.BoroCnstDependency*np.tile(np.reshape(self.WorstIncPrbAll, (1,self.StateCount)),(self.StateCount,1)) temp_array = self.MrkvArray*WorstIncPrb_array WorstIncPrbNow = np.sum(temp_array,axis=1) # Probability of getting the "worst" income shock and transition from each current state ExMPCmaxNext = (np.dot(temp_array,self.Rfree_list**(1.0-self.CRRA)* self.solution_next.MPCmax**(-self.CRRA))/WorstIncPrbNow)**\ (-1.0/self.CRRA) DiscFacEff_temp = self.DiscFac*self.LivPrb self.MPCmaxNow = 1.0/(1.0 + ((DiscFacEff_temp*WorstIncPrbNow)** (1.0/self.CRRA))/ExMPCmaxNext) self.MPCmaxEff = self.MPCmaxNow self.MPCmaxEff[self.BoroCnstNat_list < self.mNrmMin_list] = 1.0 # State-conditional PDV of human wealth hNrmPlusIncNext = self.ExIncNextAll + self.solution_next.hNrm self.hNrmNow = np.dot(self.MrkvArray,(self.PermGroFac_list/self.Rfree_list)* hNrmPlusIncNext) # Lower bound on MPC as m gets arbitrarily large temp = (DiscFacEff_temp*np.dot(self.MrkvArray,self.solution_next.MPCmin** (-self.CRRA)*self.Rfree_list**(1.0-self.CRRA)))**(1.0/self.CRRA) self.MPCminNow = 1.0/(1.0 + temp)
def calcHumWealthAndBoundingMPCs(self)
Calculates human wealth and the maximum and minimum MPC for each current period state, then stores them as attributes of self for use by other methods. Parameters ---------- none Returns ------- none
5.039477
4.329066
1.164103
''' Make a linear interpolation to represent the (unconstrained) consumption function conditional on the current period state. Parameters ---------- mNrm : np.array Array of normalized market resource values for interpolation. cNrm : np.array Array of normalized consumption values for interpolation. Returns ------- cFuncUnc: an instance of HARK.interpolation.LinearInterp ''' cFuncUnc = LinearInterp(mNrm,cNrm,self.MPCminNow_j*self.hNrmNow_j,self.MPCminNow_j) return cFuncUnc
def makeLinearcFunc(self,mNrm,cNrm)
Make a linear interpolation to represent the (unconstrained) consumption function conditional on the current period state. Parameters ---------- mNrm : np.array Array of normalized market resource values for interpolation. cNrm : np.array Array of normalized consumption values for interpolation. Returns ------- cFuncUnc: an instance of HARK.interpolation.LinearInterp
5.411397
2.088042
2.591613
''' Make a cubic interpolation to represent the (unconstrained) consumption function conditional on the current period state. Parameters ---------- mNrm : np.array Array of normalized market resource values for interpolation. cNrm : np.array Array of normalized consumption values for interpolation. Returns ------- cFuncUnc: an instance of HARK.interpolation.CubicInterp ''' cFuncUnc = CubicInterp(mNrm,cNrm,self.MPC_temp_j,self.MPCminNow_j*self.hNrmNow_j, self.MPCminNow_j) return cFuncUnc
def makeCubiccFunc(self,mNrm,cNrm)
Make a cubic interpolation to represent the (unconstrained) consumption function conditional on the current period state. Parameters ---------- mNrm : np.array Array of normalized market resource values for interpolation. cNrm : np.array Array of normalized consumption values for interpolation. Returns ------- cFuncUnc: an instance of HARK.interpolation.CubicInterp
5.724911
2.300719
2.488314
''' Construct the value function for each current state. Parameters ---------- solution : ConsumerSolution The solution to the single period consumption-saving problem. Must have a consumption function cFunc (using cubic or linear splines) as a list with elements corresponding to the current Markov state. E.g. solution.cFunc[0] is the consumption function when in the i=0 Markov state this period. Returns ------- vFuncNow : [ValueFunc] A list of value functions (defined over normalized market resources m) for each current period Markov state. ''' vFuncNow = [] # Initialize an empty list of value functions # Loop over each current period state and construct the value function for i in range(self.StateCount): # Make state-conditional grids of market resources and consumption mNrmMin = self.mNrmMin_list[i] mGrid = mNrmMin + self.aXtraGrid cGrid = solution.cFunc[i](mGrid) aGrid = mGrid - cGrid # Calculate end-of-period value at each gridpoint EndOfPrdv_all = np.zeros((self.StateCount,self.aXtraGrid.size)) for j in range(self.StateCount): if self.possible_transitions[i,j]: EndOfPrdv_all[j,:] = self.EndOfPrdvFunc_list[j](aGrid) EndOfPrdv = np.dot(self.MrkvArray[i,:],EndOfPrdv_all) # Calculate (normalized) value and marginal value at each gridpoint vNrmNow = self.u(cGrid) + EndOfPrdv vPnow = self.uP(cGrid) # Make a "decurved" value function with the inverse utility function vNvrs = self.uinv(vNrmNow) # value transformed through inverse utility vNvrsP = vPnow*self.uinvP(vNrmNow) mNrm_temp = np.insert(mGrid,0,mNrmMin) # add the lower bound vNvrs = np.insert(vNvrs,0,0.0) vNvrsP = np.insert(vNvrsP,0,self.MPCmaxEff[i]**(-self.CRRA/(1.0-self.CRRA))) MPCminNvrs = self.MPCminNow[i]**(-self.CRRA/(1.0-self.CRRA)) vNvrsFunc_i = CubicInterp(mNrm_temp,vNvrs,vNvrsP,MPCminNvrs*self.hNrmNow[i],MPCminNvrs) # "Recurve" the decurved value function and add it to the list vFunc_i = ValueFunc(vNvrsFunc_i,self.CRRA) vFuncNow.append(vFunc_i) return vFuncNow
def makevFunc(self,solution)
Construct the value function for each current state. Parameters ---------- solution : ConsumerSolution The solution to the single period consumption-saving problem. Must have a consumption function cFunc (using cubic or linear splines) as a list with elements corresponding to the current Markov state. E.g. solution.cFunc[0] is the consumption function when in the i=0 Markov state this period. Returns ------- vFuncNow : [ValueFunc] A list of value functions (defined over normalized market resources m) for each current period Markov state.
4.15047
2.795597
1.484645
''' Many parameters used by MarkovConsumerType are arrays. Make sure those arrays are the right shape. Parameters ---------- None Returns ------- None ''' StateCount = self.MrkvArray[0].shape[0] # Check that arrays are the right shape assert self.Rfree.shape == (StateCount,),'Rfree not the right shape!' # Check that arrays in lists are the right shape for MrkvArray_t in self.MrkvArray: assert MrkvArray_t.shape == (StateCount,StateCount),'MrkvArray not the right shape!' for LivPrb_t in self.LivPrb: assert LivPrb_t.shape == (StateCount,),'Array in LivPrb is not the right shape!' for PermGroFac_t in self.LivPrb: assert PermGroFac_t.shape == (StateCount,),'Array in PermGroFac is not the right shape!' # Now check the income distribution. # Note IncomeDstn is (potentially) time-varying, so it is in time_vary. # Therefore it is a list, and each element of that list responds to the income distribution # at a particular point in time. Each income distribution at a point in time should itself # be a list, with each element corresponding to the income distribution # conditional on a particular Markov state. for IncomeDstn_t in self.IncomeDstn: assert len(IncomeDstn_t) == StateCount,'List in IncomeDstn is not the right length!'
def checkMarkovInputs(self)
Many parameters used by MarkovConsumerType are arrays. Make sure those arrays are the right shape. Parameters ---------- None Returns ------- None
4.374978
3.464204
1.26291
''' 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[0].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 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
3.840433
2.815885
1.363846
''' Makes new Markov consumer by drawing initial normalized assets, permanent income levels, and discrete states. Calls IndShockConsumerType.simBirth, then draws from initial Markov distribution. 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) # Get initial assets and permanent income if not self.global_markov: #Markov state is not changed if it is set at the global level N = np.sum(which_agents) base_draws = drawUniform(N,seed=self.RNG.randint(0,2**31-1)) Cutoffs = np.cumsum(np.array(self.MrkvPrbsInit)) self.MrkvNow[which_agents] = np.searchsorted(Cutoffs,base_draws).astype(int)
def simBirth(self,which_agents)
Makes new Markov consumer by drawing initial normalized assets, permanent income levels, and discrete states. Calls IndShockConsumerType.simBirth, then draws from initial Markov distribution. Parameters ---------- which_agents : np.array(Bool) Boolean array of size self.AgentCount indicating which agents should be "born". Returns ------- None
8.139178
3.474928
2.342258
''' Gets new Markov states and permanent and transitory income shocks for this period. Samples from IncomeDstn for each period-state in the cycle. Parameters ---------- None Returns ------- None ''' # Get new Markov states for each agent if self.global_markov: base_draws = np.ones(self.AgentCount)*drawUniform(1,seed=self.RNG.randint(0,2**31-1)) else: base_draws = self.RNG.permutation(np.arange(self.AgentCount,dtype=float)/self.AgentCount + 1.0/(2*self.AgentCount)) newborn = self.t_age == 0 # Don't change Markov state for those who were just born (unless global_markov) MrkvPrev = self.MrkvNow MrkvNow = np.zeros(self.AgentCount,dtype=int) for t in range(self.T_cycle): Cutoffs = np.cumsum(self.MrkvArray[t],axis=1) for j in range(self.MrkvArray[t].shape[0]): these = np.logical_and(self.t_cycle == t,MrkvPrev == j) MrkvNow[these] = np.searchsorted(Cutoffs[j,:],base_draws[these]).astype(int) if not self.global_markov: MrkvNow[newborn] = MrkvPrev[newborn] self.MrkvNow = MrkvNow.astype(int) # Now get income shocks for each consumer, by cycle-time and discrete state PermShkNow = np.zeros(self.AgentCount) # Initialize shock arrays TranShkNow = np.zeros(self.AgentCount) for t in range(self.T_cycle): for j in range(self.MrkvArray[t].shape[0]): these = np.logical_and(t == self.t_cycle, j == MrkvNow) N = np.sum(these) if N > 0: IncomeDstnNow = self.IncomeDstn[t-1][j] # set current income distribution PermGroFacNow = self.PermGroFac[t-1][j] # and permanent growth factor Indices = np.arange(IncomeDstnNow[0].size) # just a list of integers # Get random draws of income shocks from the discrete distribution EventDraws = drawDiscrete(N,X=Indices,P=IncomeDstnNow[0],exact_match=False,seed=self.RNG.randint(0,2**31-1)) PermShkNow[these] = IncomeDstnNow[1][EventDraws]*PermGroFacNow # permanent "shock" includes expected growth TranShkNow[these] = IncomeDstnNow[2][EventDraws] newborn = self.t_age == 0 PermShkNow[newborn] = 1.0 TranShkNow[newborn] = 1.0 self.PermShkNow = PermShkNow self.TranShkNow = TranShkNow
def getShocks(self)
Gets new Markov states and permanent and transitory income shocks for this period. Samples from IncomeDstn for each period-state in the cycle. Parameters ---------- None Returns ------- None
3.726504
3.228394
1.15429
''' A slight modification of AgentType.readShocks that makes sure that MrkvNow is int, not float. Parameters ---------- None Returns ------- None ''' IndShockConsumerType.readShocks(self) self.MrkvNow = self.MrkvNow.astype(int)
def readShocks(self)
A slight modification of AgentType.readShocks that makes sure that MrkvNow is int, not float. Parameters ---------- None Returns ------- None
7.239028
2.367135
3.058139
''' Calculates consumption for each consumer of this type using the consumption functions. Parameters ---------- None Returns ------- None ''' cNrmNow = np.zeros(self.AgentCount) + np.nan for t in range(self.T_cycle): for j in range(self.MrkvArray[t].shape[0]): these = np.logical_and(t == self.t_cycle, j == self.MrkvNow) cNrmNow[these] = self.solution[t].cFunc[j](self.mNrmNow[these]) self.cNrmNow = cNrmNow return None
def getControls(self)
Calculates consumption for each consumer of this type using the consumption functions. Parameters ---------- None Returns ------- None
4.923546
3.162806
1.556702
''' Calculates updated values of normalized market resources and permanent income level. Uses pLvlNow, aNrmNow, PermShkNow, TranShkNow. Parameters ---------- None Returns ------- None ''' pLvlPrev = self.pLvlNow aNrmPrev = self.aNrmNow # Calculate new states: normalized market resources and permanent income level self.pLvlNow = pLvlPrev*self.PermShkNow # Same as in IndShockConsType self.kNrmNow = aNrmPrev/self.PermShkNow self.yNrmNow = self.kNrmNow**self.CapShare*self.TranShkNow**(1.-self.CapShare) self.Rfree = 1. + self.CapShare*self.kNrmNow**(self.CapShare-1.)*self.TranShkNow**(1.-self.CapShare) - self.DeprFac self.wRte = (1.-self.CapShare)*self.kNrmNow**self.CapShare*self.TranShkNow**(-self.CapShare) self.mNrmNow = self.Rfree*self.kNrmNow + self.wRte*self.TranShkNow
def getStates(self)
Calculates updated values of normalized market resources and permanent income level. Uses pLvlNow, aNrmNow, PermShkNow, TranShkNow. Parameters ---------- None Returns ------- None
3.826439
2.538304
1.507479
''' Update the terminal period solution. This method should be run when a new AgentType is created or when CRRA changes. Parameters ---------- None Returns ------- None ''' RepAgentConsumerType.updateSolutionTerminal(self) # Make replicated terminal period solution StateCount = self.MrkvArray.shape[0] self.solution_terminal.cFunc = StateCount*[self.cFunc_terminal_] self.solution_terminal.vPfunc = StateCount*[self.solution_terminal.vPfunc] self.solution_terminal.mNrmMin = StateCount*[self.solution_terminal.mNrmMin]
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
5.27479
3.1709
1.663499
''' Draws a new Markov state and income shocks for the representative agent. Parameters ---------- None Returns ------- None ''' cutoffs = np.cumsum(self.MrkvArray[self.MrkvNow,:]) MrkvDraw = drawUniform(N=1,seed=self.RNG.randint(0,2**31-1)) self.MrkvNow = np.searchsorted(cutoffs,MrkvDraw) t = self.t_cycle[0] i = self.MrkvNow[0] IncomeDstnNow = self.IncomeDstn[t-1][i] # set current income distribution PermGroFacNow = self.PermGroFac[t-1][i] # and permanent growth factor Indices = np.arange(IncomeDstnNow[0].size) # just a list of integers # Get random draws of income shocks from the discrete distribution EventDraw = drawDiscrete(N=1,X=Indices,P=IncomeDstnNow[0],exact_match=False,seed=self.RNG.randint(0,2**31-1)) PermShkNow = IncomeDstnNow[1][EventDraw]*PermGroFacNow # permanent "shock" includes expected growth TranShkNow = IncomeDstnNow[2][EventDraw] self.PermShkNow = np.array(PermShkNow) self.TranShkNow = np.array(TranShkNow)
def getShocks(self)
Draws a new Markov state and income shocks for the representative agent. Parameters ---------- None Returns ------- None
4.337319
3.708063
1.169699
''' Calculates consumption for the representative agent using the consumption functions. Parameters ---------- None Returns ------- None ''' t = self.t_cycle[0] i = self.MrkvNow[0] self.cNrmNow = self.solution[t].cFunc[i](self.mNrmNow)
def getControls(self)
Calculates consumption for the representative agent using the consumption functions. Parameters ---------- None Returns ------- None
10.886662
4.849223
2.245033
''' Initialize this type for a new simulated history of K/L ratio. Parameters ---------- None Returns ------- None ''' self.initializeSim() self.aLvlNow = self.kInit*np.ones(self.AgentCount) # Start simulation near SS self.aNrmNow = self.aLvlNow/self.pLvlNow
def reset(self)
Initialize this type for a new simulated history of K/L ratio. Parameters ---------- None Returns ------- None
14.814819
6.030406
2.456687
''' Updates the terminal period solution for an aggregate shock consumer. Only fills in the consumption function and marginal value function. Parameters ---------- None Returns ------- None ''' cFunc_terminal = BilinearInterp(np.array([[0.0,0.0],[1.0,1.0]]),np.array([0.0,1.0]),np.array([0.0,1.0])) vPfunc_terminal = MargValueFunc2D(cFunc_terminal,self.CRRA) mNrmMin_terminal = ConstantFunction(0) self.solution_terminal = ConsumerSolution(cFunc=cFunc_terminal,vPfunc=vPfunc_terminal,mNrmMin=mNrmMin_terminal)
def updateSolutionTerminal(self)
Updates the terminal period solution for an aggregate shock consumer. Only fills in the consumption function and marginal value function. Parameters ---------- None Returns ------- None
4.266834
2.483345
1.71818
''' Imports economy-determined objects into self from a Market. Instances of AggShockConsumerType "live" in some macroeconomy that has attributes relevant to their microeconomic model, like the relationship between the capital-to-labor ratio and the interest and wage rates; this method imports those attributes from an "economy" object and makes them attributes of the ConsumerType. Parameters ---------- Economy : Market The "macroeconomy" in which this instance "lives". Might be of the subclass CobbDouglasEconomy, which has methods to generate the relevant attributes. Returns ------- None ''' self.T_sim = Economy.act_T # Need to be able to track as many periods as economy runs self.kInit = Economy.kSS # Initialize simulation assets to steady state self.aNrmInitMean = np.log(0.00000001) # Initialize newborn assets to nearly zero self.Mgrid = Economy.MSS*self.MgridBase # Aggregate market resources grid adjusted around SS capital ratio self.AFunc = Economy.AFunc # Next period's aggregate savings function self.Rfunc = Economy.Rfunc # Interest factor as function of capital ratio self.wFunc = Economy.wFunc # Wage rate as function of capital ratio self.DeprFac = Economy.DeprFac # Rate of capital depreciation self.PermGroFacAgg = Economy.PermGroFacAgg # Aggregate permanent productivity growth self.addAggShkDstn(Economy.AggShkDstn) # Combine idiosyncratic and aggregate shocks into one dstn self.addToTimeInv('Mgrid','AFunc','Rfunc', 'wFunc','DeprFac','PermGroFacAgg')
def getEconomyData(self,Economy)
Imports economy-determined objects into self from a Market. Instances of AggShockConsumerType "live" in some macroeconomy that has attributes relevant to their microeconomic model, like the relationship between the capital-to-labor ratio and the interest and wage rates; this method imports those attributes from an "economy" object and makes them attributes of the ConsumerType. Parameters ---------- Economy : Market The "macroeconomy" in which this instance "lives". Might be of the subclass CobbDouglasEconomy, which has methods to generate the relevant attributes. Returns ------- None
7.625759
3.371546
2.261799
''' Updates attribute IncomeDstn by combining idiosyncratic shocks with aggregate shocks. Parameters ---------- AggShkDstn : [np.array] Aggregate productivity shock distribution. First element is proba- bilities, second element is agg permanent shocks, third element is agg transitory shocks. Returns ------- None ''' if len(self.IncomeDstn[0]) > 3: self.IncomeDstn = self.IncomeDstnWithoutAggShocks else: self.IncomeDstnWithoutAggShocks = self.IncomeDstn self.IncomeDstn = [combineIndepDstns(self.IncomeDstn[t],AggShkDstn) for t in range(self.T_cycle)]
def addAggShkDstn(self,AggShkDstn)
Updates attribute IncomeDstn by combining idiosyncratic shocks with aggregate shocks. Parameters ---------- AggShkDstn : [np.array] Aggregate productivity shock distribution. First element is proba- bilities, second element is agg permanent shocks, third element is agg transitory shocks. Returns ------- None
4.057273
1.907816
2.126658
''' 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
5.017372
1.462048
3.431742
''' Randomly determine which consumers die, and distribute their wealth among the survivors. This method only works if there is only one period in the cycle. Parameters ---------- None Returns ------- who_dies : np.array(bool) Boolean array of size AgentCount indicating which agents die. ''' # Divide agents into wealth groups, kill one random agent per wealth group # order = np.argsort(self.aLvlNow) # how_many_die = int(self.AgentCount*(1.0-self.LivPrb[0])) # group_size = self.AgentCount/how_many_die # This should be an integer # base_idx = self.RNG.randint(0,group_size,size=how_many_die) # kill_by_rank = np.arange(how_many_die,dtype=int)*group_size + base_idx # who_dies = np.zeros(self.AgentCount,dtype=bool) # who_dies[order[kill_by_rank]] = True # Just select a random set of agents to die how_many_die = int(round(self.AgentCount*(1.0-self.LivPrb[0]))) base_bool = np.zeros(self.AgentCount,dtype=bool) base_bool[0:how_many_die] = True who_dies = self.RNG.permutation(base_bool) if self.T_age is not None: who_dies[self.t_age >= self.T_age] = True # Divide up the wealth of those who die, giving it to those who survive who_lives = np.logical_not(who_dies) wealth_living = np.sum(self.aLvlNow[who_lives]) wealth_dead = np.sum(self.aLvlNow[who_dies]) Ractuarial = 1.0 + wealth_dead/wealth_living self.aNrmNow[who_lives] = self.aNrmNow[who_lives]*Ractuarial self.aLvlNow[who_lives] = self.aLvlNow[who_lives]*Ractuarial return who_dies
def simDeath(self)
Randomly determine which consumers die, and distribute their wealth among the survivors. This method only works if there is only one period in the cycle. Parameters ---------- None Returns ------- who_dies : np.array(bool) Boolean array of size AgentCount indicating which agents die.
3.160424
2.378298
1.328859
''' Returns an array of size self.AgentCount with self.RfreeNow in every entry. Parameters ---------- None Returns ------- RfreeNow : np.array Array of size self.AgentCount with risk free interest rate for each agent. ''' RfreeNow = self.RfreeNow*np.ones(self.AgentCount) return RfreeNow
def getRfree(self)
Returns an array of size self.AgentCount with self.RfreeNow in every entry. Parameters ---------- None Returns ------- RfreeNow : np.array Array of size self.AgentCount with risk free interest rate for each agent.
6.283127
1.655485
3.795339
''' 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
5.065439
2.415624
2.096948
''' Variation on AggShockConsumerType.addAggShkDstn that handles the Markov state. AggShkDstn is a list of aggregate productivity shock distributions for each Markov state. ''' if len(self.IncomeDstn[0][0]) > 3: self.IncomeDstn = self.IncomeDstnWithoutAggShocks else: self.IncomeDstnWithoutAggShocks = self.IncomeDstn IncomeDstnOut = [] N = self.MrkvArray.shape[0] for t in range(self.T_cycle): IncomeDstnOut.append([combineIndepDstns(self.IncomeDstn[t][n],AggShkDstn[n]) for n in range(N)]) self.IncomeDstn = IncomeDstnOut
def addAggShkDstn(self,AggShkDstn)
Variation on AggShockConsumerType.addAggShkDstn that handles the Markov state. AggShkDstn is a list of aggregate productivity shock distributions for each Markov state.
4.415258
2.520653
1.751632
''' Update the terminal period solution. This method should be run when a new AgentType is created or when CRRA changes. Parameters ---------- None Returns ------- None ''' AggShockConsumerType.updateSolutionTerminal(self) # Make replicated terminal period solution StateCount = self.MrkvArray.shape[0] self.solution_terminal.cFunc = StateCount*[self.solution_terminal.cFunc] self.solution_terminal.vPfunc = StateCount*[self.solution_terminal.vPfunc] self.solution_terminal.mNrmMin = StateCount*[self.solution_terminal.mNrmMin]
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
4.431566
2.722193
1.62794
''' Gets permanent and transitory income shocks for this period. Samples from IncomeDstn for each period in the cycle. This is a copy-paste from IndShockConsumerType, with the addition of the Markov macroeconomic state. Unfortunately, the getShocks method for MarkovConsumerType cannot be used, as that method assumes that MrkvNow is a vector with a value for each agent, not just a single int. Parameters ---------- None Returns ------- None ''' PermShkNow = np.zeros(self.AgentCount) # Initialize shock arrays TranShkNow = np.zeros(self.AgentCount) newborn = self.t_age == 0 for t in range(self.T_cycle): these = t == self.t_cycle N = np.sum(these) if N > 0: IncomeDstnNow = self.IncomeDstn[t-1][self.MrkvNow] # set current income distribution PermGroFacNow = self.PermGroFac[t-1] # and permanent growth factor Indices = np.arange(IncomeDstnNow[0].size) # just a list of integers # Get random draws of income shocks from the discrete distribution EventDraws = drawDiscrete(N,X=Indices,P=IncomeDstnNow[0],exact_match=True,seed=self.RNG.randint(0,2**31-1)) PermShkNow[these] = IncomeDstnNow[1][EventDraws]*PermGroFacNow # permanent "shock" includes expected growth TranShkNow[these] = IncomeDstnNow[2][EventDraws] # That procedure used the *last* period in the sequence for newborns, but that's not right # Redraw shocks for newborns, using the *first* period in the sequence. Approximation. N = np.sum(newborn) if N > 0: these = newborn IncomeDstnNow = self.IncomeDstn[0][self.MrkvNow] # set current income distribution PermGroFacNow = self.PermGroFac[0] # and permanent growth factor Indices = np.arange(IncomeDstnNow[0].size) # just a list of integers # Get random draws of income shocks from the discrete distribution EventDraws = drawDiscrete(N,X=Indices,P=IncomeDstnNow[0],exact_match=False,seed=self.RNG.randint(0,2**31-1)) PermShkNow[these] = IncomeDstnNow[1][EventDraws]*PermGroFacNow # permanent "shock" includes expected growth TranShkNow[these] = IncomeDstnNow[2][EventDraws] # PermShkNow[newborn] = 1.0 # TranShkNow[newborn] = 1.0 # Store the shocks in self self.EmpNow = np.ones(self.AgentCount,dtype=bool) self.EmpNow[TranShkNow == self.IncUnemp] = False self.TranShkNow = TranShkNow*self.TranShkAggNow*self.wRteNow self.PermShkNow = PermShkNow*self.PermShkAggNow
def getShocks(self)
Gets permanent and transitory income shocks for this period. Samples from IncomeDstn for each period in the cycle. This is a copy-paste from IndShockConsumerType, with the addition of the Markov macroeconomic state. Unfortunately, the getShocks method for MarkovConsumerType cannot be used, as that method assumes that MrkvNow is a vector with a value for each agent, not just a single int. Parameters ---------- None Returns ------- None
3.329032
2.423755
1.373502
''' Calculates consumption for each consumer of this type using the consumption functions. For this AgentType class, MrkvNow is the same for all consumers. However, in an extension with "macroeconomic inattention", consumers might misperceive the state and thus act as if they are in different states. Parameters ---------- None Returns ------- None ''' cNrmNow = np.zeros(self.AgentCount) + np.nan MPCnow = np.zeros(self.AgentCount) + np.nan MaggNow = self.getMaggNow() MrkvNow = self.getMrkvNow() StateCount = self.MrkvArray.shape[0] MrkvBoolArray = np.zeros((StateCount,self.AgentCount),dtype=bool) for i in range(StateCount): MrkvBoolArray[i,:] = i == MrkvNow for t in range(self.T_cycle): these = t == self.t_cycle for i in range(StateCount): those = np.logical_and(these,MrkvBoolArray[i,:]) cNrmNow[those] = self.solution[t].cFunc[i](self.mNrmNow[those],MaggNow[those]) MPCnow[those] = self.solution[t].cFunc[i].derivativeX(self.mNrmNow[those],MaggNow[those]) # Marginal propensity to consume self.cNrmNow = cNrmNow self.MPCnow = MPCnow return None
def getControls(self)
Calculates consumption for each consumer of this type using the consumption functions. For this AgentType class, MrkvNow is the same for all consumers. However, in an extension with "macroeconomic inattention", consumers might misperceive the state and thus act as if they are in different states. Parameters ---------- None Returns ------- None
4.494213
2.197349
2.045288
''' Use primitive parameters (and perfect foresight calibrations) to make interest factor and wage rate functions (of capital to labor ratio), as well as discrete approximations to the aggregate shock distributions. Parameters ---------- None Returns ------- None ''' self.kSS = ((self.getPermGroFacAggLR()**(self.CRRA)/self.DiscFac - (1.0-self.DeprFac))/self.CapShare)**(1.0/(self.CapShare-1.0)) self.KtoYSS = self.kSS**(1.0-self.CapShare) self.wRteSS = (1.0-self.CapShare)*self.kSS**(self.CapShare) self.RfreeSS = (1.0 + self.CapShare*self.kSS**(self.CapShare-1.0) - self.DeprFac) self.MSS = self.kSS*self.RfreeSS + self.wRteSS self.convertKtoY = lambda KtoY : KtoY**(1.0/(1.0 - self.CapShare)) # converts K/Y to K/L self.Rfunc = lambda k : (1.0 + self.CapShare*k**(self.CapShare-1.0) - self.DeprFac) self.wFunc = lambda k : ((1.0-self.CapShare)*k**(self.CapShare)) self.KtoLnow_init = self.kSS self.MaggNow_init = self.kSS self.AaggNow_init = self.kSS self.RfreeNow_init = self.Rfunc(self.kSS) self.wRteNow_init = self.wFunc(self.kSS) self.PermShkAggNow_init = 1.0 self.TranShkAggNow_init = 1.0 self.makeAggShkDstn() self.AFunc = AggregateSavingRule(self.intercept_prev,self.slope_prev)
def update(self)
Use primitive parameters (and perfect foresight calibrations) to make interest factor and wage rate functions (of capital to labor ratio), as well as discrete approximations to the aggregate shock distributions. Parameters ---------- None Returns ------- None
4.534728
3.132879
1.447464
''' Creates the attributes TranShkAggDstn, PermShkAggDstn, and AggShkDstn. Draws on attributes TranShkAggStd, PermShkAddStd, TranShkAggCount, PermShkAggCount. Parameters ---------- None Returns ------- None ''' self.TranShkAggDstn = approxMeanOneLognormal(sigma=self.TranShkAggStd,N=self.TranShkAggCount) self.PermShkAggDstn = approxMeanOneLognormal(sigma=self.PermShkAggStd,N=self.PermShkAggCount) self.AggShkDstn = combineIndepDstns(self.PermShkAggDstn,self.TranShkAggDstn)
def makeAggShkDstn(self)
Creates the attributes TranShkAggDstn, PermShkAggDstn, and AggShkDstn. Draws on attributes TranShkAggStd, PermShkAddStd, TranShkAggCount, PermShkAggCount. Parameters ---------- None Returns ------- None
2.881031
1.655221
1.740572
''' Calculates the interest factor and wage rate this period using each agent's capital stock to get the aggregate capital ratio. Parameters ---------- aLvlNow : [np.array] Agents' current end-of-period assets. Elements of the list correspond to types in the economy, entries within arrays to agents of that type. Returns ------- AggVarsNow : CobbDouglasAggVars An object containing the aggregate variables for the upcoming period: capital-to-labor ratio, interest factor, (normalized) wage rate, aggregate permanent and transitory shocks. ''' # Calculate aggregate savings AaggPrev = np.mean(np.array(aLvlNow))/np.mean(pLvlNow) # End-of-period savings from last period # Calculate aggregate capital this period AggregateK = np.mean(np.array(aLvlNow)) # ...becomes capital today # This version uses end-of-period assets and # permanent income to calculate aggregate capital, unlike the Mathematica # version, which first applies the idiosyncratic permanent income shocks # and then aggregates. Obviously this is mathematically equivalent. # Get this period's aggregate shocks PermShkAggNow = self.PermShkAggHist[self.Shk_idx] TranShkAggNow = self.TranShkAggHist[self.Shk_idx] self.Shk_idx += 1 AggregateL = np.mean(pLvlNow)*PermShkAggNow # Calculate the interest factor and wage rate this period KtoLnow = AggregateK/AggregateL self.KtoYnow = KtoLnow**(1.0-self.CapShare) RfreeNow = self.Rfunc(KtoLnow/TranShkAggNow) wRteNow = self.wFunc(KtoLnow/TranShkAggNow) MaggNow = KtoLnow*RfreeNow + wRteNow*TranShkAggNow self.KtoLnow = KtoLnow # Need to store this as it is a sow variable # Package the results into an object and return it AggVarsNow = CobbDouglasAggVars(MaggNow,AaggPrev,KtoLnow,RfreeNow,wRteNow,PermShkAggNow,TranShkAggNow) return AggVarsNow
def calcRandW(self,aLvlNow,pLvlNow)
Calculates the interest factor and wage rate this period using each agent's capital stock to get the aggregate capital ratio. Parameters ---------- aLvlNow : [np.array] Agents' current end-of-period assets. Elements of the list correspond to types in the economy, entries within arrays to agents of that type. Returns ------- AggVarsNow : CobbDouglasAggVars An object containing the aggregate variables for the upcoming period: capital-to-labor ratio, interest factor, (normalized) wage rate, aggregate permanent and transitory shocks.
5.597821
3.233683
1.731098
''' Calculate a new aggregate savings rule based on the history of the aggregate savings and aggregate market resources from a simulation. Parameters ---------- MaggNow : [float] List of the history of the simulated aggregate market resources for an economy. AaggNow : [float] List of the history of the simulated aggregate savings for an economy. Returns ------- (unnamed) : CapDynamicRule Object containing a new savings rule ''' verbose = self.verbose discard_periods = self.T_discard # Throw out the first T periods to allow the simulation to approach the SS update_weight = 1. - self.DampingFac # Proportional weight to put on new function vs old function parameters total_periods = len(MaggNow) # Regress the log savings against log market resources logAagg = np.log(AaggNow[discard_periods:total_periods]) logMagg = np.log(MaggNow[discard_periods-1:total_periods-1]) slope, intercept, r_value, p_value, std_err = stats.linregress(logMagg,logAagg) # Make a new aggregate savings rule by combining the new regression parameters # with the previous guess intercept = update_weight*intercept + (1.0-update_weight)*self.intercept_prev slope = update_weight*slope + (1.0-update_weight)*self.slope_prev AFunc = AggregateSavingRule(intercept,slope) # Make a new next-period capital function # Save the new values as "previous" values for the next iteration self.intercept_prev = intercept self.slope_prev = slope # Plot aggregate resources vs aggregate savings for this run and print the new parameters if verbose: print('intercept=' + str(intercept) + ', slope=' + str(slope) + ', r-sq=' + str(r_value**2)) #plot_start = discard_periods #plt.plot(logMagg[plot_start:],logAagg[plot_start:],'.k') #plt.show() return AggShocksDynamicRule(AFunc)
def calcAFunc(self,MaggNow,AaggNow)
Calculate a new aggregate savings rule based on the history of the aggregate savings and aggregate market resources from a simulation. Parameters ---------- MaggNow : [float] List of the history of the simulated aggregate market resources for an economy. AaggNow : [float] List of the history of the simulated aggregate savings for an economy. Returns ------- (unnamed) : CapDynamicRule Object containing a new savings rule
5.005973
3.535789
1.415801
''' Use primitive parameters to set basic objects. This is an extremely stripped-down version of update for CobbDouglasEconomy. Parameters ---------- none Returns ------- none ''' self.kSS = 1.0 self.MSS = 1.0 self.KtoLnow_init = self.kSS self.Rfunc = ConstantFunction(self.Rfree) self.wFunc = ConstantFunction(self.wRte) self.RfreeNow_init = self.Rfunc(self.kSS) self.wRteNow_init = self.wFunc(self.kSS) self.MaggNow_init = self.kSS self.AaggNow_init = self.kSS self.PermShkAggNow_init = 1.0 self.TranShkAggNow_init = 1.0 self.makeAggShkDstn() self.AFunc = ConstantFunction(1.0)
def update(self)
Use primitive parameters to set basic objects. This is an extremely stripped-down version of update for CobbDouglasEconomy. Parameters ---------- none Returns ------- none
5.145731
2.958326
1.739407
''' Make simulated histories of aggregate transitory and permanent shocks. Histories are of length self.act_T, for use in the general equilibrium simulation. This replicates the same method for CobbDouglasEconomy; future version should create parent class. Parameters ---------- None Returns ------- None ''' sim_periods = self.act_T Events = np.arange(self.AggShkDstn[0].size) # just a list of integers EventDraws = drawDiscrete(N=sim_periods,P=self.AggShkDstn[0],X=Events,seed=0) PermShkAggHist = self.AggShkDstn[1][EventDraws] TranShkAggHist = self.AggShkDstn[2][EventDraws] # Store the histories self.PermShkAggHist = PermShkAggHist self.TranShkAggHist = TranShkAggHist
def makeAggShkHist(self)
Make simulated histories of aggregate transitory and permanent shocks. Histories are of length self.act_T, for use in the general equilibrium simulation. This replicates the same method for CobbDouglasEconomy; future version should create parent class. Parameters ---------- None Returns ------- None
5.07751
2.378675
2.134596
''' Returns aggregate state variables and shocks for this period. The capital-to-labor ratio is irrelevant and thus treated as constant, and the wage and interest rates are also constant. However, aggregate shocks are assigned from a prespecified history. Parameters ---------- None Returns ------- AggVarsNow : CobbDouglasAggVars Aggregate state and shock variables for this period. ''' # Get this period's aggregate shocks PermShkAggNow = self.PermShkAggHist[self.Shk_idx] TranShkAggNow = self.TranShkAggHist[self.Shk_idx] self.Shk_idx += 1 # Factor prices are constant RfreeNow = self.Rfunc(1.0/PermShkAggNow) wRteNow = self.wFunc(1.0/PermShkAggNow) # Aggregates are irrelavent AaggNow = 1.0 MaggNow = 1.0 KtoLnow = 1.0/PermShkAggNow # Package the results into an object and return it AggVarsNow = CobbDouglasAggVars(MaggNow,AaggNow,KtoLnow,RfreeNow,wRteNow,PermShkAggNow,TranShkAggNow) return AggVarsNow
def getAggShocks(self)
Returns aggregate state variables and shocks for this period. The capital-to-labor ratio is irrelevant and thus treated as constant, and the wage and interest rates are also constant. However, aggregate shocks are assigned from a prespecified history. Parameters ---------- None Returns ------- AggVarsNow : CobbDouglasAggVars Aggregate state and shock variables for this period.
4.544246
2.394601
1.897705
''' Use primitive parameters (and perfect foresight calibrations) to make interest factor and wage rate functions (of capital to labor ratio), as well as discrete approximations to the aggregate shock distributions. Parameters ---------- None Returns ------- None ''' CobbDouglasEconomy.update(self) StateCount = self.MrkvArray.shape[0] AFunc_all = [] for i in range(StateCount): AFunc_all.append(AggregateSavingRule(self.intercept_prev[i],self.slope_prev[i])) self.AFunc = AFunc_all
def update(self)
Use primitive parameters (and perfect foresight calibrations) to make interest factor and wage rate functions (of capital to labor ratio), as well as discrete approximations to the aggregate shock distributions. Parameters ---------- None Returns ------- None
11.497344
3.401436
3.380144
''' Calculates and returns the long run permanent income growth factor. This is the average growth factor in self.PermGroFacAgg, weighted by the long run distribution of Markov states (as determined by self.MrkvArray). Parameters ---------- None Returns ------- PermGroFacAggLR : float Long run aggregate permanent income growth factor ''' # Find the long run distribution of Markov states w, v = np.linalg.eig(np.transpose(self.MrkvArray)) idx = (np.abs(w-1.0)).argmin() x = v[:,idx].astype(float) LR_dstn = (x/np.sum(x)) # Return the weighted average of aggregate permanent income growth factors PermGroFacAggLR = np.dot(LR_dstn,np.array(self.PermGroFacAgg)) return PermGroFacAggLR
def getPermGroFacAggLR(self)
Calculates and returns the long run permanent income growth factor. This is the average growth factor in self.PermGroFacAgg, weighted by the long run distribution of Markov states (as determined by self.MrkvArray). Parameters ---------- None Returns ------- PermGroFacAggLR : float Long run aggregate permanent income growth factor
4.04113
2.257476
1.79011
''' Creates the attributes TranShkAggDstn, PermShkAggDstn, and AggShkDstn. Draws on attributes TranShkAggStd, PermShkAddStd, TranShkAggCount, PermShkAggCount. This version accounts for the Markov macroeconomic state. Parameters ---------- None Returns ------- None ''' TranShkAggDstn = [] PermShkAggDstn = [] AggShkDstn = [] StateCount = self.MrkvArray.shape[0] for i in range(StateCount): TranShkAggDstn.append(approxMeanOneLognormal(sigma=self.TranShkAggStd[i],N=self.TranShkAggCount)) PermShkAggDstn.append(approxMeanOneLognormal(sigma=self.PermShkAggStd[i],N=self.PermShkAggCount)) AggShkDstn.append(combineIndepDstns(PermShkAggDstn[-1],TranShkAggDstn[-1])) self.TranShkAggDstn = TranShkAggDstn self.PermShkAggDstn = PermShkAggDstn self.AggShkDstn = AggShkDstn
def makeAggShkDstn(self)
Creates the attributes TranShkAggDstn, PermShkAggDstn, and AggShkDstn. Draws on attributes TranShkAggStd, PermShkAddStd, TranShkAggCount, PermShkAggCount. This version accounts for the Markov macroeconomic state. Parameters ---------- None Returns ------- None
2.658353
1.610274
1.650869
''' Make simulated histories of aggregate transitory and permanent shocks. Histories are of length self.act_T, for use in the general equilibrium simulation. Draws on history of aggregate Markov states generated by internal call to makeMrkvHist(). Parameters ---------- None Returns ------- None ''' self.makeMrkvHist() # Make a (pseudo)random sequence of Markov states sim_periods = self.act_T # For each Markov state in each simulated period, draw the aggregate shocks # that would occur in that state in that period StateCount = self.MrkvArray.shape[0] PermShkAggHistAll = np.zeros((StateCount,sim_periods)) TranShkAggHistAll = np.zeros((StateCount,sim_periods)) for i in range(StateCount): Events = np.arange(self.AggShkDstn[i][0].size) # just a list of integers EventDraws = drawDiscrete(N=sim_periods,P=self.AggShkDstn[i][0],X=Events,seed=0) PermShkAggHistAll[i,:] = self.AggShkDstn[i][1][EventDraws] TranShkAggHistAll[i,:] = self.AggShkDstn[i][2][EventDraws] # Select the actual history of aggregate shocks based on the sequence # of Markov states that the economy experiences PermShkAggHist = np.zeros(sim_periods) TranShkAggHist = np.zeros(sim_periods) for i in range(StateCount): these = i == self.MrkvNow_hist PermShkAggHist[these] = PermShkAggHistAll[i,these]*self.PermGroFacAgg[i] TranShkAggHist[these] = TranShkAggHistAll[i,these] # Store the histories self.PermShkAggHist = PermShkAggHist self.TranShkAggHist = TranShkAggHist
def makeAggShkHist(self)
Make simulated histories of aggregate transitory and permanent shocks. Histories are of length self.act_T, for use in the general equilibrium simulation. Draws on history of aggregate Markov states generated by internal call to makeMrkvHist(). Parameters ---------- None Returns ------- None
3.521977
2.528301
1.393021
''' Function to calculate the capital to labor ratio, interest factor, and wage rate based on each agent's current state. Just calls calcRandW() and adds the Markov state index. See documentation for calcRandW for more information. ''' MrkvNow = self.MrkvNow_hist[self.Shk_idx] temp = self.calcRandW(aLvlNow,pLvlNow) temp(MrkvNow = MrkvNow) return temp
def millRule(self,aLvlNow,pLvlNow)
Function to calculate the capital to labor ratio, interest factor, and wage rate based on each agent's current state. Just calls calcRandW() and adds the Markov state index. See documentation for calcRandW for more information.
13.501414
2.992998
4.511001
''' Calculate a new aggregate savings rule based on the history of the aggregate savings and aggregate market resources from a simulation. Calculates an aggregate saving rule for each macroeconomic Markov state. Parameters ---------- MaggNow : [float] List of the history of the simulated aggregate market resources for an economy. AaggNow : [float] List of the history of the simulated aggregate savings for an economy. Returns ------- (unnamed) : CapDynamicRule Object containing new saving rules for each Markov state. ''' verbose = self.verbose discard_periods = self.T_discard # Throw out the first T periods to allow the simulation to approach the SS update_weight = 1. - self.DampingFac # Proportional weight to put on new function vs old function parameters total_periods = len(MaggNow) # Trim the histories of M_t and A_t and convert them to logs logAagg = np.log(AaggNow[discard_periods:total_periods]) logMagg = np.log(MaggNow[discard_periods-1:total_periods-1]) MrkvHist = self.MrkvNow_hist[discard_periods-1:total_periods-1] # For each Markov state, regress A_t on M_t and update the saving rule AFunc_list = [] rSq_list = [] for i in range(self.MrkvArray.shape[0]): these = i == MrkvHist slope, intercept, r_value, p_value, std_err = stats.linregress(logMagg[these],logAagg[these]) #if verbose: # plt.plot(logMagg[these],logAagg[these],'.') # Make a new aggregate savings rule by combining the new regression parameters # with the previous guess intercept = update_weight*intercept + (1.0-update_weight)*self.intercept_prev[i] slope = update_weight*slope + (1.0-update_weight)*self.slope_prev[i] AFunc_list.append(AggregateSavingRule(intercept,slope)) # Make a new next-period capital function rSq_list.append(r_value**2) # Save the new values as "previous" values for the next iteration self.intercept_prev[i] = intercept self.slope_prev[i] = slope # Plot aggregate resources vs aggregate savings for this run and print the new parameters if verbose: print('intercept=' + str(self.intercept_prev) + ', slope=' + str(self.slope_prev) + ', r-sq=' + str(rSq_list)) #plt.show() return AggShocksDynamicRule(AFunc_list)
def calcAFunc(self,MaggNow,AaggNow)
Calculate a new aggregate savings rule based on the history of the aggregate savings and aggregate market resources from a simulation. Calculates an aggregate saving rule for each macroeconomic Markov state. Parameters ---------- MaggNow : [float] List of the history of the simulated aggregate market resources for an economy. AaggNow : [float] List of the history of the simulated aggregate savings for an economy. Returns ------- (unnamed) : CapDynamicRule Object containing new saving rules for each Markov state.
4.730549
3.315587
1.426761
''' Finds the difference between simulated and target capital to income ratio in an economy when a given parameter has heterogeneity according to some distribution. Parameters ---------- Economy : cstwMPCmarket An object representing the entire economy, containing the various AgentTypes as an attribute. param_name : string The name of the parameter of interest that varies across the population. param_count : int The number of different values the parameter of interest will take on. center : float A measure of centrality for the distribution of the parameter of interest. spread : float A measure of spread or diffusion for the distribution of the parameter of interest. dist_type : string The type of distribution to be used. Can be "lognormal" or "uniform" (can expand). Returns ------- diff : float Difference between simulated and target capital to income ratio for this economy. ''' Economy(LorenzBool = False, ManyStatsBool = False) # Make sure we're not wasting time calculating stuff Economy.distributeParams(param_name,param_count,center,spread,dist_type) # Distribute parameters Economy.solve() diff = Economy.calcKYratioDifference() print('getKYratioDifference tried center = ' + str(center) + ' and got ' + str(diff)) return diff
def getKYratioDifference(Economy,param_name,param_count,center,spread,dist_type)
Finds the difference between simulated and target capital to income ratio in an economy when a given parameter has heterogeneity according to some distribution. Parameters ---------- Economy : cstwMPCmarket An object representing the entire economy, containing the various AgentTypes as an attribute. param_name : string The name of the parameter of interest that varies across the population. param_count : int The number of different values the parameter of interest will take on. center : float A measure of centrality for the distribution of the parameter of interest. spread : float A measure of spread or diffusion for the distribution of the parameter of interest. dist_type : string The type of distribution to be used. Can be "lognormal" or "uniform" (can expand). Returns ------- diff : float Difference between simulated and target capital to income ratio for this economy.
6.048744
2.131835
2.837341
''' Finds the sum of squared distances between simulated and target Lorenz points in an economy when a given parameter has heterogeneity according to some distribution. The class of distribution and a measure of spread are given as inputs, but the measure of centrality such that the capital to income ratio matches the target ratio must be found. Parameters ---------- Economy : cstwMPCmarket An object representing the entire economy, containing the various AgentTypes as an attribute. param_name : string The name of the parameter of interest that varies across the population. param_count : int The number of different values the parameter of interest will take on. center_range : [float,float] Bounding values for a measure of centrality for the distribution of the parameter of interest. spread : float A measure of spread or diffusion for the distribution of the parameter of interest. dist_type : string The type of distribution to be used. Can be "lognormal" or "uniform" (can expand). Returns ------- dist : float Sum of squared distances between simulated and target Lorenz points for this economy (sqrt). ''' # Define the function to search for the correct value of center, then find its zero intermediateObjective = lambda center : getKYratioDifference(Economy = Economy, param_name = param_name, param_count = param_count, center = center, spread = spread, dist_type = dist_type) optimal_center = brentq(intermediateObjective,center_range[0],center_range[1],xtol=10**(-6)) Economy.center_save = optimal_center # Get the sum of squared Lorenz distances given the correct distribution of the parameter Economy(LorenzBool = True) # Make sure we actually calculate simulated Lorenz points Economy.distributeParams(param_name,param_count,optimal_center,spread,dist_type) # Distribute parameters Economy.solveAgents() Economy.makeHistory() dist = Economy.calcLorenzDistance() Economy(LorenzBool = False) print ('findLorenzDistanceAtTargetKY tried spread = ' + str(spread) + ' and got ' + str(dist)) return dist
def findLorenzDistanceAtTargetKY(Economy,param_name,param_count,center_range,spread,dist_type)
Finds the sum of squared distances between simulated and target Lorenz points in an economy when a given parameter has heterogeneity according to some distribution. The class of distribution and a measure of spread are given as inputs, but the measure of centrality such that the capital to income ratio matches the target ratio must be found. Parameters ---------- Economy : cstwMPCmarket An object representing the entire economy, containing the various AgentTypes as an attribute. param_name : string The name of the parameter of interest that varies across the population. param_count : int The number of different values the parameter of interest will take on. center_range : [float,float] Bounding values for a measure of centrality for the distribution of the parameter of interest. spread : float A measure of spread or diffusion for the distribution of the parameter of interest. dist_type : string The type of distribution to be used. Can be "lognormal" or "uniform" (can expand). Returns ------- dist : float Sum of squared distances between simulated and target Lorenz points for this economy (sqrt).
5.6942
2.317508
2.457036
''' Calculates the steady state proportions of each age given survival probability sequence LivPrb. Assumes that agents who die are replaced by a newborn agent with t_age=0. Parameters ---------- LivPrb : [float] Sequence of survival probabilities in ordinary chronological order. Has length T_cycle. terminal_period : bool Indicator for whether a terminal period follows the last period in the cycle (with LivPrb=0). Returns ------- AgeDstn : np.array Stationary distribution of age. Stochastic vector with frequencies of each age. ''' T = len(LivPrb) if terminal_period: MrkvArray = np.zeros((T+1,T+1)) top = T else: MrkvArray = np.zeros((T,T)) top = T-1 for t in range(top): MrkvArray[t,0] = 1.0 - LivPrb[t] MrkvArray[t,t+1] = LivPrb[t] MrkvArray[t+1,0] = 1.0 w, v = np.linalg.eig(np.transpose(MrkvArray)) idx = (np.abs(w-1.0)).argmin() x = v[:,idx].astype(float) AgeDstn = (x/np.sum(x)) return AgeDstn
def calcStationaryAgeDstn(LivPrb,terminal_period)
Calculates the steady state proportions of each age given survival probability sequence LivPrb. Assumes that agents who die are replaced by a newborn agent with t_age=0. Parameters ---------- LivPrb : [float] Sequence of survival probabilities in ordinary chronological order. Has length T_cycle. terminal_period : bool Indicator for whether a terminal period follows the last period in the cycle (with LivPrb=0). Returns ------- AgeDstn : np.array Stationary distribution of age. Stochastic vector with frequencies of each age.
4.136896
1.730014
2.39125
''' An alternative method for constructing the income process in the infinite horizon model. Parameters ---------- none Returns ------- none ''' if self.cycles == 0: tax_rate = (self.IncUnemp*self.UnempPrb)/((1.0-self.UnempPrb)*self.IndL) TranShkDstn = deepcopy(approxMeanOneLognormal(self.TranShkCount,sigma=self.TranShkStd[0],tail_N=0)) TranShkDstn[0] = np.insert(TranShkDstn[0]*(1.0-self.UnempPrb),0,self.UnempPrb) TranShkDstn[1] = np.insert(TranShkDstn[1]*(1.0-tax_rate)*self.IndL,0,self.IncUnemp) PermShkDstn = approxMeanOneLognormal(self.PermShkCount,sigma=self.PermShkStd[0],tail_N=0) self.IncomeDstn = [combineIndepDstns(PermShkDstn,TranShkDstn)] self.TranShkDstn = TranShkDstn self.PermShkDstn = PermShkDstn self.addToTimeVary('IncomeDstn') else: # Do the usual method if this is the lifecycle model EstimationAgentClass.updateIncomeProcess(self)
def updateIncomeProcess(self)
An alternative method for constructing the income process in the infinite horizon model. Parameters ---------- none Returns ------- none
4.045452
3.489318
1.159382
''' Solves the cstwMPCmarket. ''' if self.AggShockBool: for agent in self.agents: agent.getEconomyData(self) Market.solve(self) else: self.solveAgents() self.makeHistory()
def solve(self)
Solves the cstwMPCmarket.
15.055676
6.797852
2.21477
''' The millRule for this class simply calls the method calcStats. ''' self.calcStats(aLvlNow,pLvlNow,MPCnow,TranShkNow,EmpNow,t_age,LorenzBool,ManyStatsBool) if self.AggShockBool: return self.calcRandW(aLvlNow,pLvlNow) else: # These variables are tracked but not created in no-agg-shocks specifications self.MaggNow = 0.0 self.AaggNow = 0.0
def millRule(self,aLvlNow,pLvlNow,MPCnow,TranShkNow,EmpNow,t_age,LorenzBool,ManyStatsBool)
The millRule for this class simply calls the method calcStats.
5.633596
4.029594
1.398055
''' Distributes heterogeneous values of one parameter to the AgentTypes in self.agents. Parameters ---------- param_name : string Name of the parameter to be assigned. param_count : int Number of different values the parameter will take on. center : float A measure of centrality for the distribution of the parameter. spread : float A measure of spread or diffusion for the distribution of the parameter. dist_type : string The type of distribution to be used. Can be "lognormal" or "uniform" (can expand). Returns ------- None ''' # Get a list of discrete values for the parameter if dist_type == 'uniform': # If uniform, center is middle of distribution, spread is distance to either edge param_dist = approxUniform(N=param_count,bot=center-spread,top=center+spread) elif dist_type == 'lognormal': # If lognormal, center is the mean and spread is the standard deviation (in log) tail_N = 3 param_dist = approxLognormal(N=param_count-tail_N,mu=np.log(center)-0.5*spread**2,sigma=spread,tail_N=tail_N,tail_bound=[0.0,0.9], tail_order=np.e) # Distribute the parameters to the various types, assigning consecutive types the same # value if there are more types than values replication_factor = len(self.agents) // param_count # Note: the double division is intenger division in Python 3 and 2.7, this makes it explicit j = 0 b = 0 while j < len(self.agents): for n in range(replication_factor): self.agents[j](AgentCount = int(self.Population*param_dist[0][b]*self.TypeWeight[n])) exec('self.agents[j](' + param_name + '= param_dist[1][b])') j += 1 b += 1
def distributeParams(self,param_name,param_count,center,spread,dist_type)
Distributes heterogeneous values of one parameter to the AgentTypes in self.agents. Parameters ---------- param_name : string Name of the parameter to be assigned. param_count : int Number of different values the parameter will take on. center : float A measure of centrality for the distribution of the parameter. spread : float A measure of spread or diffusion for the distribution of the parameter. dist_type : string The type of distribution to be used. Can be "lognormal" or "uniform" (can expand). Returns ------- None
5.074802
3.599065
1.410033
''' Returns the difference between the simulated capital to income ratio and the target ratio. Can only be run after solving all AgentTypes and running makeHistory. Parameters ---------- None Returns ------- diff : float Difference between simulated and target capital to income ratio. ''' # Ignore the first X periods to allow economy to stabilize from initial conditions KYratioSim = np.mean(np.array(self.KtoYnow_hist)[self.ignore_periods:]) diff = KYratioSim - self.KYratioTarget return diff
def calcKYratioDifference(self)
Returns the difference between the simulated capital to income ratio and the target ratio. Can only be run after solving all AgentTypes and running makeHistory. Parameters ---------- None Returns ------- diff : float Difference between simulated and target capital to income ratio.
10.175361
3.71946
2.735709
''' Returns the sum of squared differences between simulated and target Lorenz points. Parameters ---------- None Returns ------- dist : float Sum of squared distances between simulated and target Lorenz points (sqrt) ''' LorenzSim = np.mean(np.array(self.Lorenz_hist)[self.ignore_periods:,:],axis=0) dist = np.sqrt(np.sum((100*(LorenzSim - self.LorenzTarget))**2)) self.LorenzDistance = dist return dist
def calcLorenzDistance(self)
Returns the sum of squared differences between simulated and target Lorenz points. Parameters ---------- None Returns ------- dist : float Sum of squared distances between simulated and target Lorenz points (sqrt)
4.359365
2.679512
1.626925
''' Evaluate the first derivative with respect to market resources of the marginal value function at given levels of market resources m and per- manent income p. Parameters ---------- m : float or np.array Market resources whose value is to be calcuated. p : float or np.array Persistent income levels whose value is to be calculated. Returns ------- vPP : float or np.array Marginal marginal value of market resources when beginning this period with market resources m and persistent income p; has same size as inputs m and p. ''' c = self.cFunc(m,p) MPC = self.cFunc.derivativeX(m,p) return MPC*utilityPP(c,gam=self.CRRA)
def derivativeX(self,m,p)
Evaluate the first derivative with respect to market resources of the marginal value function at given levels of market resources m and per- manent income p. Parameters ---------- m : float or np.array Market resources whose value is to be calcuated. p : float or np.array Persistent income levels whose value is to be calculated. Returns ------- vPP : float or np.array Marginal marginal value of market resources when beginning this period with market resources m and persistent income p; has same size as inputs m and p.
7.594263
1.944306
3.905899
''' Unpacks some of the inputs (and calculates simple objects based on them), storing the results in self for use by other methods. These include: income shocks and probabilities, next period's marginal value function (etc), the probability of getting the worst income shock next period, the patience factor, human wealth, and the bounding MPCs. Human wealth is stored as a function of persistent income. Parameters ---------- solution_next : ConsumerSolution The solution to next period's one period problem. IncomeDstn : [np.array] A list containing three arrays of floats, representing a discrete approximation to the income process between the period being solved and the one immediately following (in solution_next). Order: event probabilities, persistent shocks, transitory shocks. LivPrb : float Survival probability; likelihood of being alive at the beginning of the succeeding period. DiscFac : float Intertemporal discount factor for future utility. Returns ------- None ''' # Run basic version of this method ConsIndShockSetup.setAndUpdateValues(self,solution_next,IncomeDstn,LivPrb,DiscFac) self.mLvlMinNext = solution_next.mLvlMin # Replace normalized human wealth (scalar) with human wealth level as function of persistent income self.hNrmNow = 0.0 pLvlCount = self.pLvlGrid.size IncShkCount = self.PermShkValsNext.size pLvlNext = np.tile(self.pLvlNextFunc(self.pLvlGrid),(IncShkCount,1))*np.tile(self.PermShkValsNext,(pLvlCount,1)).transpose() hLvlGrid = 1.0/self.Rfree*np.sum((np.tile(self.TranShkValsNext,(pLvlCount,1)).transpose()*pLvlNext + solution_next.hLvl(pLvlNext))*np.tile(self.ShkPrbsNext,(pLvlCount,1)).transpose(),axis=0) self.hLvlNow = LinearInterp(np.insert(self.pLvlGrid,0,0.0),np.insert(hLvlGrid,0,0.0))
def setAndUpdateValues(self,solution_next,IncomeDstn,LivPrb,DiscFac)
Unpacks some of the inputs (and calculates simple objects based on them), storing the results in self for use by other methods. These include: income shocks and probabilities, next period's marginal value function (etc), the probability of getting the worst income shock next period, the patience factor, human wealth, and the bounding MPCs. Human wealth is stored as a function of persistent income. Parameters ---------- solution_next : ConsumerSolution The solution to next period's one period problem. IncomeDstn : [np.array] A list containing three arrays of floats, representing a discrete approximation to the income process between the period being solved and the one immediately following (in solution_next). Order: event probabilities, persistent shocks, transitory shocks. LivPrb : float Survival probability; likelihood of being alive at the beginning of the succeeding period. DiscFac : float Intertemporal discount factor for future utility. Returns ------- None
3.564502
2.07857
1.714881
''' Defines the constrained portion of the consumption function as cFuncNowCnst, an attribute of self. Parameters ---------- BoroCnstArt : float or None Borrowing constraint for the minimum allowable assets to end the period with. If it is less than the natural borrowing constraint, then it is irrelevant; BoroCnstArt=None indicates no artificial bor- rowing constraint. Returns ------- None ''' # Make temporary grids of income shocks and next period income values ShkCount = self.TranShkValsNext.size pLvlCount = self.pLvlGrid.size PermShkVals_temp = np.tile(np.reshape(self.PermShkValsNext,(1,ShkCount)),(pLvlCount,1)) TranShkVals_temp = np.tile(np.reshape(self.TranShkValsNext,(1,ShkCount)),(pLvlCount,1)) pLvlNext_temp = np.tile(np.reshape(self.pLvlNextFunc(self.pLvlGrid),(pLvlCount,1)),(1,ShkCount))*PermShkVals_temp # Find the natural borrowing constraint for each persistent income level aLvlMin_candidates = (self.mLvlMinNext(pLvlNext_temp) - TranShkVals_temp*pLvlNext_temp)/self.Rfree aLvlMinNow = np.max(aLvlMin_candidates,axis=1) self.BoroCnstNat = LinearInterp(np.insert(self.pLvlGrid,0,0.0),np.insert(aLvlMinNow,0,0.0)) # Define the minimum allowable mLvl by pLvl as the greater of the natural and artificial borrowing constraints if self.BoroCnstArt is not None: self.BoroCnstArt = LinearInterp(np.array([0.0,1.0]),np.array([0.0,self.BoroCnstArt])) self.mLvlMinNow = UpperEnvelope(self.BoroCnstArt,self.BoroCnstNat) else: self.mLvlMinNow = self.BoroCnstNat # Define the constrained consumption function as "consume all" shifted by mLvlMin cFuncNowCnstBase = BilinearInterp(np.array([[0.,0.],[1.,1.]]),np.array([0.0,1.0]),np.array([0.0,1.0])) self.cFuncNowCnst = VariableLowerBoundFunc2D(cFuncNowCnstBase,self.mLvlMinNow)
def defBoroCnst(self,BoroCnstArt)
Defines the constrained portion of the consumption function as cFuncNowCnst, an attribute of self. Parameters ---------- BoroCnstArt : float or None Borrowing constraint for the minimum allowable assets to end the period with. If it is less than the natural borrowing constraint, then it is irrelevant; BoroCnstArt=None indicates no artificial bor- rowing constraint. Returns ------- None
3.135195
2.437148
1.28642
''' Prepare to calculate end-of-period marginal value by creating an array of market resources that the agent could have next period, considering the grid of end-of-period normalized assets, the grid of persistent income levels, and the distribution of shocks he might experience next period. Parameters ---------- None Returns ------- aLvlNow : np.array 2D array of end-of-period assets; also stored as attribute of self. pLvlNow : np.array 2D array of persistent income levels this period. ''' ShkCount = self.TranShkValsNext.size pLvlCount = self.pLvlGrid.size aNrmCount = self.aXtraGrid.size pLvlNow = np.tile(self.pLvlGrid,(aNrmCount,1)).transpose() aLvlNow = np.tile(self.aXtraGrid,(pLvlCount,1))*pLvlNow + self.BoroCnstNat(pLvlNow) pLvlNow_tiled = np.tile(pLvlNow,(ShkCount,1,1)) aLvlNow_tiled = np.tile(aLvlNow,(ShkCount,1,1)) # shape = (ShkCount,pLvlCount,aNrmCount) if self.pLvlGrid[0] == 0.0: # aLvl turns out badly if pLvl is 0 at bottom aLvlNow[0,:] = self.aXtraGrid aLvlNow_tiled[:,0,:] = np.tile(self.aXtraGrid,(ShkCount,1)) # Tile arrays of the income shocks and put them into useful shapes PermShkVals_tiled = np.transpose(np.tile(self.PermShkValsNext,(aNrmCount,pLvlCount,1)),(2,1,0)) TranShkVals_tiled = np.transpose(np.tile(self.TranShkValsNext,(aNrmCount,pLvlCount,1)),(2,1,0)) ShkPrbs_tiled = np.transpose(np.tile(self.ShkPrbsNext,(aNrmCount,pLvlCount,1)),(2,1,0)) # Get cash on hand next period pLvlNext = self.pLvlNextFunc(pLvlNow_tiled)*PermShkVals_tiled mLvlNext = self.Rfree*aLvlNow_tiled + pLvlNext*TranShkVals_tiled # Store and report the results self.ShkPrbs_temp = ShkPrbs_tiled self.pLvlNext = pLvlNext self.mLvlNext = mLvlNext self.aLvlNow = aLvlNow return aLvlNow, pLvlNow
def prepareToCalcEndOfPrdvP(self)
Prepare to calculate end-of-period marginal value by creating an array of market resources that the agent could have next period, considering the grid of end-of-period normalized assets, the grid of persistent income levels, and the distribution of shocks he might experience next period. Parameters ---------- None Returns ------- aLvlNow : np.array 2D array of end-of-period assets; also stored as attribute of self. pLvlNow : np.array 2D array of persistent income levels this period.
3.15658
2.159738
1.461557
''' Calculates end-of-period marginal value of assets at each state space point in aLvlNow x pLvlNow. Does so by taking a weighted sum of next period marginal values across income shocks (in preconstructed grids self.mLvlNext x self.pLvlNext). Parameters ---------- None Returns ------- EndOfPrdVP : np.array A 2D array of end-of-period marginal value of assets. ''' EndOfPrdvP = self.DiscFacEff*self.Rfree*np.sum(self.vPfuncNext(self.mLvlNext,self.pLvlNext)*self.ShkPrbs_temp,axis=0) return EndOfPrdvP
def calcEndOfPrdvP(self)
Calculates end-of-period marginal value of assets at each state space point in aLvlNow x pLvlNow. Does so by taking a weighted sum of next period marginal values across income shocks (in preconstructed grids self.mLvlNext x self.pLvlNext). Parameters ---------- None Returns ------- EndOfPrdVP : np.array A 2D array of end-of-period marginal value of assets.
7.055632
1.834329
3.846438
''' Construct the end-of-period value function for this period, storing it as an attribute of self for use by other methods. Parameters ---------- EndOfPrdvP : np.array Array of end-of-period marginal value of assets corresponding to the asset values in self.aLvlNow x self.pLvlGrid. Returns ------- none ''' vLvlNext = self.vFuncNext(self.mLvlNext,self.pLvlNext) # value in many possible future states EndOfPrdv = self.DiscFacEff*np.sum(vLvlNext*self.ShkPrbs_temp,axis=0) # expected value, averaging across states EndOfPrdvNvrs = self.uinv(EndOfPrdv) # value transformed through inverse utility EndOfPrdvNvrsP = EndOfPrdvP*self.uinvP(EndOfPrdv) # Add points at mLvl=zero EndOfPrdvNvrs = np.concatenate((np.zeros((self.pLvlGrid.size,1)),EndOfPrdvNvrs),axis=1) if hasattr(self,'MedShkDstn'): EndOfPrdvNvrsP = np.concatenate((np.zeros((self.pLvlGrid.size,1)),EndOfPrdvNvrsP),axis=1) else: EndOfPrdvNvrsP = np.concatenate((np.reshape(EndOfPrdvNvrsP[:,0],(self.pLvlGrid.size,1)),EndOfPrdvNvrsP),axis=1) # This is a very good approximation, vNvrsPP = 0 at the asset minimum aLvl_temp = np.concatenate((np.reshape(self.BoroCnstNat(self.pLvlGrid),(self.pLvlGrid.size,1)),self.aLvlNow),axis=1) # Make an end-of-period value function for each persistent income level in the grid EndOfPrdvNvrsFunc_list = [] for p in range(self.pLvlGrid.size): EndOfPrdvNvrsFunc_list.append(CubicInterp(aLvl_temp[p,:]-self.BoroCnstNat(self.pLvlGrid[p]),EndOfPrdvNvrs[p,:],EndOfPrdvNvrsP[p,:])) EndOfPrdvNvrsFuncBase = LinearInterpOnInterp1D(EndOfPrdvNvrsFunc_list,self.pLvlGrid) # Re-adjust the combined end-of-period value function to account for the natural borrowing constraint shifter EndOfPrdvNvrsFunc = VariableLowerBoundFunc2D(EndOfPrdvNvrsFuncBase,self.BoroCnstNat) self.EndOfPrdvFunc = ValueFunc2D(EndOfPrdvNvrsFunc,self.CRRA)
def makeEndOfPrdvFunc(self,EndOfPrdvP)
Construct the end-of-period value function for this period, storing it as an attribute of self for use by other methods. Parameters ---------- EndOfPrdvP : np.array Array of end-of-period marginal value of assets corresponding to the asset values in self.aLvlNow x self.pLvlGrid. Returns ------- none
3.74056
3.056656
1.223742
''' Finds endogenous interpolation points (c,m) for the consumption function. Parameters ---------- EndOfPrdvP : np.array Array of end-of-period marginal values. aLvlNow : np.array Array of end-of-period asset values that yield the marginal values in EndOfPrdvP. Returns ------- c_for_interpolation : np.array Consumption points for interpolation. m_for_interpolation : np.array Corresponding market resource points for interpolation. ''' cLvlNow = self.uPinv(EndOfPrdvP) mLvlNow = cLvlNow + aLvlNow # Limiting consumption is zero as m approaches mNrmMin c_for_interpolation = np.concatenate((np.zeros((self.pLvlGrid.size,1)),cLvlNow),axis=-1) m_for_interpolation = np.concatenate((self.BoroCnstNat(np.reshape(self.pLvlGrid,(self.pLvlGrid.size,1))),mLvlNow),axis=-1) # Limiting consumption is MPCmin*mLvl as p approaches 0 m_temp = np.reshape(m_for_interpolation[0,:],(1,m_for_interpolation.shape[1])) m_for_interpolation = np.concatenate((m_temp,m_for_interpolation),axis=0) c_for_interpolation = np.concatenate((self.MPCminNow*m_temp,c_for_interpolation),axis=0) return c_for_interpolation, m_for_interpolation
def getPointsForInterpolation(self,EndOfPrdvP,aLvlNow)
Finds endogenous interpolation points (c,m) for the consumption function. Parameters ---------- EndOfPrdvP : np.array Array of end-of-period marginal values. aLvlNow : np.array Array of end-of-period asset values that yield the marginal values in EndOfPrdvP. Returns ------- c_for_interpolation : np.array Consumption points for interpolation. m_for_interpolation : np.array Corresponding market resource points for interpolation.
3.43346
2.300444
1.49252
''' Constructs a basic solution for this period, including the consumption function and marginal value function. Parameters ---------- cLvl : np.array Consumption points for interpolation. mLvl : np.array Corresponding market resource points for interpolation. pLvl : np.array Corresponding persistent income level points for interpolation. interpolator : function A function that constructs and returns a consumption function. Returns ------- solution_now : ConsumerSolution The solution to this period's consumption-saving problem, with a consumption function, marginal value function, and minimum m. ''' # Construct the unconstrained consumption function cFuncNowUnc = interpolator(mLvl,pLvl,cLvl) # Combine the constrained and unconstrained functions into the true consumption function cFuncNow = LowerEnvelope2D(cFuncNowUnc,self.cFuncNowCnst) # Make the marginal value function vPfuncNow = self.makevPfunc(cFuncNow) # Pack up the solution and return it solution_now = ConsumerSolution(cFunc=cFuncNow, vPfunc=vPfuncNow, mNrmMin=0.0) return solution_now
def usePointsForInterpolation(self,cLvl,mLvl,pLvl,interpolator)
Constructs a basic solution for this period, including the consumption function and marginal value function. Parameters ---------- cLvl : np.array Consumption points for interpolation. mLvl : np.array Corresponding market resource points for interpolation. pLvl : np.array Corresponding persistent income level points for interpolation. interpolator : function A function that constructs and returns a consumption function. Returns ------- solution_now : ConsumerSolution The solution to this period's consumption-saving problem, with a consumption function, marginal value function, and minimum m.
4.35387
2.034942
2.139555
''' Given end of period assets and end of period marginal value, construct the basic solution for this period. Parameters ---------- EndOfPrdvP : np.array Array of end-of-period marginal values. aLvl : np.array Array of end-of-period asset values that yield the marginal values in EndOfPrdvP. pLvl : np.array Array of persistent income levels that yield the marginal values in EndOfPrdvP (corresponding pointwise to aLvl). interpolator : function A function that constructs and returns a consumption function. Returns ------- solution_now : ConsumerSolution The solution to this period's consumption-saving problem, with a consumption function, marginal value function, and minimum m. ''' cLvl,mLvl = self.getPointsForInterpolation(EndOfPrdvP,aLvl) pLvl_temp = np.concatenate((np.reshape(self.pLvlGrid,(self.pLvlGrid.size,1)),pLvl),axis=-1) pLvl_temp = np.concatenate((np.zeros((1,mLvl.shape[1])),pLvl_temp)) solution_now = self.usePointsForInterpolation(cLvl,mLvl,pLvl_temp,interpolator) return solution_now
def makeBasicSolution(self,EndOfPrdvP,aLvl,pLvl,interpolator)
Given end of period assets and end of period marginal value, construct the basic solution for this period. Parameters ---------- EndOfPrdvP : np.array Array of end-of-period marginal values. aLvl : np.array Array of end-of-period asset values that yield the marginal values in EndOfPrdvP. pLvl : np.array Array of persistent income levels that yield the marginal values in EndOfPrdvP (corresponding pointwise to aLvl). interpolator : function A function that constructs and returns a consumption function. Returns ------- solution_now : ConsumerSolution The solution to this period's consumption-saving problem, with a consumption function, marginal value function, and minimum m.
3.660952
1.729243
2.117084