fig6_par = copy(base_params)

# Replace parameters.
fig6_par['Rfree'] = 0.98
fig6_par['DiscFac'] = 1
fig6_par['PermGroFac'] = [0.99]
fig6_par['CRRA'] = 2
fig6_par['BoroCnstArt']  = 0
fig6_par['T_cycle'] = 0
fig6_par['cycles'] = 0
fig6_par['quiet'] = False

# Create the agent
RichButPatientAgent = PerfForesightConsumerType(**fig6_par)
# Check conditions
RichButPatientAgent.checkConditions(verbose = 3)
# Solve
RichButPatientAgent.solve()

# Plot
mPlotMin, mPlotMax = 1, 9.5
plt.figure(figsize = (8,4))
m_grid = np.linspace(mPlotMin,mPlotMax,500)
plt.plot(m_grid-1, RichButPatientAgent.solution[0].cFunc(m_grid), color="black")
plt.text(mPlotMax-1+0.05,1,r"$b$",fontsize = 26)
plt.text(mPlotMin-1,1.017,r"$c$",fontsize = 26)
plt.xlim(mPlotMin-1,mPlotMax-1)
plt.ylim(mPlotMin,1.016)

make('PFGICHoldsFHWCFailsRICFails')
class testPerfForesightConsumerType(unittest.TestCase):
    def setUp(self):
        self.agent = PerfForesightConsumerType()
        self.agent_infinite = PerfForesightConsumerType(cycles=0)

        PF_dictionary = {
            'CRRA': 2.5,
            'DiscFac': 0.96,
            'Rfree': 1.03,
            'LivPrb': [0.98],
            'PermGroFac': [1.01],
            'T_cycle': 1,
            'cycles': 0,
            'AgentCount': 10000
        }
        self.agent_alt = PerfForesightConsumerType(**PF_dictionary)

    def test_default_solution(self):
        self.agent.solve()
        c = self.agent.solution[0].cFunc

        self.assertEqual(c.x_list[0], -0.9805825242718447)
        self.assertEqual(c.x_list[1], 0.01941747572815533)
        self.assertEqual(c.y_list[0], 0)
        self.assertEqual(c.y_list[1], 0.511321002804608)
        self.assertEqual(c.decay_extrap, False)

    def test_another_solution(self):
        self.agent_alt.DiscFac = 0.90
        self.agent_alt.solve()
        self.assertAlmostEqual(self.agent_alt.solution[0].cFunc(10).tolist(),
                               3.9750093524820787)

    def test_checkConditions(self):
        self.agent_infinite.checkConditions()
        self.assertTrue(self.agent_infinite.conditions['AIC'])
        self.assertTrue(self.agent_infinite.conditions['GICPF'])
        self.assertTrue(self.agent_infinite.conditions['RIC'])
        self.assertTrue(self.agent_infinite.conditions['FHWC'])

    def test_simulation(self):

        self.agent_infinite.solve()

        # Create parameter values necessary for simulation
        SimulationParams = {
            "AgentCount": 10000,  # Number of agents of this type
            "T_sim": 120,  # Number of periods to simulate
            "aNrmInitMean": -6.0,  # Mean of log initial assets
            "aNrmInitStd": 1.0,  # Standard deviation of log initial assets
            "pLvlInitMean": 0.0,  # Mean of log initial permanent income
            "pLvlInitStd":
            0.0,  # Standard deviation of log initial permanent income
            "PermGroFacAgg": 1.0,  # Aggregate permanent income growth factor
            "T_age":
            None,  # Age after which simulated agents are automatically killed
        }

        self.agent_infinite(
            **SimulationParams
        )  # This implicitly uses the assignParameters method of AgentType

        # Create PFexample object
        self.agent_infinite.track_vars = ['mNrmNow']
        self.agent_infinite.initializeSim()
        self.agent_infinite.simulate()

        self.assertAlmostEqual(
            np.mean(self.agent_infinite.history['mNrmNow'], axis=1)[40],
            -23.008063500363942)

        self.assertAlmostEqual(
            np.mean(self.agent_infinite.history['mNrmNow'], axis=1)[100],
            -27.164608851546927)

        ## Try now with the manipulation at time step 80

        self.agent_infinite.initializeSim()
        self.agent_infinite.simulate(80)
        self.agent_infinite.aNrmNow += -5.  # Adjust all simulated consumers' assets downward by 5
        self.agent_infinite.simulate(40)

        self.assertAlmostEqual(
            np.mean(self.agent_infinite.history['mNrmNow'], axis=1)[40],
            -23.008063500363942)

        self.assertAlmostEqual(
            np.mean(self.agent_infinite.history['mNrmNow'], axis=1)[100],
            -29.140261331951606)
