def perturbParameterToGetcPlotList(base_dictionary, param_name, param_min, param_max, N=20, time_vary=False): param_vec = np.linspace( param_min, param_max, num=N, endpoint=True ) # vector of alternative values of the parameter to examine thisConsumer = IndShockConsumerType( **my_dictionary) # create an instance of the consumer type thisConsumer.cycles = 0 # Make this type have an infinite horizon x = np.linspace( mMinVal, mMaxVal, xPoints, endpoint=True ) # Define a vector of x values that span the range from the minimum to the maximum values of m for j in range( N): # loop from the first to the last values of the parameter if time_vary: # Some parameters are time-varying; others are not setattr(thisConsumer, param_name, [param_vec[j]]) else: setattr(thisConsumer, param_name, param_vec[j]) thisConsumer.update( ) # set up the preliminaries required to solve the problem thisConsumer.solve() # solve the problem y = thisConsumer.solution[0].cFunc( x ) # Get the values of the consumption function at the points in the vector of x points pylab.plot( x, y, label=str(round(param_vec[j], 3)) ) # plot it and generate a label indicating the rounded value of the parameter pylab.legend(loc='upper right') # put the legend in the upper right return pylab # return the figure
def setUp(self): # Set up and solve infinite type import ConsumerParameters as Params InfiniteType = IndShockConsumerType(**Params.init_idiosyncratic_shocks) InfiniteType.assignParameters( LivPrb=[1.], DiscFac=0.955, PermGroFac=[1.], PermShkStd=[0.], TempShkStd=[0.], T_total=1, T_retire=0, BoroCnstArt=None, UnempPrb=0., cycles=0) # This is what makes the type infinite horizon InfiniteType.updateIncomeProcess() InfiniteType.solve() InfiniteType.timeFwd() InfiniteType.unpackcFunc() # Make and solve a perfect foresight consumer type PerfectForesightType = deepcopy(InfiniteType) PerfectForesightType.solveOnePeriod = solvePerfForesight PerfectForesightType.solve() PerfectForesightType.unpackcFunc() PerfectForesightType.timeFwd() self.InfiniteType = InfiniteType self.PerfectForesightType = PerfectForesightType
def makeNonFarmerHist(stdPerm, stdTran, numAgents, numPeriods): NonFarmerParams = { 'BoroCnstArt': 0.0, 'CRRA': np.inf, 'CubicBool': True, 'DiscFac': 0.5, 'IncUnemp': 0.0, 'IncUnempRet': 0.0, 'LivPrb': [0.98], 'Nagents': 100, 'PermGroFac': [1.01], 'PermShkCount': 20, 'PermShkStd': [stdPerm], 'Rfree': 1.0, 'T_retire': 0, 'T_total': 1, 'TranShkCount': numAgents, 'TranShkStd': [stdTran], 'UnempPrb': 0.0, 'UnempPrbRet': 0.00, 'aXtraCount': 12, 'aXtraExtra': [None], 'aXtraMax': 20, 'aXtraMin': 0.001, 'aXtraNestFac': 3, 'tax_rate': 0.0, 'vFuncBool': False } PerfForNonFarmer = PerfForesightConsumerType(**NonFarmerParams) PerfForNonFarmer.solve() NonFarmer = IndShockConsumerType(**NonFarmerParams) NonFarmer.solution = copy.deepcopy(PerfForNonFarmer.solution) NonFarmer.addToTimeVary('solution') NonFarmer.sim_periods = numPeriods NonFarmer.initializeSim(sim_prds=NonFarmer.sim_periods) NonFarmer.makeIncShkHist() NonFarmer.simConsHistory() NonFarmer.IncHist = np.multiply(NonFarmer.PermShkHist, NonFarmer.TranShkHist) NonFarmer.IncHist = np.reshape( NonFarmer.IncHist, (NonFarmer.Nagents * NonFarmer.sim_periods, 1)) NonFarmer.cHist = np.reshape( NonFarmer.cHist, (NonFarmer.Nagents * NonFarmer.sim_periods, 1)) NonFarmer.IncHist = list(itertools.chain.from_iterable(NonFarmer.IncHist)) NonFarmer.cHist = list(itertools.chain.from_iterable(NonFarmer.cHist)) return (NonFarmer.IncHist, NonFarmer.cHist)
# Make an initialization dictionary on an annual basis base_params = deepcopy(init_infinite) base_params['LivPrb'] = [0.975] base_params['Rfree'] = 1.04 / base_params['LivPrb'][0] base_params['PermShkStd'] = [0.1] base_params['TranShkStd'] = [0.1] base_params[ 'T_age'] = T_kill # Kill off agents if they manage to achieve T_kill working years base_params['AgentCount'] = 10000 base_params['pLvlInitMean'] = np.log( 23.72) # From Table 1, in thousands of USD base_params[ 'T_sim'] = T_kill # No point simulating past when agents would be killed off # Make several consumer types to be used during estimation BaseType = IndShockConsumerType(**base_params) EstTypeList = [] for j in range(TypeCount): EstTypeList.append(deepcopy(BaseType)) EstTypeList[-1](seed=j) # Define the objective function def FagerengObjFunc(center, spread, verbose=False): ''' Objective function for the quick and dirty structural estimation to fit Fagereng, Holm, and Natvik's Table 9 results with a basic infinite horizon consumption-saving model (with permanent and transitory income shocks). Parameters ----------
import os sys.path.insert(0, os.path.abspath('../')) #Path to ConsumptionSaving folder sys.path.insert(0, os.path.abspath('../../')) sys.path.insert(0, os.path.abspath('../../cstwMPC')) #Path to cstwMPC folder # Now, bring in what we need from cstwMPC import cstwMPC import SetupParamsCSTW as cstwParams ## Import the HARK ConsumerType we want ## Here, we bring in an agent making a consumption/savings decision every period, subject ## to transitory and permanent income shocks. from ConsIndShockModel import IndShockConsumerType # Now initialize a baseline consumer type, using default parameters from infinite horizon cstwMPC BaselineType = IndShockConsumerType(**cstwParams.init_infinite) #################################################################################################### #################################################################################################### """ Now, add in ex-ante heterogeneity in consumers' discount factors """ # The cstwMPC parameters do not define a discount factor, since there is ex-ante heterogeneity # in the discount factor. To prepare to create this ex-ante heterogeneity, first create # the desired number of consumer types from copy import deepcopy num_consumer_types = 7 # declare the number of types we want ConsumerTypes = [] # initialize an empty list for nn in range(num_consumer_types):
# Remove TimeBefore periods cAggImpulseResponse = cAggImpulseResponse[TimeBefore:] return cAggImpulseResponse ############################################################################### if __name__ == '__main__': import ConsumerParameters as Params from time import clock mystr = lambda number: "{:.4f}".format(number) # Make and solve an example consumer with idiosyncratic income shocks IndShockExample = IndShockConsumerType(**Params.init_idiosyncratic_shocks) IndShockExample.cycles = 0 # Make this type have an infinite horizon IndShockExample.DiePrb = 1 - IndShockExample.LivPrb[ 0] # Not sure why this is not already in the object start_time = clock() IndShockExample.solve() end_time = clock() print('Solving a consumer with idiosyncratic shocks took ' + mystr(end_time - start_time) + ' seconds.') IndShockExample.unpackcFunc() IndShockExample.timeFwd() PermShk = 1.1 TranShk = 1 cPermImpulseResponse = AggCons_impulseResponseInd(IndShockExample, PermShk,
class Compare_PerfectForesight_and_Infinite(unittest.TestCase): def setUp(self): # Set up and solve infinite type <<<<<<< HEAD import SetupConsumerParameters as Params InfiniteType = ConsumerType(**Params.init_consumer_objects) InfiniteType.solveOnePeriod = consumptionSavingSolverENDG InfiniteType.assignParameters(LivPrb = [1.], DiscFac = [0.955], ======= import ConsumerParameters as Params InfiniteType = IndShockConsumerType(**Params.init_idiosyncratic_shocks) InfiniteType.assignParameters(LivPrb = [1.], DiscFac = 0.955, >>>>>>> eeb37f24755d0c683c9d9efbe5e7447425c98b86 PermGroFac = [1.], PermShkStd = [0.], TempShkStd = [0.], T_total = 1, T_retire = 0, BoroCnstArt = None, UnempPrb = 0., cycles = 0) # This is what makes the type infinite horizon InfiniteType.updateIncomeProcess() InfiniteType.solve() InfiniteType.timeFwd() <<<<<<< HEAD InfiniteType.unpack_cFunc() =======
for the queue to clear. ''' queue.finish() if __name__ == '__main__': import ConsumerParameters as Params from ConsIndShockModel import IndShockConsumerType import matplotlib.pyplot as plt from copy import deepcopy from time import clock from HARK.parallel import multiThreadCommands, multiThreadCommandsFake # Set up a baseline IndShockConsumerType, which will be replicated. # In this case, we use a completely arbitrary 10 period lifecycle. TestType = IndShockConsumerType(**Params.init_lifecycle) TestType.TestVar = np.empty( TestType.AgentCount ) # This is for making an empty buffer for diagnostics TestType.CubicBool = True # Cubic interpolation must be on, because that's what's used in OpenCL version T_sim = 10 # Choose simulation length AgentCount = 100 # Chose number of agents in each type TestType.T_sim = T_sim # Choose number of periods to simulate TestType.AgentCount = AgentCount TestType.initializeSim() # Set up some objects for simulation # Make a list with many copies of the baseline agent type, each with a different CRRA. TypeCount = 100 CRRAmin = 1.0 CRRAmax = 5.0 CRRAset = np.linspace(CRRAmin, CRRAmax, TypeCount)
end_time = clock() print('Solving a perfect foresight consumer took ' + mystr(end_time - start_time) + ' seconds.') PFexample.unpackcFunc() PFexample.timeFwd() # Plot the perfect foresight consumption function print('Linear consumption function:') mMin = PFexample.solution[0].mNrmMin #plotFuncs(PFexample.cFunc[0],mMin,mMin+10) ############################################################################### # Make and solve an example consumer with idiosyncratic income shocks IndShockExample = IndShockConsumerType(**Params.init_idiosyncratic_shocks) IndShockExample.cycles = 0 # Make this type have an infinite horizon start_time = clock() IndShockExample.solve() end_time = clock() print('Solving a consumer with idiosyncratic shocks took ' + mystr(end_time - start_time) + ' seconds.') IndShockExample.unpackcFunc() IndShockExample.timeFwd() # Plot the consumption function and MPC for the infinite horizon consumer #print('Concave consumption function:') #plotFuncs(IndShockExample.cFunc[0],IndShockExample.solution[0].mNrmMin,5) #print('Marginal consumption function:') #plotFuncsDer(IndShockExample.cFunc[0],IndShockExample.solution[0].mNrmMin,5)