Ejemplo n.º 1
0
 def initializeSim(self):
     IndShockConsumerType.initializeSim(self)
     if self.global_markov:  #Need to initialize markov state to be the same for all agents
         base_draw = drawUniform(1,seed=self.RNG.randint(0,2**31-1))
         Cutoffs = np.cumsum(np.array(self.MrkvPrbsInit))
         self.MrkvNow = np.ones(self.AgentCount)*np.searchsorted(Cutoffs,base_draw).astype(int)
     self.MrkvNow = self.MrkvNow.astype(int)
Ejemplo n.º 2
0
    def __init__(self,
                 cycles=1,
                 **kwds):
        '''
        Instantiate a new ConsumerType with given data, and construct objects
        to be used during solution (income distribution, assets grid, etc).
        See ConsumerParameters.init_pref_shock for a dictionary of
        the keywords that should be passed to the constructor.

        Parameters
        ----------
        cycles : int
            Number of times the sequence of periods should be solved.

        Returns
        -------
        None
        '''
        params = init_preference_shocks.copy()
        params.update(kwds)

        IndShockConsumerType.__init__(self,
                                      cycles=cycles,
                                      **params)
        self.solveOnePeriod = makeOnePeriodOOSolver(ConsPrefShockSolver)
Ejemplo n.º 3
0
    def __init__(self, cycles=1, time_flow=True, **kwds):
        '''
        Instantiate a new consumer type with given data.
        See ConsumerParameters.init_labor_intensive for a dictionary of
        the keywords that should be passed to the constructor.
        
        Parameters
        ----------
        cycles : int
            Number of times the sequence of periods should be solved.
        time_flow : boolean
            Whether time is currently "flowing" forward for this instance.
        
        Returns
        -------
        None
        '''
        params = Params.init_labor_intensive.copy()
        params.update(kwds)
        kwds = params

        IndShockConsumerType.__init__(self,
                                      cycles=cycles,
                                      time_flow=time_flow,
                                      **kwds)
        self.pseudo_terminal = False
        self.solveOnePeriod = solveConsLaborIntMarg
        self.update()
Ejemplo n.º 4
0
    def test_ConsIndShockSolverBasic(self):
        LifecycleExample = IndShockConsumerType(**init_lifecycle)
        LifecycleExample.cycles = 1
        LifecycleExample.solve()

        solver = ConsIndShockSolverBasic(
            LifecycleExample.solution[1], LifecycleExample.IncomeDstn[0],
            LifecycleExample.LivPrb[0], LifecycleExample.DiscFac,
            LifecycleExample.CRRA, LifecycleExample.Rfree,
            LifecycleExample.PermGroFac[0], LifecycleExample.BoroCnstArt,
            LifecycleExample.aXtraGrid, LifecycleExample.vFuncBool,
            LifecycleExample.CubicBool)

        solver.prepareToSolve()

        self.assertAlmostEqual(solver.DiscFacEff, 0.9503999999999999)
        self.assertAlmostEqual(solver.PermShkMinNext, 0.850430160026919)
        self.assertAlmostEqual(solver.cFuncNowCnst(4).tolist(), 4.0)
        self.assertAlmostEqual(solver.prepareToCalcEndOfPrdvP()[0],
                               -0.2491750859108316)
        self.assertAlmostEqual(solver.prepareToCalcEndOfPrdvP()[-1],
                               19.74982491408914)

        EndOfPrdvP = solver.calcEndOfPrdvP()

        self.assertAlmostEqual(EndOfPrdvP[0], 6622.251864311334)
        self.assertAlmostEqual(EndOfPrdvP[-1], 0.026301061207747087)

        solution = solver.makeBasicSolution(EndOfPrdvP, solver.aNrmNow,
                                            solver.makeLinearcFunc)
        solver.addMPCandHumanWealth(solution)

        self.assertAlmostEqual(solution.cFunc(4).tolist(), 1.7391265696400773)
Ejemplo n.º 5
0
    def setUp(self):
        self.agent = IndShockConsumerType(
            AgentCount = 2,
            T_sim = 10
        )

        self.agent.solve()
Ejemplo n.º 6
0
    def test_cyclical(self):
        CyclicalExample = IndShockConsumerType(**CyclicalDict)
        CyclicalExample.cycles = 0  # Make this consumer type have an infinite horizon
        CyclicalExample.solve()

        self.assertAlmostEqual(CyclicalExample.solution[3].cFunc(3).tolist(),
                               1.5958390056965004)