class testPerfForesightConsumerType(unittest.TestCase):
    def setUp(self):
        self.agent = PerfForesightConsumerType()
        self.agent_infinite = PerfForesightConsumerType(cycles=0)

        PF_dictionary = {
            "CRRA": 2.5,
            "DiscFac": 0.96,
            "Rfree": 1.03,
            "LivPrb": [0.98],
            "PermGroFac": [1.01],
            "T_cycle": 1,
            "cycles": 0,
            "AgentCount": 10000,
        }
        self.agent_alt = PerfForesightConsumerType(**PF_dictionary)

    def test_default_solution(self):
        self.agent.solve()
        c = self.agent.solution[0].cFunc

        self.assertEqual(c.x_list[0], -0.9805825242718447)
        self.assertEqual(c.x_list[1], 0.01941747572815533)
        self.assertEqual(c.y_list[0], 0)
        self.assertEqual(c.y_list[1], 0.511321002804608)
        self.assertEqual(c.decay_extrap, False)

    def test_another_solution(self):
        self.agent_alt.DiscFac = 0.90
        self.agent_alt.solve()
        self.assertAlmostEqual(self.agent_alt.solution[0].cFunc(10).tolist(),
                               3.9750093524820787)

    def test_checkConditions(self):
        self.agent_infinite.checkConditions()
        self.assertTrue(self.agent_infinite.conditions["AIC"])
        self.assertTrue(self.agent_infinite.conditions["GICPF"])
        self.assertTrue(self.agent_infinite.conditions["RIC"])
        self.assertTrue(self.agent_infinite.conditions["FHWC"])

    def test_simulation(self):

        self.agent_infinite.solve()

        # Create parameter values necessary for simulation
        SimulationParams = {
            "AgentCount": 10000,  # Number of agents of this type
            "T_sim": 120,  # Number of periods to simulate
            "aNrmInitMean": -6.0,  # Mean of log initial assets
            "aNrmInitStd": 1.0,  # Standard deviation of log initial assets
            "pLvlInitMean": 0.0,  # Mean of log initial permanent income
            "pLvlInitStd":
            0.0,  # Standard deviation of log initial permanent income
            "PermGroFacAgg": 1.0,  # Aggregate permanent income growth factor
            "T_age":
            None,  # Age after which simulated agents are automatically killed
        }

        self.agent_infinite(
            **SimulationParams
        )  # This implicitly uses the assignParameters method of AgentType

        # Create PFexample object
        self.agent_infinite.track_vars = ["mNrmNow"]
        self.agent_infinite.initializeSim()
        self.agent_infinite.simulate()

        self.assertAlmostEqual(
            np.mean(self.agent_infinite.history["mNrmNow"], axis=1)[40],
            -23.008063500363942,
        )

        self.assertAlmostEqual(
            np.mean(self.agent_infinite.history["mNrmNow"], axis=1)[100],
            -27.164608851546927,
        )

        ## Try now with the manipulation at time step 80

        self.agent_infinite.initializeSim()
        self.agent_infinite.simulate(80)

        # This actually does nothing because aNrmNow is
        # epiphenomenal. Probably should change mNrmNow instead
        self.agent_infinite.state_now['aNrmNow'] += (-5.0)
        self.agent_infinite.simulate(40)

        self.assertAlmostEqual(
            np.mean(self.agent_infinite.history["mNrmNow"], axis=1)[40],
            -23.008063500363942,
        )

        self.assertAlmostEqual(
            np.mean(self.agent_infinite.history["mNrmNow"], axis=1)[100],
            -29.140261331951606,
        )
