Ejemplo n.º 1
0
    def test_Harmenberg_mtd(self):

        example = IndShockConsumerType(**dict_harmenberg, verbose=0)
        example.cycles = 0
        example.track_vars = ['aNrm', 'mNrm', 'cNrm', 'pLvl', 'aLvl']
        example.T_sim = 20000

        example.solve()

        example.neutral_measure = True
        example.update_income_process()

        example.initialize_sim()
        example.simulate()

        Asset_list = []
        Consumption_list = []
        M_list = []

        for i in range(example.T_sim):
            Assetagg = np.mean(example.history['aNrm'][i])
            Asset_list.append(Assetagg)
            ConsAgg = np.mean(example.history['cNrm'][i])
            Consumption_list.append(ConsAgg)
            Magg = np.mean(example.history['mNrm'][i])
            M_list.append(Magg)

        #########################################################

        example2 = IndShockConsumerType(**dict_harmenberg, verbose=0)
        example2.cycles = 0
        example2.track_vars = ['aNrm', 'mNrm', 'cNrm', 'pLvl', 'aLvl']
        example2.T_sim = 20000

        example2.solve()
        example2.initialize_sim()
        example2.simulate()

        Asset_list2 = []
        Consumption_list2 = []
        M_list2 = []

        for i in range(example2.T_sim):
            Assetagg = np.mean(example2.history['aLvl'][i])
            Asset_list2.append(Assetagg)
            ConsAgg = np.mean(example2.history['cNrm'][i] *
                              example2.history['pLvl'][i])
            Consumption_list2.append(ConsAgg)
            Magg = np.mean(example2.history['mNrm'][i] *
                           example2.history['pLvl'][i])
            M_list2.append(Magg)

        c_std2 = np.std(Consumption_list2)
        c_std1 = np.std(Consumption_list)
        c_std_ratio = c_std2 / c_std1

        self.assertAlmostEqual(c_std2, 0.03768819564871894)
        self.assertAlmostEqual(c_std1, 0.004411745897568616)
        self.assertAlmostEqual(c_std_ratio, 8.542694099741672)
Ejemplo n.º 2
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)
Ejemplo n.º 3
0
    def test_infinite_horizon(self):
        IndShockExample = IndShockConsumerType(**IdiosyncDict)
        IndShockExample.assign_parameters(
            cycles=0)  # Make this type have an infinite horizon
        IndShockExample.solve()

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

        IndShockExample.track_vars = ['aNrm', "mNrm", "cNrm", 'pLvl']
        IndShockExample.initialize_sim()
        IndShockExample.simulate()

        self.assertAlmostEqual(IndShockExample.history["mNrm"][0][0],
                               1.0170176090252379)
Ejemplo n.º 4
0
# | :---: | --- | --- |
# | Number of consumers of this type | $\texttt{AgentCount}$ | $10000$ |
# | Number of periods to simulate | $\texttt{T_sim}$ | $120$ |
# | Mean of initial log (normalized) assets | $\texttt{aNrmInitMean}$ | $-6.0$ |
# | Stdev of initial log  (normalized) assets | $\texttt{aNrmInitStd}$ | $1.0$ |
# | Mean of initial log permanent income | $\texttt{pLvlInitMean}$ | $0.0$ |
# | Stdev of initial log permanent income | $\texttt{pLvlInitStd}$ | $0.0$ |
# | Aggregrate productivity growth factor | $\texttt{PermGroFacAgg}$ | $1.0$ |
# | Age after which consumers are automatically killed | $\texttt{T_age}$ | $None$ |
#
# Here, we will simulate 10,000 consumers for 120 periods.  All newly born agents will start with permanent income of exactly $P_t = 1.0 = \exp(\texttt{pLvlInitMean})$, as $\texttt{pLvlInitStd}$ has been set to zero; they will have essentially zero assets at birth, as $\texttt{aNrmInitMean}$ is $-6.0$; assets will be less than $1\%$ of permanent income at birth.
#
# These example parameter values were already passed as part of the parameter dictionary that we used to create $\texttt{IndShockExample}$, so it is ready to simulate.  We need to set the $\texttt{track_vars}$ attribute to indicate the variables for which we want to record a *history*.

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

# %% [markdown]
# We can now look at the simulated data in aggregate or at the individual consumer level.  Like in the perfect foresight model, we can plot average (normalized) market resources over time, as well as average consumption:

# %%
plt.plot(np.mean(IndShockExample.history['mNrmNow'],axis=1))
plt.xlabel('Time')
plt.ylabel('Mean market resources')
plt.show()