Ejemplo n.º 7
0
    def __init__(self, cycles=1, time_flow=True, **kwds):
        '''
        Instantiate a new ConsumerType with given data, and construct objects
        to be used during solution (income distribution, assets grid, etc).
        See ConsumerParameters.init_pref_shock for a dictionary of
        the keywords that should be passed to the constructor.

        Parameters
        ----------
        cycles : int
            Number of times the sequence of periods should be solved.
        time_flow : boolean
            Whether time is currently "flowing" forward for this instance.

        Returns
        -------
        None
        '''
        params = init_preference_shocks.copy()
        params.update(kwds)

        IndShockConsumerType.__init__(self,
                                      cycles=cycles,
                                      time_flow=time_flow,
                                      **params)
        self.solveOnePeriod = solveConsPrefShock  # Choose correct solver
Ejemplo n.º 8
0
    def update_solution_terminal(self):
        """
        Update the terminal period solution.  This method should be run when a
        new AgentType is created or when CRRA changes.

        Parameters
        ----------
        none

        Returns
        -------
        none
        """
        IndShockConsumerType.update_solution_terminal(self)

        # Make replicated terminal period solution: consume all resources, no human wealth, minimum m is 0
        StateCount = self.MrkvArray[0].shape[0]
        self.solution_terminal.cFunc = StateCount * [self.cFunc_terminal_]
        self.solution_terminal.vFunc = StateCount * [self.solution_terminal.vFunc]
        self.solution_terminal.vPfunc = StateCount * [self.solution_terminal.vPfunc]
        self.solution_terminal.vPPfunc = StateCount * [self.solution_terminal.vPPfunc]
        self.solution_terminal.mNrmMin = np.zeros(StateCount)
        self.solution_terminal.hRto = np.zeros(StateCount)
        self.solution_terminal.MPCmax = np.ones(StateCount)
        self.solution_terminal.MPCmin = np.ones(StateCount)
Ejemplo n.º 9
0
    def __init__(self, cycles=1, time_flow=True, **kwds):
        '''
        Instantiate a new ConsumerType with given data, and construct objects
        to be used during solution (income distribution, assets grid, etc).
        See ConsumerParameters.init_kinky_pref for a dictionary of the keywords
        that should be passed to the constructor.

        Parameters
        ----------
        cycles : int
            Number of times the sequence of periods should be solved.
        time_flow : boolean
            Whether time is currently "flowing" forward for this instance.

        Returns
        -------
        None
        '''
        params = Params.init_kinky_pref.copy()
        params.update(kwds)
        kwds = params
        IndShockConsumerType.__init__(self, **kwds)
        self.solveOnePeriod = solveConsKinkyPref  # Choose correct solver
        self.addToTimeInv('Rboro', 'Rsave')
        self.delFromTimeInv('Rfree')