예제 #4
0
#
# \begin{align}
# \mathrm{v}_{t}(m) & = \mathrm{u}({\scriptsize \Lambda_{t}}(m))
# \end{align}
#
# In this case, the interpolation is exact, not an approximation: We need only two points to construct a line, so we choose the minimum possible value of normalized market resources, $\texttt{mNrmMin}$, where $o_{t}=0$ so that $c_{t}=0$, and that minimum plus 1, where the inverted value function will have the value $\kappa_{t}^{-\rho/(1-\rho)}$.  From these we construct $vFuncNvrs$ as a linear interpolating function (which automatically extrapolates to the whole number line).
#
#

# %% [markdown]
# ## Checking Solution Conditions
#
# The code performs tests for whether the supplied parameter values meet various conditions that determine the properties of the solution.  Some conditions (like the Finite Human Wealth Condition) are required for the model to have a sensible solution, and if these conditions are violated the code generates a warning message.  Other conditions govern characteristics of the model like whether consumption is falling (whether the consumer is 'absolutely impatient').  All conditions can manually be performed using the syntax below.  The function returns "False" if none of the key conditions has been violated.

# %%
PFexample.checkConditions(verbose=True)

# %% [markdown]
# An element of $\texttt{solution}$ also includes the (normalized) marginal value function $\texttt{vPfunc}$, and the lower and upper bounds of the marginal propensity to consume (MPC) $\texttt{MPCmin}$ and $\texttt{MPCmax}$.  Note that with a linear consumption function, the MPC is constant, so its lower and upper bound are identical.

# %% [markdown]
# ## Simulating the model
#
# Suppose we wanted to simulate many consumers who share the parameter values that we passed to $\texttt{PerfForesightConsumerType}$-- an *ex ante* homogeneous *type* of consumers.  To do this, our instance would have to know *how many* agents there are of this type, as well as their initial levels of assets $a_t$ and permanent income $P_t$.
#
# ### Setting Parameters
#
# Let's fill in this information by passing another dictionary to $\texttt{PFexample}$ with simulation parameters.  The table below lists the parameters that an instance of $\texttt{PerfForesightConsumerType}$ needs in order to successfully simulate its model using the $\texttt{simulate}$ method.
#
# | Description | Code | Example value |
# | :---: | --- | --- |
예제 #5
0
#
# \begin{align}
# \mathrm{v}_{t}(m) & = \mathrm{u}({\scriptsize \Lambda_{t}}(m))
# \end{align}
#
# In this case, the interpolation is exact, not an approximation: We need only two points to construct a line, so we choose the minimum possible value of normalized market resources, $\texttt{mNrmMin}$, where $o_{t}=0$ so that $c_{t}=0$, and that minimum plus 1, where the inverted value function will have the value $\kappa_{t}^{-\rho/(1-\rho)}$.  From these we construct $vFuncNvrs$ as a linear interpolating function (which automatically extrapolates to the whole number line).
#
#

# %% [markdown]
# ## Checking Solution Conditions
#
# The code performs tests for whether the supplied parameter values meet various conditions that determine the properties of the solution.  Some conditions (like the Finite Human Wealth Condition) are required for the model to have a sensible solution, and if these conditions are violated the code generates a warning message.  Other conditions govern characteristics of the model like whether consumption is falling (whether the consumer is 'absolutely impatient').  All conditions can manually be performed using the syntax below.  The function returns "False" if none of the key conditions has been violated.

# %%
PFexample.checkConditions(verbose=True, public_call=True)

# %% [markdown]
# An element of $\texttt{solution}$ also includes the (normalized) marginal value function $\texttt{vPfunc}$, and the lower and upper bounds of the marginal propensity to consume (MPC) $\texttt{MPCmin}$ and $\texttt{MPCmax}$.  Note that with a linear consumption function, the MPC is constant, so its lower and upper bound are identical.

# %% [markdown]
# ## Simulating the model
#
# Suppose we wanted to simulate many consumers who share the parameter values that we passed to $\texttt{PerfForesightConsumerType}$-- an *ex ante* homogeneous *type* of consumers.  To do this, our instance would have to know *how many* agents there are of this type, as well as their initial levels of assets $a_t$ and permanent income $P_t$.
#
# ### Setting Parameters
#
# Let's fill in this information by passing another dictionary to $\texttt{PFexample}$ with simulation parameters.  The table below lists the parameters that an instance of $\texttt{PerfForesightConsumerType}$ needs in order to successfully simulate its model using the $\texttt{simulate}$ method.
#
# | Description | Code | Example value |
# | :---: | --- | --- |