plt.plot(np.mean(IndShockExample.history['cNrmNow'],axis=1))
plt.xlabel('Time')
plt.ylabel('Mean consumption')
# | :---: | --- | --- |
# | Number of consumers of this type | $\texttt{AgentCount}$ | $10000$ |
# | Number of periods to simulate | $\texttt{T_sim}$ | $120$ |
# | Mean of initial log (normalized) assets | $\texttt{aNrmInitMean}$ | $-6.0$ |
# | Stdev of initial log  (normalized) assets | $\texttt{aNrmInitStd}$ | $1.0$ |
# | Mean of initial log permanent income | $\texttt{pLvlInitMean}$ | $0.0$ |
# | Stdev of initial log permanent income | $\texttt{pLvlInitStd}$ | $0.0$ |
# | Aggregrate productivity growth factor | $\texttt{PermGroFacAgg}$ | $1.0$ |
# | Age after which consumers are automatically killed | $\texttt{T_age}$ | $None$ |
#
# Here, we will simulate 10,000 consumers for 120 periods.  All newly born agents will start with permanent income of exactly $P_t = 1.0 = \exp(\texttt{pLvlInitMean})$, as $\texttt{pLvlInitStd}$ has been set to zero; they will have essentially zero assets at birth, as $\texttt{aNrmInitMean}$ is $-6.0$; assets will be less than $1\%$ of permanent income at birth.
#
# These example parameter values were already passed as part of the parameter dictionary that we used to create `IndShockExample`, so it is ready to simulate.  We need to set the `track_vars` attribute to indicate the variables for which we want to record a *history*.

# %%
IndShockExample.track_vars = ['aNrm', 'mNrm', 'cNrm', 'pLvl']
IndShockExample.initialize_sim()
IndShockExample.simulate()

# %% [markdown]
# We can now look at the simulated data in aggregate or at the individual consumer level.  Like in the perfect foresight model, we can plot average (normalized) market resources over time, as well as average consumption:

# %%
plt.plot(np.mean(IndShockExample.history['mNrm'], axis=1))
plt.xlabel('Time')
plt.ylabel('Mean market resources')
plt.show()

plt.plot(np.mean(IndShockExample.history['cNrm'], axis=1))
plt.xlabel('Time')
plt.ylabel('Mean consumption')
# %%
# Compare the value functions for the two types
if IndShockExample.vFuncBool:
    print("Value functions for perfect foresight vs idiosyncratic shocks:")
    plotFuncs(
        [PFexample.solution[0].vFunc, IndShockExample.solution[0].vFunc],
        IndShockExample.solution[0].mNrmMin + 0.5,
        10,
    )

# %%
# Simulate some data; results stored in mNrmNow_hist, cNrmNow_hist, and pLvlNow_hist
if do_simulation:
    IndShockExample.T_sim = 120
    IndShockExample.track_vars = ["mNrmNow", "cNrmNow", "pLvlNow"]
    IndShockExample.makeShockHistory(
    )  # This is optional, simulation will draw shocks on the fly if it isn't run.
    IndShockExample.initializeSim()
    IndShockExample.simulate()

# %%
# Make and solve an idiosyncratic shocks consumer with a finite lifecycle
LifecycleExample = IndShockConsumerType(**init_lifecycle)
LifecycleExample.cycles = (
    1)  # Make this consumer live a sequence of periods exactly once

# %%
start_time = time()
LifecycleExample.solve()
end_time = time()
    "PermGroFacAgg": 1.0,  # Aggregate permanent income growth factor
    "T_age": None,  # Age after which simulated agents are automatically killed
}

# %% slideshow={"slide_type": "slide"}
from HARK.ConsumptionSaving.ConsIndShockModel import IndShockConsumerType

IndShockSimExample = IndShockConsumerType(**IdiosyncDict)
IndShockSimExample.cycles = 0  # Make this type have an infinite horizon
IndShockSimExample.solve()

plot_funcs(IndShockSimExample.solution[0].cFunc,
           IndShockSimExample.solution[0].mNrmMin, 5)

# simulation
IndShockSimExample.track_vars = ['aNrm', 'mNrm', 'cNrm', 'pLvl']
IndShockSimExample.initialize_sim()
IndShockSimExample.simulate()

# %% slideshow={"slide_type": "slide"}
# distribution of cash on hand
density = np.histogram(IndShockSimExample.history['mNrm'],
                       density=True)  #print(density)
n, bins, patches = plt.hist(IndShockSimExample.history['mNrm'], density=True)

# %% slideshow={"slide_type": "slide"}
df1 = pd.DataFrame(IndShockSimExample.history['mNrm'],
                   columns=['beta = 0.9941'
                            ])  #Converting array to pandas DataFrame
df1.plot(kind='density', title='distribution of cash on hand')
Ejemplo n.º 8
0
        'dist_last': sims[-1, ]
    }


# %% [markdown]
# We now configure and solve a buffer-stock agent with a default parametrization.

# %% Create and simulate agent tags=[]
# Create and solve agent

popn = IndShockConsumerType(**init_idiosyncratic_shocks)

