text_prompt
stringlengths
157
13.1k
code_prompt
stringlengths
7
19.8k
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def delFromTimeInv(self,*params): ''' Removes any number of parameters from time_inv for this instance. Parameters ---------- params : string Any number of strings naming attributes to be removed from time_inv Returns ------- None ''' for param in params: if param in self.time_inv: self.time_inv.remove(param)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def solve(self,verbose=False): ''' Solve the model for this instance of an agent type by backward induction. Loops through the sequence of one period problems, passing the solution from period t+1 to the problem for period t. Parameters ---------- verbose : boolean If True, solution progress is printed to screen. Returns ------- none ''' # Ignore floating point "errors". Numpy calls it "errors", but really it's excep- # tions with well-defined answers such as 1.0/0.0 that is np.inf, -1.0/0.0 that is # -np.inf, np.inf/np.inf is np.nan and so on. with np.errstate(divide='ignore', over='ignore', under='ignore', invalid='ignore'): self.preSolve() # Do pre-solution stuff self.solution = solveAgent(self,verbose) # Solve the model by backward induction if self.time_flow: # Put the solution in chronological order if this instance's time flow runs that way self.solution.reverse() self.addToTimeVary('solution') # Add solution to the list of time-varying attributes self.postSolve()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def checkElementsOfTimeVaryAreLists(self): """ A method to check that elements of time_vary are lists. """
for param in self.time_vary: assert type(getattr(self,param))==list,param + ' is not a list, but should be' + \ ' because it is in time_vary'
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def simDeath(self): ''' Determines which agents in the current population "die" or should be replaced. Takes no inputs, returns a Boolean array of size self.AgentCount, which has True for agents who die and False for those that survive. Returns all False by default, must be overwritten by a subclass to have replacement events. Parameters ---------- None Returns ------- who_dies : np.array Boolean array of size self.AgentCount indicating which agents die and are replaced. ''' print('AgentType subclass must define method simDeath!') who_dies = np.ones(self.AgentCount,dtype=bool) return who_dies
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def solveAgents(self): ''' Solves the microeconomic problem for all AgentTypes in this market. Parameters ---------- None Returns ------- None ''' #for this_type in self.agents: # this_type.solve() try: multiThreadCommands(self.agents,['solve()']) except Exception as err: if self.print_parallel_error_once: # Set flag to False so this is only printed once. self.print_parallel_error_once = False print("**** WARNING: could not execute multiThreadCommands in HARK.core.Market.solveAgents(), so using the serial version instead. This will likely be slower. The multiTreadCommands() functions failed with the following error:", '\n ', sys.exc_info()[0], ':', err) #sys.exc_info()[0]) multiThreadCommandsFake(self.agents,['solve()'])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def solve(self): ''' "Solves" the market by finding a "dynamic rule" that governs the aggregate market state such that when agents believe in these dynamics, their actions collectively generate the same dynamic rule. Parameters ---------- None Returns ------- None ''' go = True max_loops = self.max_loops # Failsafe against infinite solution loop completed_loops = 0 old_dynamics = None while go: # Loop until the dynamic process converges or we hit the loop cap self.solveAgents() # Solve each AgentType's micro problem self.makeHistory() # "Run" the model while tracking aggregate variables new_dynamics = self.updateDynamics() # Find a new aggregate dynamic rule # Check to see if the dynamic rule has converged (if this is not the first loop) if completed_loops > 0: distance = new_dynamics.distance(old_dynamics) else: distance = 1000000.0 # Move to the next loop if the terminal conditions are not met old_dynamics = new_dynamics completed_loops += 1 go = distance >= self.tolerance and completed_loops < max_loops self.dynamics = new_dynamics
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def reap(self): ''' Collects attributes named in reap_vars from each AgentType in the market, storing them in respectively named attributes of self. Parameters ---------- none Returns ------- none ''' for var_name in self.reap_vars: harvest = [] for this_type in self.agents: harvest.append(getattr(this_type,var_name)) setattr(self,var_name,harvest)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def sow(self): ''' Distributes attrributes named in sow_vars from self to each AgentType in the market, storing them in respectively named attributes. Parameters ---------- none Returns ------- none ''' for var_name in self.sow_vars: this_seed = getattr(self,var_name) for this_type in self.agents: setattr(this_type,var_name,this_seed)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def mill(self): ''' Processes the variables collected from agents using the function millRule, storing the results in attributes named in aggr_sow. Parameters ---------- none Returns ------- none ''' # Make a dictionary of inputs for the millRule reap_vars_string = '' for name in self.reap_vars: reap_vars_string += ' \'' + name + '\' : self.' + name + ',' const_vars_string = '' for name in self.const_vars: const_vars_string += ' \'' + name + '\' : self.' + name + ',' mill_dict = eval('{' + reap_vars_string + const_vars_string + '}') # Run the millRule and store its output in self product = self.millRule(**mill_dict) for j in range(len(self.sow_vars)): this_var = self.sow_vars[j] this_product = getattr(product,this_var) setattr(self,this_var,this_product)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def store(self): ''' Record the current value of each variable X named in track_vars in an attribute named X_hist. Parameters ---------- none Returns ------- none ''' for var_name in self.track_vars: value_now = getattr(self,var_name) getattr(self,var_name + '_hist').append(value_now)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def updateDynamics(self): ''' Calculates a new "aggregate dynamic rule" using the history of variables named in track_vars, and distributes this rule to AgentTypes in agents. Parameters ---------- none Returns ------- dynamics : instance The new "aggregate dynamic rule" that agents believe in and act on. Should have attributes named in dyn_vars. ''' # Make a dictionary of inputs for the dynamics calculator history_vars_string = '' arg_names = list(getArgNames(self.calcDynamics)) if 'self' in arg_names: arg_names.remove('self') for name in arg_names: history_vars_string += ' \'' + name + '\' : self.' + name + '_hist,' update_dict = eval('{' + history_vars_string + '}') # Calculate a new dynamic rule and distribute it to the agents in agent_list dynamics = self.calcDynamics(**update_dict) # User-defined dynamics calculator for var_name in self.dyn_vars: this_obj = getattr(dynamics,var_name) for this_type in self.agents: setattr(this_type,var_name,this_obj) return dynamics
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def getArgNames(function): ''' Returns a list of strings naming all of the arguments for the passed function. Parameters ---------- function : function A function whose argument names are wanted. Returns ------- argNames : [string] The names of the arguments of function. ''' argCount = function.__code__.co_argcount argNames = function.__code__.co_varnames[:argCount] return argNames
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def approxMeanOneLognormal(N, sigma=1.0, **kwargs): ''' Calculate a discrete approximation to a mean one lognormal distribution. Based on function approxLognormal; see that function's documentation for further notes. Parameters ---------- N : int Size of discrete space vector to be returned. sigma : float standard deviation associated with underlying normal probability distribution. Returns ------- X : np.array Discrete points for discrete probability mass function. pmf : np.array Probability associated with each point in X. Written by Nathan M. Palmer Based on Matab function "setup_shocks.m," from Chris Carroll's [Solution Methods for Microeconomic Dynamic Optimization Problems] (http://www.econ2.jhu.edu/people/ccarroll/solvingmicrodsops/) toolkit. Latest update: 01 May 2015 ''' mu_adj = - 0.5*sigma**2; pmf,X = approxLognormal(N=N, mu=mu_adj, sigma=sigma, **kwargs) return [pmf,X]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def approxBeta(N,a=1.0,b=1.0): ''' Calculate a discrete approximation to the beta distribution. May be quite slow, as it uses a rudimentary numeric integration method to generate the discrete approximation. Parameters ---------- N : int Size of discrete space vector to be returned. a : float First shape parameter (sometimes called alpha). b : float Second shape parameter (sometimes called beta). Returns ------- X : np.array Discrete points for discrete probability mass function. pmf : np.array Probability associated with each point in X. ''' P = 1000 vals = np.reshape(stats.beta.ppf(np.linspace(0.0,1.0,N*P),a,b),(N,P)) X = np.mean(vals,axis=1) pmf = np.ones(N)/float(N) return( [pmf, X] )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def approxUniform(N,bot=0.0,top=1.0): ''' Makes a discrete approximation to a uniform distribution, given its bottom and top limits and number of points. Parameters ---------- N : int The number of points in the discrete approximation bot : float The bottom of the uniform distribution top : float The top of the uniform distribution Returns ------- (unnamed) : np.array An equiprobable discrete approximation to the uniform distribution. ''' pmf = np.ones(N)/float(N) center = (top+bot)/2.0 width = (top-bot)/2.0 X = center + width*np.linspace(-(N-1.0)/2.0,(N-1.0)/2.0,N)/(N/2.0) return [pmf,X]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def addDiscreteOutcomeConstantMean(distribution, x, p, sort = False): ''' Adds a discrete outcome of x with probability p to an existing distribution, holding constant the relative probabilities of other outcomes and overall mean. Parameters ---------- distribution : [np.array] Two element list containing a list of probabilities and a list of outcomes. x : float The new value to be added to the distribution. p : float The probability of the discrete outcome x occuring. sort: bool Whether or not to sort X before returning it Returns ------- X : np.array Discrete points for discrete probability mass function. pmf : np.array Probability associated with each point in X. Written by Matthew N. White Latest update: 08 December 2015 by David Low ''' X = np.append(x,distribution[1]*(1-p*x)/(1-p)) pmf = np.append(p,distribution[0]*(1-p)) if sort: indices = np.argsort(X) X = X[indices] pmf = pmf[indices] return([pmf,X])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def makeGridExpMult(ming, maxg, ng, timestonest=20): ''' Make a multi-exponentially spaced grid. Parameters ---------- ming : float Minimum value of the grid maxg : float Maximum value of the grid ng : int The number of grid points timestonest : int the number of times to nest the exponentiation Returns ------- points : np.array A multi-exponentially spaced grid Original Matab code can be found in Chris Carroll's [Solution Methods for Microeconomic Dynamic Optimization Problems] (http://www.econ2.jhu.edu/people/ccarroll/solvingmicrodsops/) toolkit. Latest update: 01 May 2015 ''' if timestonest > 0: Lming = ming Lmaxg = maxg for j in range(timestonest): Lming = np.log(Lming + 1) Lmaxg = np.log(Lmaxg + 1) Lgrid = np.linspace(Lming,Lmaxg,ng) grid = Lgrid for j in range(timestonest): grid = np.exp(grid) - 1 else: Lming = np.log(ming) Lmaxg = np.log(maxg) Lstep = (Lmaxg - Lming)/(ng - 1) Lgrid = np.arange(Lming,Lmaxg+0.000001,Lstep) grid = np.exp(Lgrid) return(grid)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def calcWeightedAvg(data,weights): ''' Generates a weighted average of simulated data. The Nth row of data is averaged and then weighted by the Nth element of weights in an aggregate average. Parameters ---------- data : numpy.array An array of data with N rows of J floats weights : numpy.array A length N array of weights for the N rows of data. Returns ------- weighted_sum : float The weighted sum of the data. ''' data_avg = np.mean(data,axis=1) weighted_sum = np.dot(data_avg,weights) return weighted_sum
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def kernelRegression(x,y,bot=None,top=None,N=500,h=None): ''' Performs a non-parametric Nadaraya-Watson 1D kernel regression on given data with optionally specified range, number of points, and kernel bandwidth. Parameters ---------- x : np.array The independent variable in the kernel regression. y : np.array The dependent variable in the kernel regression. bot : float Minimum value of interest in the regression; defaults to min(x). top : float Maximum value of interest in the regression; defaults to max(y). N : int Number of points to compute. h : float The bandwidth of the (Epanechnikov) kernel. To-do: GENERALIZE. Returns ------- regression : LinearInterp A piecewise locally linear kernel regression: y = f(x). ''' # Fix omitted inputs if bot is None: bot = np.min(x) if top is None: top = np.max(x) if h is None: h = 2.0*(top - bot)/float(N) # This is an arbitrary default # Construct a local linear approximation x_vec = np.linspace(bot,top,num=N) y_vec = np.zeros_like(x_vec) + np.nan for j in range(N): x_here = x_vec[j] weights = epanechnikovKernel(x,x_here,h) y_vec[j] = np.dot(weights,y)/np.sum(weights) regression = interp1d(x_vec,y_vec,bounds_error=False,assume_sorted=True) return regression
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def epanechnikovKernel(x,ref_x,h=1.0): ''' The Epanechnikov kernel. Parameters ---------- x : np.array Values at which to evaluate the kernel x_ref : float The reference point h : float Kernel bandwidth Returns ------- out : np.array Kernel values at each value of x ''' u = (x-ref_x)/h # Normalize distance by bandwidth these = np.abs(u) <= 1.0 # Kernel = 0 outside [-1,1] out = np.zeros_like(x) # Initialize kernel output out[these] = 0.75*(1.0-u[these]**2.0) # Evaluate kernel return out
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def runStickyEregressionsInStata(infile_name,interval_size,meas_err,sticky,all_specs,stata_exe): ''' Runs regressions for the main tables of the StickyC paper in Stata and produces a LaTeX table with results for one "panel". Running in Stata allows production of the KP-statistic, for which there is currently no command in statsmodels.api. Parameters ---------- infile_name : str Name of tab-delimited text file with simulation data. Assumed to be in the results directory, and was almost surely generated by makeStickyEdataFile unless we resort to fabricating simulated data. THAT'S A JOKE, FUTURE REFEREES. interval_size : int Number of periods in each regression sample (or interval). meas_err : bool Indicator for whether to add measurement error to DeltaLogC. sticky : bool Indicator for whether these results used sticky expectations. all_specs : bool Indicator for whether this panel should include all specifications or just the OLS on lagged consumption growth. stata_exe : str Absolute location where the Stata executable can be found on the computer running this code. Usually set at the top of StickyEparams.py. Returns ------- panel_text : str String with one panel's worth of LaTeX input. ''' dofile = "StickyETimeSeries.do" infile_name_full = os.path.abspath(results_dir + infile_name + ".txt") temp_name_full = os.path.abspath(results_dir + "temp.txt") if meas_err: meas_err_stata = 1 else: meas_err_stata = 0 # Define the command to run the Stata do file cmd = [stata_exe, "do", dofile, infile_name_full, temp_name_full, str(interval_size), str(meas_err_stata)] # Run Stata do-file stata_status = subprocess.call(cmd,shell = 'true') if stata_status!=0: raise ValueError('Stata code could not run. Check the stata_exe in StickyEparams.py') stata_output = pd.read_csv(temp_name_full, sep=',',header=0) # Make results table and return it panel_text = makeResultsPanel(Coeffs=stata_output.CoeffsArray, StdErrs=stata_output.StdErrArray, Rsq=stata_output.RsqArray, Pvals=stata_output.PvalArray, OID=stata_output.OIDarray, Counts=stata_output.ExtraInfo, meas_err=meas_err, sticky=sticky, all_specs=all_specs) return panel_text
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def calcValueAtBirth(cLvlHist,BirthBool,PlvlHist,MrkvHist,DiscFac,CRRA): ''' Calculate expected value of being born in each Markov state using the realizations of consumption for a history of many consumers. The histories should already be trimmed of the "burn in" periods. Parameters ---------- cLvlHist : np.array TxN array of consumption level history for many agents across many periods. Agents who die are replaced by newborms. BirthBool : np.array TxN boolean array indicating when agents are born, replacing one who died. PlvlHist : np.array T length vector of aggregate permanent productivity levels. MrkvHist : np.array T length vector of integers for the Markov index in each period. DiscFac : float Intertemporal discount factor. CRRA : float Coefficient of relative risk aversion. Returns ------- vAtBirth : np.array J length vector of average lifetime value at birth by Markov state. ''' J = np.max(MrkvHist) + 1 # Number of Markov states T = MrkvHist.size # Length of simulation I = cLvlHist.shape[1] # Number of agent indices in histories u = lambda c : CRRAutility(c,gam=CRRA) # Initialize an array to hold each agent's lifetime utility BirthsByPeriod = np.sum(BirthBool,axis=1) BirthsByState = np.zeros(J,dtype=int) for j in range(J): these = MrkvHist == j BirthsByState[j] = np.sum(BirthsByPeriod[these]) N = np.max(BirthsByState) # Array must hold this many agents per row at least vArray = np.zeros((J,N)) + np.nan n = np.zeros(J,dtype=int) # Loop through each agent index DiscVec = DiscFac**np.arange(T) for i in range(I): birth_t = np.where(BirthBool[:,i])[0] # Loop through each agent who lived and died in this index for k in range(birth_t.size-1): # Last birth event has no death, so ignore # Get lifespan of this agent and circumstances at birth t0 = birth_t[k] t1 = birth_t[k+1] span = t1-t0 j = MrkvHist[t0] # Calculate discounted flow of utility for this agent and store it cVec = cLvlHist[t0:t1,i]/PlvlHist[t0] uVec = u(cVec) v = np.dot(DiscVec[:span],uVec) vArray[j,n[j]] = v n[j] += 1 # Calculate expected value at birth by state and return it vAtBirth = np.nanmean(vArray,axis=1) return vAtBirth
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def makeResultsTable(caption,panels,counts,filename,label): ''' Make a time series regression results table by piecing together one or more panels. Saves a tex file to disk in the tables directory. Parameters ---------- caption : str or None Text to apply at the start of the table as a title. If None, the table environment is not invoked and the output is formatted for slides. panels : [str] List of strings with one or more panels, usually made by makeResultsPanel. counts : int List of two integers: [interval_length, interval_count] filename : str Name of the file in which to save output (in the ./Tables/ directory). label : str LaTeX \label, for internal reference in the paper text. Returns ------- None ''' if caption is not None: note_size = '\\footnotesize' else: note_size = '\\tiny' note = '\\multicolumn{6}{p{0.95\\textwidth}}{' + note_size + ' \\textbf{Notes:} ' if counts[1] > 1: note += 'Reported statistics are the average values for ' + str(counts[1]) + ' samples of ' + str(counts[0]) + ' simulated quarters each. ' note += 'Bullets indicate that the average sample coefficient divided by average sample standard error is outside of the inner 90\%, 95\%, and 99\% of the standard normal distribution. ' else: note += 'Reported statistics are for a single simulation of ' + str(counts[0]) + ' quarters. ' note += 'Stars indicate statistical significance at the 90\%, 95\%, and 99\% levels, respectively. ' note += 'Instruments $\\textbf{Z}_t = \\{\Delta \log \mathbf{C}_{t-2}, \Delta \log \mathbf{C}_{t-3}, \Delta \log \mathbf{Y}_{t-2}, \Delta \log \mathbf{Y}_{t-3}, A_{t-2}, A_{t-3}, \Delta_8 \log \mathbf{C}_{t-2}, \Delta_8 \log \mathbf{Y}_{t-2} \\}$.' note += '}' if caption is not None: output = '\\begin{minipage}{\\textwidth}\n' output += '\\begin{table} \caption{' + caption + '} \\label{' + label + '} \n' output += ' \\centerline{$ \Delta \log \mathbf{C}_{t+1} = \\varsigma + \chi \Delta \log \mathbf{C}_t + \eta \mathbb{E}_t[\Delta \log \mathbf{Y}_{t+1}] + \\alpha A_t + \epsilon_{t+1} $}\n' else: output = '\\begin{center} \n' output += '$ \Delta \log \mathbf{C}_{t+1} = \\varsigma + \chi \Delta \log \mathbf{C}_t + \eta \mathbb{E}_t[\Delta \log \mathbf{Y}_{t+1}] + \\alpha A_t + \epsilon_{t+1} $ \\\\ \n' output += '\\begin{tabular}{d{4}d{4}d{5}cd{4}c}\n \\toprule \n' output += '\multicolumn{3}{c}{Expectations : Dep Var} & OLS & \multicolumn{1}{c}{2${}^{\\text{nd}}$ Stage} & \multicolumn{1}{c}{KP $p$-val} \n' output += '\\\\ \multicolumn{3}{c}{Independent Variables} & or IV & \multicolumn{1}{c}{$\\bar{R}^{2} $} & \multicolumn{1}{c}{Hansen J $p$-val} \n' for panel in panels: output += panel output += '\\\\ \\bottomrule \n ' + note + '\n' output += '\end{tabular}\n' if caption is not None: output += '\end{table}\n' output += '\end{minipage}\n' else: output += '\end{center}\n' with open(tables_dir + filename + '.tex','w') as f: f.write(output) f.close()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def solveConsPrefShock(solution_next,IncomeDstn,PrefShkDstn, LivPrb,DiscFac,CRRA,Rfree,PermGroFac,BoroCnstArt, aXtraGrid,vFuncBool,CubicBool): ''' Solves a single period of a consumption-saving model with preference shocks to marginal utility. Problem is solved using the method of endogenous gridpoints. Parameters ---------- solution_next : ConsumerSolution The solution to the succeeding 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. PrefShkDstn : [np.array] Discrete distribution of the multiplicative utility shifter. Order: probabilities, preference shocks. LivPrb : float Survival probability; likelihood of being alive at the beginning of the succeeding period. DiscFac : float Intertemporal discount factor for future utility. CRRA : float Coefficient of relative risk aversion. Rfree : float Risk free interest factor on end-of-period assets. PermGroGac : float Expected permanent income growth factor at the end of this period. 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. aXtraGrid: np.array Array of "extra" end-of-period asset values-- assets above the absolute minimum acceptable level. vFuncBool: boolean An indicator for whether the value function should be computed and included in the reported solution. CubicBool: boolean An indicator for whether the solver should use cubic or linear inter- polation. Returns ------- solution: ConsumerSolution The solution to the single period consumption-saving problem. Includes a consumption function cFunc (using linear splines), a marginal value function vPfunc, a minimum acceptable level of normalized market re- sources mNrmMin, normalized human wealth hNrm, and bounding MPCs MPCmin and MPCmax. It might also have a value function vFunc. The consumption function is defined over normalized market resources and the preference shock, c = cFunc(m,PrefShk), but the (marginal) value function is defined unconditionally on the shock, just before it is revealed. ''' solver = ConsPrefShockSolver(solution_next,IncomeDstn,PrefShkDstn,LivPrb, DiscFac,CRRA,Rfree,PermGroFac,BoroCnstArt,aXtraGrid, vFuncBool,CubicBool) solver.prepareToSolve() solution = solver.solve() return solution
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def solveConsKinkyPref(solution_next,IncomeDstn,PrefShkDstn, LivPrb,DiscFac,CRRA,Rboro,Rsave,PermGroFac,BoroCnstArt, aXtraGrid,vFuncBool,CubicBool): ''' Solves a single period of a consumption-saving model with preference shocks to marginal utility and a different interest rate on saving vs borrowing. Problem is solved using the method of endogenous gridpoints. Parameters ---------- solution_next : ConsumerSolution The solution to the succeeding 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. PrefShkDstn : [np.array] Discrete distribution of the multiplicative utility shifter. Order: probabilities, preference shocks. LivPrb : float Survival probability; likelihood of being alive at the beginning of the succeeding period. DiscFac : float Intertemporal discount factor for future utility. CRRA : float Coefficient of relative risk aversion. Rboro: float Interest factor on assets between this period and the succeeding period when assets are negative. Rsave: float Interest factor on assets between this period and the succeeding period when assets are positive. PermGroGac : float Expected permanent income growth factor at the end of this period. 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. aXtraGrid: np.array Array of "extra" end-of-period asset values-- assets above the absolute minimum acceptable level. vFuncBool: boolean An indicator for whether the value function should be computed and included in the reported solution. CubicBool: boolean An indicator for whether the solver should use cubic or linear inter- polation. Returns ------- solution: ConsumerSolution The solution to the single period consumption-saving problem. Includes a consumption function cFunc (using linear splines), a marginal value function vPfunc, a minimum acceptable level of normalized market re- sources mNrmMin, normalized human wealth hNrm, and bounding MPCs MPCmin and MPCmax. It might also have a value function vFunc. The consumption function is defined over normalized market resources and the preference shock, c = cFunc(m,PrefShk), but the (marginal) value function is defined unconditionally on the shock, just before it is revealed. ''' solver = ConsKinkyPrefSolver(solution_next,IncomeDstn,PrefShkDstn,LivPrb, DiscFac,CRRA,Rboro,Rsave,PermGroFac,BoroCnstArt, aXtraGrid,vFuncBool,CubicBool) solver.prepareToSolve() solution = solver.solve() return solution
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def getShocks(self): ''' Gets permanent and transitory income shocks for this period as well as preference shocks. Parameters ---------- None Returns ------- None ''' IndShockConsumerType.getShocks(self) # Get permanent and transitory income shocks PrefShkNow = np.zeros(self.AgentCount) # Initialize shock array for t in range(self.T_cycle): these = t == self.t_cycle N = np.sum(these) if N > 0: PrefShkNow[these] = self.RNG.permutation(approxMeanOneLognormal(N,sigma=self.PrefShkStd[t])[1]) self.PrefShkNow = PrefShkNow
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def getPointsForInterpolation(self,EndOfPrdvP,aNrmNow): ''' Find endogenous interpolation points for each asset point and each discrete preference shock. Parameters ---------- EndOfPrdvP : np.array Array of end-of-period marginal values. aNrmNow : 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. ''' c_base = self.uPinv(EndOfPrdvP) PrefShkCount = self.PrefShkVals.size PrefShk_temp = np.tile(np.reshape(self.PrefShkVals**(1.0/self.CRRA),(PrefShkCount,1)), (1,c_base.size)) self.cNrmNow = np.tile(c_base,(PrefShkCount,1))*PrefShk_temp self.mNrmNow = self.cNrmNow + np.tile(aNrmNow,(PrefShkCount,1)) # Add the bottom point to the c and m arrays m_for_interpolation = np.concatenate((self.BoroCnstNat*np.ones((PrefShkCount,1)), self.mNrmNow),axis=1) c_for_interpolation = np.concatenate((np.zeros((PrefShkCount,1)),self.cNrmNow),axis=1) return c_for_interpolation,m_for_interpolation
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def simBirth(self,which_agents): ''' Makes new consumers for the given indices. Slightly extends base method by also setting pLvlErrNow = 1.0 for new agents, indicating that they correctly perceive their productivity. Parameters ---------- which_agents : np.array(Bool) Boolean array of size self.AgentCount indicating which agents should be "born". Returns ------- None ''' AggShockConsumerType.simBirth(self,which_agents) if hasattr(self,'pLvlErrNow'): self.pLvlErrNow[which_agents] = 1.0 else: self.pLvlErrNow = np.ones(self.AgentCount)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def getUpdaters(self): ''' Determine which agents update this period vs which don't. Fills in the attributes update and dont as boolean arrays of size AgentCount. Parameters ---------- None Returns ------- None ''' how_many_update = int(round(self.UpdatePrb*self.AgentCount)) base_bool = np.zeros(self.AgentCount,dtype=bool) base_bool[0:how_many_update] = True self.update = self.RNG.permutation(base_bool) self.dont = np.logical_not(self.update)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def getStates(self): ''' Gets simulated consumers pLvl and mNrm for this period, but with the alteration that these represent perceived rather than actual values. Also calculates mLvlTrue, the true level of market resources that the individual has on hand. Parameters ---------- None Returns ------- None ''' # Update consumers' perception of their permanent income level pLvlPrev = self.pLvlNow self.pLvlNow = pLvlPrev*self.PermShkNow # Perceived permanent income level (only correct if macro state is observed this period) self.PlvlAggNow *= self.PermShkAggNow # Updated aggregate permanent productivity level self.pLvlTrue = self.pLvlNow*self.pLvlErrNow # Calculate what the consumers perceive their normalized market resources to be RfreeNow = self.getRfree() bLvlNow = RfreeNow*self.aLvlNow # This is the true level yLvlNow = self.pLvlTrue*self.TranShkNow # This is true income level mLvlTrueNow = bLvlNow + yLvlNow # This is true market resource level mNrmPcvdNow = mLvlTrueNow/self.pLvlNow # This is perceived normalized resources self.mNrmNow = mNrmPcvdNow self.mLvlTrueNow = mLvlTrueNow self.yLvlNow = yLvlNow
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def getUpdaters(self): ''' Determine which agents update this period vs which don't. Fills in the attributes update and dont as boolean arrays of size AgentCount. This version also updates perceptions of the Markov state. Parameters ---------- None Returns ------- None ''' StickyEconsumerType.getUpdaters(self) # Only updaters change their perception of the Markov state if hasattr(self,'MrkvNowPcvd'): self.MrkvNowPcvd[self.update] = self.MrkvNow else: # This only triggers in the first simulated period self.MrkvNowPcvd = np.ones(self.AgentCount,dtype=int)*self.MrkvNow
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def getpLvlError(self): ''' Calculates and returns the misperception of this period's shocks. Updaters have no misperception this period, while those who don't update don't see the value of the aggregate permanent shock and thus base their belief about aggregate growth on the last Markov state that they actually observed, which is stored in MrkvNowPcvd. Parameters ---------- None Returns ------- pLvlErr : np.array Array of size AgentCount with this period's (new) misperception. ''' pLvlErr = np.ones(self.AgentCount) pLvlErr[self.dont] = self.PermShkAggNow/self.PermGroFacAgg[self.MrkvNowPcvd[self.dont]] return pLvlErr
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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. Parameters ---------- which_agents : np.array(Bool) Boolean array of size self.AgentCount indicating which agents should be "born". Returns ------- None ''' super(self.__class__,self).simBirth(which_agents) if self.t_sim == 0: # Make sure that pLvlTrue and aLvlNow exist self.pLvlTrue = np.ones(self.AgentCount) self.aLvlNow = self.aNrmNow*self.pLvlTrue
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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 ''' 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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 ''' 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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 ''' for agent in agent_list: for command in command_list: exec('agent.' + command)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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 ''' 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]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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. ''' # 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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. ''' # 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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. ''' 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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 ''' # 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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 ''' # 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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. ''' # Nobody dies in this model which_agents = np.zeros(self.AgentCount,dtype=bool) return which_agents
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def getShocks(self): ''' 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def getStates(self): ''' Calculate market resources for all agents this period. Parameters ---------- None Returns ------- None ''' self.bLvlNow = self.Rfree*self.aLvlNow self.mLvlNow = self.bLvlNow + self.eStateNow
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def getControls(self): ''' 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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). ''' 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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). ''' 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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). ''' 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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 ''' self.updateIncomeProcess() self.updateAssetsGrid() self.updatepLvlNextFunc() self.updatepLvlGrid() self.updateMedShockProcess() self.updateSolutionTerminal()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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 ''' 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')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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 ''' 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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 ''' 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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. ''' 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def solve(self): ''' Solve the one period problem of the consumption-saving model with a Markov state. Parameters ---------- none Returns ------- solution : ConsumerSolution The solution to the single period consumption-saving problem. Includes a consumption function cFunc (using cubic or linear splines), a marg- inal value function vPfunc, a minimum acceptable level of normalized market resources mNrmMin, normalized human wealth hNrm, and bounding MPCs MPCmin and MPCmax. It might also have a value function vFunc and marginal marginal value function vPPfunc. All of these attributes are lists or arrays, 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. ''' # Find the natural borrowing constraint in each current state self.defBoundary() # Initialize end-of-period (marginal) value functions self.EndOfPrdvFunc_list = [] self.EndOfPrdvPfunc_list = [] self.ExIncNextAll = np.zeros(self.StateCount) + np.nan # expected income conditional on the next state self.WorstIncPrbAll = np.zeros(self.StateCount) + np.nan # probability of getting the worst income shock in each next period state # Loop through each next-period-state and calculate the end-of-period # (marginal) value function for j in range(self.StateCount): # Condition values on next period's state (and record a couple for later use) self.conditionOnState(j) self.ExIncNextAll[j] = np.dot(self.ShkPrbsNext,self.PermShkValsNext*self.TranShkValsNext) self.WorstIncPrbAll[j] = self.WorstIncPrb # Construct the end-of-period marginal value function conditional # on next period's state and add it to the list of value functions EndOfPrdvPfunc_cond = self.makeEndOfPrdvPfuncCond() self.EndOfPrdvPfunc_list.append(EndOfPrdvPfunc_cond) # Construct the end-of-period value functional conditional on next # period's state and add it to the list of value functions if self.vFuncBool: EndOfPrdvFunc_cond = self.makeEndOfPrdvFuncCond() self.EndOfPrdvFunc_list.append(EndOfPrdvFunc_cond) # EndOfPrdvP_cond is EndOfPrdvP conditional on *next* period's state. # Take expectations to get EndOfPrdvP conditional on *this* period's state. self.calcEndOfPrdvP() # Calculate the bounding MPCs and PDV of human wealth for each state self.calcHumWealthAndBoundingMPCs() # Find consumption and market resources corresponding to each end-of-period # assets point for each state (and add an additional point at the lower bound) aNrm = np.asarray(self.aXtraGrid)[np.newaxis,:] + np.array(self.BoroCnstNat_list)[:,np.newaxis] self.getPointsForInterpolation(self.EndOfPrdvP,aNrm) cNrm = np.hstack((np.zeros((self.StateCount,1)),self.cNrmNow)) mNrm = np.hstack((np.reshape(self.mNrmMin_list,(self.StateCount,1)),self.mNrmNow)) # Package and return the solution for this period self.BoroCnstNat = self.BoroCnstNat_list solution = self.makeSolution(cNrm,mNrm) return solution
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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 ''' 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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. ''' 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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. ''' # 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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 ''' # 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def makeSolution(self,cNrm,mNrm): ''' Construct an object representing the solution to this period's problem. Parameters ---------- cNrm : np.array Array of normalized consumption values for interpolation. Each row corresponds to a Markov state for this period. mNrm : np.array Array of normalized market resource values for interpolation. Each row corresponds to a Markov state for this period. Returns ------- solution : ConsumerSolution The solution to the single period consumption-saving problem. Includes a consumption function cFunc (using cubic or linear splines), a marg- inal value function vPfunc, a minimum acceptable level of normalized market resources mNrmMin, normalized human wealth hNrm, and bounding MPCs MPCmin and MPCmax. It might also have a value function vFunc and marginal marginal value function vPPfunc. All of these attributes are lists or arrays, 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. ''' solution = ConsumerSolution() # An empty solution to which we'll add state-conditional solutions # Calculate the MPC at each market resource gridpoint in each state (if desired) if self.CubicBool: dcda = self.EndOfPrdvPP/self.uPP(np.array(self.cNrmNow)) MPC = dcda/(dcda+1.0) self.MPC_temp = np.hstack((np.reshape(self.MPCmaxNow,(self.StateCount,1)),MPC)) interpfunc = self.makeCubiccFunc else: interpfunc = self.makeLinearcFunc # Loop through each current period state and add its solution to the overall solution for i in range(self.StateCount): # Set current-period-conditional human wealth and MPC bounds self.hNrmNow_j = self.hNrmNow[i] self.MPCminNow_j = self.MPCminNow[i] if self.CubicBool: self.MPC_temp_j = self.MPC_temp[i,:] # Construct the consumption function by combining the constrained and unconstrained portions self.cFuncNowCnst = LinearInterp([self.mNrmMin_list[i], self.mNrmMin_list[i]+1.0], [0.0,1.0]) cFuncNowUnc = interpfunc(mNrm[i,:],cNrm[i,:]) cFuncNow = LowerEnvelope(cFuncNowUnc,self.cFuncNowCnst) # Make the marginal value function and pack up the current-state-conditional solution vPfuncNow = MargValueFunc(cFuncNow,self.CRRA) solution_cond = ConsumerSolution(cFunc=cFuncNow, vPfunc=vPfuncNow, mNrmMin=self.mNrmMinNow) if self.CubicBool: # Add the state-conditional marginal marginal value function (if desired) solution_cond = self.addvPPfunc(solution_cond) # Add the current-state-conditional solution to the overall period solution solution.appendSolution(solution_cond) # Add the lower bounds of market resources, MPC limits, human resources, # and the value functions to the overall solution solution.mNrmMin = self.mNrmMin_list solution = self.addMPCandHumanWealth(solution) if self.vFuncBool: vFuncNow = self.makevFunc(solution) solution.vFunc = vFuncNow # Return the overall solution to this period return solution
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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. ''' 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def checkMarkovInputs(self): ''' 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!'
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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 ''' 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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 ''' # 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def readShocks(self): ''' 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def solveConsRepAgent(solution_next,DiscFac,CRRA,IncomeDstn,CapShare,DeprFac,PermGroFac,aXtraGrid): ''' Solve one period of the simple representative agent consumption-saving model. Parameters ---------- solution_next : ConsumerSolution Solution to the next period's problem (i.e. previous iteration). DiscFac : float Intertemporal discount factor for future utility. CRRA : float Coefficient of relative risk aversion. 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. CapShare : float Capital's share of income in Cobb-Douglas production function. DeprFac : float Depreciation rate of capital. PermGroFac : float Expected permanent income growth factor at the end of this period. aXtraGrid : np.array Array of "extra" end-of-period asset values-- assets above the absolute minimum acceptable level. In this model, the minimum acceptable level is always zero. Returns ------- solution_now : ConsumerSolution Solution to this period's problem (new iteration). ''' # Unpack next period's solution and the income distribution vPfuncNext = solution_next.vPfunc ShkPrbsNext = IncomeDstn[0] PermShkValsNext = IncomeDstn[1] TranShkValsNext = IncomeDstn[2] # Make tiled versions of end-of-period assets, shocks, and probabilities aNrmNow = aXtraGrid aNrmCount = aNrmNow.size ShkCount = ShkPrbsNext.size aNrm_tiled = np.tile(np.reshape(aNrmNow,(aNrmCount,1)),(1,ShkCount)) # Tile arrays of the income shocks and put them into useful shapes PermShkVals_tiled = np.tile(np.reshape(PermShkValsNext,(1,ShkCount)),(aNrmCount,1)) TranShkVals_tiled = np.tile(np.reshape(TranShkValsNext,(1,ShkCount)),(aNrmCount,1)) ShkPrbs_tiled = np.tile(np.reshape(ShkPrbsNext,(1,ShkCount)),(aNrmCount,1)) # Calculate next period's capital-to-permanent-labor ratio under each combination # of end-of-period assets and shock realization kNrmNext = aNrm_tiled/(PermGroFac*PermShkVals_tiled) # Calculate next period's market resources KtoLnext = kNrmNext/TranShkVals_tiled RfreeNext = 1. - DeprFac + CapShare*KtoLnext**(CapShare-1.) wRteNext = (1.-CapShare)*KtoLnext**CapShare mNrmNext = RfreeNext*kNrmNext + wRteNext*TranShkVals_tiled # Calculate end-of-period marginal value of assets for the RA vPnext = vPfuncNext(mNrmNext) EndOfPrdvP = DiscFac*np.sum(RfreeNext*(PermGroFac*PermShkVals_tiled)**(-CRRA)*vPnext*ShkPrbs_tiled,axis=1) # Invert the first order condition to get consumption, then find endogenous gridpoints cNrmNow = EndOfPrdvP**(-1./CRRA) mNrmNow = aNrmNow + cNrmNow # Construct the consumption function and the marginal value function cFuncNow = LinearInterp(np.insert(mNrmNow,0,0.0),np.insert(cNrmNow,0,0.0)) vPfuncNow = MargValueFunc(cFuncNow,CRRA) # Construct and return the solution for this period solution_now = ConsumerSolution(cFunc=cFuncNow,vPfunc=vPfuncNow) return solution_now
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def solveConsRepAgentMarkov(solution_next,MrkvArray,DiscFac,CRRA,IncomeDstn,CapShare,DeprFac,PermGroFac,aXtraGrid): ''' Solve one period of the simple representative agent consumption-saving model. This version supports a discrete Markov process. Parameters ---------- solution_next : ConsumerSolution Solution to the next period's problem (i.e. previous iteration). MrkvArray : np.array Markov transition array between this period and next period. DiscFac : float Intertemporal discount factor for future utility. CRRA : float Coefficient of relative risk aversion. IncomeDstn : [[np.array]] A list of lists 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. CapShare : float Capital's share of income in Cobb-Douglas production function. DeprFac : float Depreciation rate of capital. PermGroFac : [float] Expected permanent income growth factor for each state we could be in next period. aXtraGrid : np.array Array of "extra" end-of-period asset values-- assets above the absolute minimum acceptable level. In this model, the minimum acceptable level is always zero. Returns ------- solution_now : ConsumerSolution Solution to this period's problem (new iteration). ''' # Define basic objects StateCount = MrkvArray.shape[0] aNrmNow = aXtraGrid aNrmCount = aNrmNow.size EndOfPrdvP_cond = np.zeros((StateCount,aNrmCount)) + np.nan # Loop over *next period* states, calculating conditional EndOfPrdvP for j in range(StateCount): # Define next-period-state conditional objects vPfuncNext = solution_next.vPfunc[j] ShkPrbsNext = IncomeDstn[j][0] PermShkValsNext = IncomeDstn[j][1] TranShkValsNext = IncomeDstn[j][2] # Make tiled versions of end-of-period assets, shocks, and probabilities ShkCount = ShkPrbsNext.size aNrm_tiled = np.tile(np.reshape(aNrmNow,(aNrmCount,1)),(1,ShkCount)) # Tile arrays of the income shocks and put them into useful shapes PermShkVals_tiled = np.tile(np.reshape(PermShkValsNext,(1,ShkCount)),(aNrmCount,1)) TranShkVals_tiled = np.tile(np.reshape(TranShkValsNext,(1,ShkCount)),(aNrmCount,1)) ShkPrbs_tiled = np.tile(np.reshape(ShkPrbsNext,(1,ShkCount)),(aNrmCount,1)) # Calculate next period's capital-to-permanent-labor ratio under each combination # of end-of-period assets and shock realization kNrmNext = aNrm_tiled/(PermGroFac[j]*PermShkVals_tiled) # Calculate next period's market resources KtoLnext = kNrmNext/TranShkVals_tiled RfreeNext = 1. - DeprFac + CapShare*KtoLnext**(CapShare-1.) wRteNext = (1.-CapShare)*KtoLnext**CapShare mNrmNext = RfreeNext*kNrmNext + wRteNext*TranShkVals_tiled # Calculate end-of-period marginal value of assets for the RA vPnext = vPfuncNext(mNrmNext) EndOfPrdvP_cond[j,:] = DiscFac*np.sum(RfreeNext*(PermGroFac[j]*PermShkVals_tiled)**(-CRRA)*vPnext*ShkPrbs_tiled,axis=1) # Apply the Markov transition matrix to get unconditional end-of-period marginal value EndOfPrdvP = np.dot(MrkvArray,EndOfPrdvP_cond) # Construct the consumption function and marginal value function for each discrete state cFuncNow_list = [] vPfuncNow_list = [] for i in range(StateCount): # Invert the first order condition to get consumption, then find endogenous gridpoints cNrmNow = EndOfPrdvP[i,:]**(-1./CRRA) mNrmNow = aNrmNow + cNrmNow # Construct the consumption function and the marginal value function cFuncNow_list.append(LinearInterp(np.insert(mNrmNow,0,0.0),np.insert(cNrmNow,0,0.0))) vPfuncNow_list.append(MargValueFunc(cFuncNow_list[-1],CRRA)) # Construct and return the solution for this period solution_now = ConsumerSolution(cFunc=cFuncNow_list,vPfunc=vPfuncNow_list) return solution_now
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def getStates(self): ''' 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def getShocks(self): ''' 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def getControls(self): ''' 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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 ''' 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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 ''' 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')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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 ''' 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)]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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. ''' # 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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. ''' RfreeNow = self.RfreeNow*np.ones(self.AgentCount) return RfreeNow
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def getShocks(self): ''' Finds the effective permanent and transitory shocks this period by combining the aggregate and idiosyncratic shocks of each type. Parameters ---------- None Returns ------- None ''' IndShockConsumerType.getShocks(self) # Update idiosyncratic shocks self.TranShkNow = self.TranShkNow*self.TranShkAggNow*self.wRteNow self.PermShkNow = self.PermShkNow*self.PermShkAggNow
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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. ''' 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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 ''' 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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 ''' 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def makeAggShkDstn(self): ''' 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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. ''' # 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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 ''' 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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 ''' 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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 ''' 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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. ''' # 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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 ''' 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def makeMrkvHist(self): ''' Makes a history of macroeconomic Markov states, stored in the attribute MrkvNow_hist. This version ensures that each state is reached a sufficient number of times to have a valid sample for calcDynamics to produce a good dynamic rule. It will sometimes cause act_T to be increased beyond its initially specified level. Parameters ---------- None Returns ------- None ''' if hasattr(self,'loops_max'): loops_max = self.loops_max else: # Maximum number of loops; final act_T never exceeds act_T*loops_max loops_max = 10 state_T_min = 50 # Choose minimum number of periods in each state for a valid Markov sequence logit_scale = 0.2 # Scaling factor on logit choice shocks when jumping to a new state # Values close to zero make the most underrepresented states very likely to visit, while # large values of logit_scale make any state very likely to be jumped to. # Reset act_T to the level actually specified by the user if hasattr(self,'act_T_orig'): act_T = self.act_T_orig else: # Or store it for the first time self.act_T_orig = self.act_T act_T = self.act_T # 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)) # Initialize the Markov history and set up transitions MrkvNow_hist = np.zeros(self.act_T_orig,dtype=int) cutoffs = np.cumsum(self.MrkvArray,axis=1) loops = 0 go = True MrkvNow = self.MrkvNow_init t = 0 StateCount = self.MrkvArray.shape[0] # Add histories until each state has been visited at least state_T_min times while go: draws = drawUniform(N=self.act_T_orig,seed=loops) for s in range(draws.size): # Add act_T_orig more periods MrkvNow_hist[t] = MrkvNow MrkvNow = np.searchsorted(cutoffs[MrkvNow,:],draws[s]) t += 1 # Calculate the empirical distribution state_T = np.zeros(StateCount) for i in range(StateCount): state_T[i] = np.sum(MrkvNow_hist==i) # Check whether each state has been visited state_T_min times if np.all(state_T >= state_T_min): go = False # If so, terminate the loop continue # Choose an underrepresented state to "jump" to if np.any(state_T == 0): # If any states have *never* been visited, randomly choose one of those never_visited = np.where(np.array(state_T == 0))[0] MrkvNow = np.random.choice(never_visited) else: # Otherwise, use logit choice probabilities to visit an underrepresented state emp_dstn = state_T/act_T ratios = LR_dstn/emp_dstn ratios_adj = ratios - np.max(ratios) ratios_exp = np.exp(ratios_adj/logit_scale) ratios_sum = np.sum(ratios_exp) jump_probs = ratios_exp/ratios_sum cum_probs = np.cumsum(jump_probs) MrkvNow = np.searchsorted(cum_probs,draws[-1]) loops += 1 # Make the Markov state history longer by act_T_orig periods if loops >= loops_max: go = False print('makeMrkvHist reached maximum number of loops without generating a valid sequence!') else: MrkvNow_new = np.zeros(self.act_T_orig,dtype=int) MrkvNow_hist = np.concatenate((MrkvNow_hist,MrkvNow_new)) act_T += self.act_T_orig # Store the results as attributes of self self.MrkvNow_hist = MrkvNow_hist self.act_T = act_T
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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. ''' 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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. ''' 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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). ''' # 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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. ''' 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def updateIncomeProcess(self): ''' 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def solve(self): ''' Solves the cstwMPCmarket. ''' if self.AggShockBool: for agent in self.agents: agent.getEconomyData(self) Market.solve(self) else: self.solveAgents() self.makeHistory()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def millRule(self,aLvlNow,pLvlNow,MPCnow,TranShkNow,EmpNow,t_age,LorenzBool,ManyStatsBool): ''' 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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 ''' # 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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. ''' # 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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) ''' 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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. ''' c = self.cFunc(m,p) MPC = self.cFunc.derivativeX(m,p) return MPC*utilityPP(c,gam=self.CRRA)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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 ''' # 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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. ''' 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