Ejemplo n.º 10
0
    def sim_birth(self, which_agents):
        """
        Makes new Markov consumer by drawing initial normalized assets, permanent income levels, and
        discrete states. Calls IndShockConsumerType.sim_birth, 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.sim_birth(
            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 = Uniform(seed=self.RNG.randint(0, 2 ** 31 - 1)).draw(N)
            Cutoffs = np.cumsum(np.array(self.MrkvPrbsInit))
            self.shocks["Mrkv"][which_agents] = np.searchsorted(
                Cutoffs, base_draws
            ).astype(int)
Ejemplo n.º 11
0
    def __init__(self, cycles=1, time_flow=True, **kwds):
        '''
        Instantiate a new ConsumerType with given data.
        See ConsumerParameters.init_idiosyncratic_shocks for a dictionary of
        the keywords that should be passed to the constructor.
        
        Parameters
        ----------
        cycles : int
            Number of times the sequence of periods should be solved.
        time_flow : boolean
            Whether time is currently "flowing" forward for this instance.
        
        Returns
        -------
        None
        '''
        # Initialize a basic AgentType
        IndShockConsumerType.__init__(self,
                                      cycles=cycles,
                                      time_flow=time_flow,
                                      **kwds)

        # Add consumer-type specific objects, copying to create independent versions
        self.solveOnePeriod = solvePrefLaborShock  # idiosyncratic shocks solver
        self.update()  # Make assets grid, income process, terminal solution
 def __init__(self, **kwds):
     params = init_kinky_pref.copy()
     params.update(kwds)
     kwds = params
     IndShockConsumerType.__init__(self, **kwds)
     self.solve_one_period = make_one_period_oo_solver(ConsKinkyPrefSolver)
     self.add_to_time_inv("Rboro", "Rsave")
     self.del_from_time_inv("Rfree")
Ejemplo n.º 13
0
    def __init__(self, **kwds):
        params = init_rep_agent.copy()
        params.update(kwds)

        IndShockConsumerType.__init__(self, cycles=0, **params)
        self.AgentCount = 1  # Hardcoded, because this is rep agent
        self.solve_one_period = solve_ConsRepAgent
        self.del_from_time_inv("Rfree", "BoroCnstArt", "vFuncBool", "CubicBool")
Ejemplo n.º 14
0
    def test_ConsIndShockSolverBasic(self):
        LifecycleExample = IndShockConsumerType(**init_lifecycle)
        LifecycleExample.cycles = 1
        LifecycleExample.solve()

        # test the solution_terminal
        self.assertAlmostEqual(LifecycleExample.solution[-1].cFunc(2).tolist(),
                               2)

        self.assertAlmostEqual(LifecycleExample.solution[9].cFunc(1),
                               0.79429538)
        self.assertAlmostEqual(LifecycleExample.solution[8].cFunc(1),
                               0.79391692)
        self.assertAlmostEqual(LifecycleExample.solution[7].cFunc(1),
                               0.79253095)

        self.assertAlmostEqual(LifecycleExample.solution[0].cFunc(1).tolist(),
                               0.7506184692092213)
        self.assertAlmostEqual(LifecycleExample.solution[1].cFunc(1).tolist(),
                               0.7586358637239385)
        self.assertAlmostEqual(LifecycleExample.solution[2].cFunc(1).tolist(),
                               0.7681247572911291)

        solver = ConsIndShockSolverBasic(
            LifecycleExample.solution[1],
            LifecycleExample.IncShkDstn[0],
            LifecycleExample.LivPrb[0],
            LifecycleExample.DiscFac,
            LifecycleExample.CRRA,
            LifecycleExample.Rfree,
            LifecycleExample.PermGroFac[0],
            LifecycleExample.BoroCnstArt,
            LifecycleExample.aXtraGrid,
            LifecycleExample.vFuncBool,
            LifecycleExample.CubicBool,
        )

        solver.prepare_to_solve()

        self.assertAlmostEqual(solver.DiscFacEff, 0.9586233599999999)
        self.assertAlmostEqual(solver.PermShkMinNext, 0.6554858756904397)
        self.assertAlmostEqual(solver.cFuncNowCnst(4).tolist(), 4.0)
        self.assertAlmostEqual(solver.prepare_to_calc_EndOfPrdvP()[0],
                               -0.19792871012285213)
        self.assertAlmostEqual(solver.prepare_to_calc_EndOfPrdvP()[-1],
                               19.801071289877118)

        EndOfPrdvP = solver.calc_EndOfPrdvP()

        self.assertAlmostEqual(EndOfPrdvP[0], 6657.839372100613)
        self.assertAlmostEqual(EndOfPrdvP[-1], 0.2606075215645896)

        solution = solver.make_basic_solution(EndOfPrdvP, solver.aNrmNow,
                                              solver.make_linear_cFunc)
        solver.add_MPC_and_human_wealth(solution)

        self.assertAlmostEqual(solution.cFunc(4).tolist(), 1.0028005137373956)
Ejemplo n.º 15
0
    def __init__(self, **kwds):
        params = init_labor_intensive.copy()
        params.update(kwds)

        IndShockConsumerType.__init__(self, **params)

        self.pseudo_terminal = False
        self.solve_one_period = solve_ConsLaborIntMarg
        self.update()
Ejemplo n.º 16
0
    def __init__(self, **kwargs):
        IndShockConsumerType.__init__(self, **kwargs)

        # Add consumer-type specific objects, copying to create independent versions
        if (not self.CubicBool) and (not self.vFuncBool):
            solver = ConsIndShockSolverBasicFast
        else:  # Use the "advanced" solver if either is requested
            solver = ConsIndShockSolverFast

        self.solve_one_period = make_one_period_oo_solver(solver)
 def initialize_sim(self):
     self.shocks["Mrkv"] = np.zeros(self.AgentCount, dtype=int)
     IndShockConsumerType.initialize_sim(self)
     if (self.global_markov
         ):  # Need to initialize markov state to be the same for all agents
         base_draw = Uniform(seed=self.RNG.randint(0, 2**31 - 1)).draw(1)
         Cutoffs = np.cumsum(np.array(self.MrkvPrbsInit))
         self.shocks["Mrkv"] = np.ones(self.AgentCount) * np.searchsorted(
             Cutoffs, base_draw).astype(int)
     self.shocks["Mrkv"] = self.shocks["Mrkv"].astype(int)
Ejemplo n.º 18
0
    def setUp(self):
        """
        Prepare to compare the models by initializing and solving them
        """
        # Set up and solve infinite type

        # Define a test dictionary that should have the same solution in the
        # perfect foresight and idiosyncratic shocks models.
        test_dictionary = deepcopy(init_idiosyncratic_shocks)
        test_dictionary["LivPrb"] = [1.0]
        test_dictionary["DiscFac"] = 0.955
        test_dictionary["PermGroFac"] = [1.0]
        test_dictionary["PermShkStd"] = [0.0]
        test_dictionary["TranShkStd"] = [0.0]
        test_dictionary["UnempPrb"] = 0.0
        test_dictionary["T_cycle"] = 1
        test_dictionary["T_retire"] = 0
        test_dictionary["BoroCnstArt"] = None

        InfiniteType = IndShockConsumerType(**test_dictionary)
        InfiniteType.cycles = 0

        InfiniteType.update_income_process()
        InfiniteType.solve()
        InfiniteType.unpack("cFunc")

        # Make and solve a perfect foresight consumer type with the same parameters
        PerfectForesightType = PerfForesightConsumerType(**test_dictionary)
        PerfectForesightType.cycles = 0

        PerfectForesightType.solve()
        PerfectForesightType.unpack("cFunc")

        self.InfiniteType = InfiniteType
        self.PerfectForesightType = PerfectForesightType
Ejemplo n.º 19
0
    def __init__(self, verbose=False, quiet=False, **kwds):
        params = init_risky_asset.copy()
        params.update(kwds)
        kwds = params

        # Initialize a basic consumer type
        IndShockConsumerType.__init__(self, verbose=verbose, quiet=quiet, **kwds)

        # These method must be overwritten by classes that inherit from
        # RiskyAssetConsumerType
        self.solve_one_period = NullFunc()
Ejemplo n.º 20
0
    def test_lifecyle(self):
        LifecycleExample = IndShockConsumerType(**LifecycleDict)
        LifecycleExample.cycles = 1
        LifecycleExample.solve()

        self.assertEquals(len(LifecycleExample.solution), 11)

        mMin = np.min([LifecycleExample.solution[t].mNrmMin for t in
                       range(LifecycleExample.T_cycle)])

        self.assertAlmostEqual(LifecycleExample.solution[5].cFunc(3).tolist(),
                               2.129983771775666)
Ejemplo n.º 21
0
    def read_shocks_from_history(self):
        """
        A slight modification of AgentType.read_shocks that makes sure that MrkvNow is int, not float.

        Parameters
        ----------
        None

        Returns
        -------
        None
        """
        IndShockConsumerType.read_shocks_from_history(self)
        self.shocks['Mrkv'] = self.shocks['Mrkv'].astype(int)
Ejemplo n.º 22
0
    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)
Ejemplo n.º 23
0
    def test_infinite_horizon(self):
        baseEx_inf = IndShockConsumerType(**self.base_params)
        baseEx_inf.assign_parameters(cycles=0)
        baseEx_inf.solve()
        baseEx_inf.unpack("cFunc")

        m1 = np.linspace(
            1, baseEx_inf.solution[0].mNrmStE, 50
        )  # m1 defines the plot range on the left of target m value (e.g. m <= target m)
        c_m1 = baseEx_inf.cFunc[0](m1)

        self.assertAlmostEqual(c_m1[0], 0.8527887545025995)
        self.assertAlmostEqual(c_m1[-1], 1.0036279936408656)

        x1 = np.linspace(0, 25, 1000)
        cfunc_m = baseEx_inf.cFunc[0](x1)

        self.assertAlmostEqual(cfunc_m[500], 1.8902146173138235)
        self.assertAlmostEqual(cfunc_m[700], 2.1591451850267176)

        m = np.linspace(0.001, 8, 1000)

        # Use the HARK method derivative to get the derivative of cFunc, and the values are just the MPC
        MPC = baseEx_inf.cFunc[0].derivative(m)

        self.assertAlmostEqual(MPC[500], 0.08415000641504392)
        self.assertAlmostEqual(MPC[700], 0.07173144137912524)
Ejemplo n.º 24
0
    def __init__(self, cycles=1, verbose=False, quiet=False, **kwds):
        params = init_portfolio.copy()
        params.update(kwds)
        kwds = params

        # Initialize a basic consumer type
        IndShockConsumerType.__init__(
            self, cycles=cycles, verbose=verbose, quiet=quiet, **kwds
        )

        shock_vars = ["PermShkNow", "TranShkNow","AdjustNow","RiskyNow"]

        # Set the solver for the portfolio model, and update various constructed attributes
        self.solveOnePeriod = solveConsPortfolio
        self.update()
Ejemplo n.º 25
0
    def initializeSim(self):
        '''
        Initialize the state of simulation attributes.  Simply calls the same method
        for IndShockConsumerType, then sets the type of AdjustNow to bool.
        
        Parameters
        ----------
        None

        Returns
        -------
        None
        '''
        IndShockConsumerType.initializeSim(self)
        self.AdjustNow = self.AdjustNow.astype(bool)
Ejemplo n.º 26
0
    def __init__(self, **kwds):

        IndShockConsumerType.__init__(self, **kwds)

        self.time_inv = ['aXtraGrid', 'mGrid', 'EGMVector', 'par', 'Util', 'UtilP',
                         'UtilP_inv', 'saveCommon']

        self.par = RetiringDeatonParameters(self.DiscFac, self.CRRA, self.DisUtil, self.Rfree, YRet, YWork, self.sigma)
       # d == 2 is working
        # - 10.0 moves curve down to improve linear interpolation
        self.Util = lambda c, d: utility(c, CRRA) - self.par.DisUtil*(d-1) - 10.0
        self.UtilP = lambda c, d: utilityP(c, CRRA) # we require CRRA 1.0 for now...
        self.UtilP_inv = lambda u, d: utilityP_inv(u, CRRA) # ... so ...

        self.preSolve = self.updateLast
        self.solveOnePeriod = solveRetiringDeaton
 def test_IndShockConsumerType(self):
     try:
         model = IndShockConsumerType(**init_lifecycle)
     except:
         self.fail(
             "IndShockConsumerType failed to initialize with Params.init_lifecycle."
         )
Ejemplo n.º 28
0
    def test_infinite_horizon(self):
        IndShockExample = IndShockConsumerType(**IdiosyncDict)
        IndShockExample.cycles = 0 # Make this type have an infinite horizon
        IndShockExample.solve()

        self.assertAlmostEqual(IndShockExample.solution[0].mNrmSS,
                               1.5488165705077026)
        self.assertAlmostEqual(IndShockExample.solution[0].cFunc.functions[0].x_list[0],
                               -0.25017509)

        IndShockExample.track_vars = ['aNrmNow','mNrmNow','cNrmNow','pLvlNow']
        IndShockExample.initializeSim()
        IndShockExample.simulate()

        self.assertAlmostEqual(IndShockExample.mNrmNow_hist[0][0],
                               1.0170176090252379)
    def update(self):
        """
        Update the income process, the assets grid, the persistent income grid,
        and the terminal solution.

        Parameters
        ----------
        None

        Returns
        -------
        None
        """
        IndShockConsumerType.update(self)
        self.update_pLvlNextFunc()
        self.update_pLvlGrid()
    def __init__(self, **kwds):
        params = init_explicit_perm_inc.copy()
        params.update(kwds)

        # Initialize a basic ConsumerType
        IndShockConsumerType.__init__(self, **params)
        self.solve_one_period = make_one_period_oo_solver(
            ConsGenIncProcessSolver)

        # a poststate?
        self.state_now['aLvl'] = None
        self.state_prev['aLvl'] = None

        # better way to do this...
        self.state_now["mLvl"] = None
        self.state_prev["mLvl"] = None