# Modify default parameters
popn.T_sim = max(sample_periods_lvl) + 1
popn.AgentCount = max_agents
popn.track_vars = ['mNrm', 'cNrm', 'pLvl']
popn.LivPrb = [1.0]
popn.cycles = 0

# Solve (but do not yet simulate)
popn.solve()

# %% [markdown]
# Under the basic simulation strategy, we have to de-normalize market resources and consumption multiplying them by permanent income. Only then we construct our statistics of interest.
#
# Note that our time-sampling strategy requires that, after enough time has passed, the economy settles on a stable distribution of its agents across states. How can we know this will be the case? [Szeidl (2013)](http://www.personal.ceu.hu/staff/Adam_Szeidl/papers/invariant.pdf) and [Harmenberg (2021)](https://www.sciencedirect.com/science/article/pii/S0165188921001202?via%3Dihub) provide conditions that can give us some reassurance.$\newcommand{\Rfree}{\mathsf{R}}$
#
# 1. [Szeidl (2013)](http://www.personal.ceu.hu/staff/Adam_Szeidl/papers/invariant.pdf) shows that if $$\log \left[\frac{(\Rfree\beta)^{1/\rho}}{\PermGroFac}
# \right] < \Ex[\log \PermShk],$$ then there is a stable invariant distribution of normalized market resources $\mNrm$.
# 2. [Harmenberg (2021)](https://www.sciencedirect.com/science/article/pii/S0165188921001202?via%3Dihub) repurposes the Szeidl proof to argue that if the same condition is satisfied when the expectation is taken with respect to the permanent-income-neutral measure ($\pShkNeutDstn$), then there is a stable invariant permanent-income-weighted distribution ($\mWgtDstnMarg$)
#
Ejemplo n.º 9
0
    "pLvlInitStd": 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
}

# %% [markdown]
# # Solve

# %% collapsed=true jupyter={"outputs_hidden": true, "source_hidden": true}
fast = IndShockConsumerType(**Harmenberg_Dict, verbose=1)
fast.cycles = 0
fast.Rfree = 1.2**.25
fast.PermGroFac = [1.02]
fast.tolerance = fast.tolerance / 100

fast.track_vars = ['cNrm', 'pLvl']
fast.solve(verbose=False)

# %% [markdown]
# # Calculate Patience Conditions

# %% collapsed=true jupyter={"outputs_hidden": true}
fast.check_conditions(verbose=True)

# %% jupyter={"source_hidden": true}
# Simulate a population
fast.initialize_sim()
fast.simulate()
print('done')

# %% jupyter={"source_hidden": true}
Ejemplo n.º 10
0
# | :---: | --- | --- |
# | Number of consumers of this type | $\texttt{AgentCount}$ | $10000$ |
# | Number of periods to simulate | $\texttt{T_sim}$ | $120$ |
# | Mean of initial log (normalized) assets | $\texttt{aNrmInitMean}$ | $-6.0$ |
# | Stdev of initial log  (normalized) assets | $\texttt{aNrmInitStd}$ | $1.0$ |
# | Mean of initial log permanent income | $\texttt{pLvlInitMean}$ | $0.0$ |
# | Stdev of initial log permanent income | $\texttt{pLvlInitStd}$ | $0.0$ |
# | Aggregrate productivity growth factor | $\texttt{PermGroFacAgg}$ | $1.0$ |
# | Age after which consumers are automatically killed | $\texttt{T_age}$ | $None$ |
#
# Here, we will simulate 10,000 consumers for 120 periods.  All newly born agents will start with permanent income of exactly $P_t = 1.0 = \exp(\texttt{pLvlInitMean})$, as $\texttt{pLvlInitStd}$ has been set to zero; they will have essentially zero assets at birth, as $\texttt{aNrmInitMean}$ is $-6.0$; assets will be less than $1\%$ of permanent income at birth.
#
# These example parameter values were already passed as part of the parameter dictionary that we used to create $\texttt{IndShockExample}$, so it is ready to simulate.  We need to set the $\texttt{track_vars}$ attribute to indicate the variables for which we want to record a *history*.

# %%
IndShockExample.track_vars = ["aNrmNow", "mNrmNow", "cNrmNow", "pLvlNow"]
IndShockExample.initializeSim()
IndShockExample.simulate()

# %% [markdown]
# We can now look at the simulated data in aggregate or at the individual consumer level.  Like in the perfect foresight model, we can plot average (normalized) market resources over time, as well as average consumption:

# %%
plt.plot(np.mean(IndShockExample.history["mNrmNow"], axis=1))
plt.xlabel("Time")
plt.ylabel("Mean market resources")
plt.show()

plt.plot(np.mean(IndShockExample.history["cNrmNow"], axis=1))
plt.xlabel("Time")
plt.ylabel("Mean consumption")