Beispiel #1
0
def main():
    from copy import deepcopy
    from time import clock
    from HARK.utilities import plotFuncs
    from . import ConsumerParameters as Params

    # Make a quick example dictionary
    RA_params = deepcopy(Params.init_idiosyncratic_shocks)
    RA_params['DeprFac'] = 0.05
    RA_params['CapShare'] = 0.36
    RA_params['UnempPrb'] = 0.0
    RA_params['LivPrb'] = [1.0]

    # Make and solve a rep agent model
    RAexample = RepAgentConsumerType(**RA_params)
    t_start = clock()
    RAexample.solve()
    t_end = clock()
    print('Solving a representative agent problem took ' +
          str(t_end - t_start) + ' seconds.')
    plotFuncs(RAexample.solution[0].cFunc, 0, 20)

    # Simulate the representative agent model
    RAexample.T_sim = 2000
    RAexample.track_vars = ['cNrmNow', 'mNrmNow', 'Rfree', 'wRte']
    RAexample.initializeSim()
    t_start = clock()
    RAexample.simulate()
    t_end = clock()
    print('Simulating a representative agent for ' + str(RAexample.T_sim) +
          ' periods took ' + str(t_end - t_start) + ' seconds.')

    # Make and solve a Markov representative agent
    RA_markov_params = deepcopy(RA_params)
    RA_markov_params['PermGroFac'] = [[0.97, 1.03]]
    RA_markov_params['MrkvArray'] = np.array([[0.99, 0.01], [0.01, 0.99]])
    RA_markov_params['MrkvNow'] = 0
    RAmarkovExample = RepAgentMarkovConsumerType(**RA_markov_params)
    RAmarkovExample.IncomeDstn[0] = 2 * [RAmarkovExample.IncomeDstn[0]]
    t_start = clock()
    RAmarkovExample.solve()
    t_end = clock()
    print('Solving a two state representative agent problem took ' +
          str(t_end - t_start) + ' seconds.')
    plotFuncs(RAmarkovExample.solution[0].cFunc, 0, 10)

    # Simulate the two state representative agent model
    RAmarkovExample.T_sim = 2000
    RAmarkovExample.track_vars = [
        'cNrmNow', 'mNrmNow', 'Rfree', 'wRte', 'MrkvNow'
    ]
    RAmarkovExample.initializeSim()
    t_start = clock()
    RAmarkovExample.simulate()
    t_end = clock()
    print('Simulating a two state representative agent for ' +
          str(RAexample.T_sim) + ' periods took ' + str(t_end - t_start) +
          ' seconds.')
targetChangeInC = -6.32  # Source: FRED
num_points = 10  #number of parameter values to plot in graphs

## First change the variance of the permanent income shock
perm_ratio_max = 5.0  #??? # Put whatever value in you want!  maximum number to multiply std of perm income shock by

perm_min = BaselineType.PermShkStd[0] * ratio_min
perm_max = BaselineType.PermShkStd[0] * perm_ratio_max

plt.ylabel('% Change in Consumption')
plt.xlabel('Std. Dev. of Perm. Income Shock (Baseline = ' +
           str(round(BaselineType.PermShkStd[0], 2)) + ')')
plt.title('Change in Cons. Following Increase in Perm. Income Uncertainty')
plt.ylim(-20., 5.)
plt.hlines(targetChangeInC, perm_min, perm_max)
plotFuncs([cChangeAfterPrmShkChange], perm_min, perm_max, N=num_points)

### Now change the variance of the temporary income shock
#temp_ratio_max = ??? # Put whatever value in you want!  maximum number to multiply std dev of temp income shock by
#
#temp_min = BaselineType.TranShkStd[0] * ratio_min
#temp_max = BaselineType.TranShkStd[0] * temp_ratio_max
#
#plt.ylabel('% Change in Consumption')
#plt.xlabel('Std. Dev. of Temp. Income Shock (Baseline = ' + str(round(BaselineType.TranShkStd[0],2)) + ')')
#plt.title('Change in Cons. Following Increase in Temp. Income Uncertainty')
#plt.ylim(-20.,5.)
#plt.hlines(targetChangeInC,temp_min,temp_max)
#plotFuncs([cChangeAfterTranShkChange],temp_min,temp_max,N=num_points)
#
#
Beispiel #3
0
# %% [markdown] {"hidden": true}
# After solving the model, we can examine an element of this type's $\texttt{solution}$:

# %% {"hidden": true}
print(vars(IndShockExample.solution[0]))

# %% [markdown] {"hidden": true}
# The single-period solution to an idiosyncratic shocks consumer's problem has all of the same attributes as in the perfect foresight model, with a couple additions.  The solution can include the marginal marginal value of market resources function $\texttt{vPPfunc}$, but this is only constructed if $\texttt{CubicBool}$ is $\texttt{True}$, so that the MPC can be accurately computed; when it is $\texttt{False}$, then $\texttt{vPPfunc}$ merely returns $\texttt{NaN}$ everywhere.
#
# The $\texttt{solveConsIndShock}$ function calculates steady state market resources and stores it in the attribute $\texttt{mNrmSS}$.  This represents the steady state level of $m_t$ if *this period* were to occur indefinitely, but with income shocks turned off.  This is relevant in a "one period infinite horizon" model like we've specified here, but is less useful in a lifecycle model.
#
# Let's take a look at the consumption function by plotting it, along with its derivative (the MPC):

# %% {"hidden": true}
print('Consumption function for an idiosyncratic shocks consumer type:')
plotFuncs(IndShockExample.solution[0].cFunc,IndShockExample.solution[0].mNrmMin,5)
print('Marginal propensity to consume for an idiosyncratic shocks consumer type:')
plotFuncsDer(IndShockExample.solution[0].cFunc,IndShockExample.solution[0].mNrmMin,5)

# %% [markdown] {"hidden": true}
# The lower part of the consumption function is linear with a slope of 1, representing the *constrained* part of the consumption function where the consumer *would like* to consume more by borrowing-- his marginal utility of consumption exceeds the marginal value of assets-- but he is prevented from doing so by the artificial borrowing constraint.
#
# The MPC is a step function, as the $\texttt{cFunc}$ itself is a piecewise linear function; note the large jump in the MPC where the borrowing constraint begins to bind.
#
# If you want to look at the interpolation nodes for the consumption function, these can be found by "digging into" attributes of $\texttt{cFunc}$:

# %% {"hidden": true}
print('mNrmGrid for unconstrained cFunc is ',IndShockExample.solution[0].cFunc.functions[0].x_list)
print('cNrmGrid for unconstrained cFunc is ',IndShockExample.solution[0].cFunc.functions[0].y_list)
print('mNrmGrid for borrowing constrained cFunc is ',IndShockExample.solution[0].cFunc.functions[1].x_list)
print('cNrmGrid for borrowing constrained cFunc is ',IndShockExample.solution[0].cFunc.functions[1].y_list)
def main():
    from time import clock
    from HARK import Market
    mystr = lambda number : "{:.4f}".format(number)
    import matplotlib.pyplot as plt
    from copy import deepcopy

    do_many_types = True

    # Make a test case and solve the micro model
    TestType = FashionVictimType(**Params.default_params)
    print('Utility function:')
    plotFuncs(TestType.conformUtilityFunc,0,1)

    t_start = clock()
    TestType.solve()
    t_end = clock()
    print('Solving a fashion victim micro model took ' + mystr(t_end-t_start) + ' seconds.')

    print('Jock value function:')
    plotFuncs(TestType.VfuncJock,0,1)
    print('Punk value function:')
    plotFuncs(TestType.VfuncPunk,0,1)
    print('Jock switch probability:')
    plotFuncs(TestType.switchFuncJock,0,1)
    print('Punk switch probability:')
    plotFuncs(TestType.switchFuncPunk,0,1)

    # Make a list of different types
    AltType = deepcopy(TestType)
    AltType(uParamA = Params.uParamB, uParamB = Params.uParamA, seed=20)
    AltType.update()
    AltType.solve()
    type_list = [TestType,AltType]
    u_vec = np.linspace(0.02,0.1,5)
    if do_many_types:
        for j in range(u_vec.size):
            ThisType = deepcopy(TestType)
            ThisType(punk_utility=u_vec[j])
            ThisType.solve()
            type_list.append(ThisType)
            ThisType = deepcopy(AltType)
            ThisType(punk_utility=u_vec[j])
            ThisType.solve()
            type_list.append(ThisType)
        for j in range(u_vec.size):
            ThisType = deepcopy(TestType)
            ThisType(jock_utility=u_vec[j])
            ThisType.solve()
            type_list.append(ThisType)
            ThisType = deepcopy(AltType)
            ThisType(jock_utility=u_vec[j])
            ThisType.solve()
            type_list.append(ThisType)

    # Now run the simulation inside a Market
    TestMarket = Market(agents        = type_list,
                        sow_vars      = ['pNow'],
                        reap_vars     = ['sNow'],
                        track_vars    = ['pNow'],
                        dyn_vars      = ['pNextIntercept','pNextSlope','pNextWidth'],
                        millRule      = calcPunkProp,
                        calcDynamics  = calcFashionEvoFunc,
                        act_T         = 1000,
                        tolerance     = 0.01)
    TestMarket.pNow_init = 0.5

    TestMarket.solve()
    plt.plot(TestMarket.pNow_hist)
    plt.show()
Beispiel #5
0
KSEconomy.makeAggShkHist()  # Make a simulated history of the economy

# Solve macro problem by finding a fixed point for beliefs

KSEconomy.solve()  # Solve the economy using the market method.
# i.e. guess the saving function, and iterate until a fixed point

# %% [markdown]
# The last line above is the converged aggregate saving rule for good and bad times, respectively.

# %% {"code_folding": []}
# Plot some key results

print('Aggregate savings as a function of aggregate market resources:')
plotFuncs(KSEconomy.AFunc, 0.1, 2 * KSEconomy.kSS)

print(
    'Consumption function at each aggregate market resources gridpoint (in general equilibrium):'
)
KSAgent.unpackcFunc()
m_grid = np.linspace(0, 10, 200)
KSAgent.unpackcFunc()
for M in KSAgent.Mgrid:
    c_at_this_M = KSAgent.solution[0].cFunc[0](
        m_grid,
        M * np.ones_like(m_grid))  #Have two consumption functions, check this
    plt.plot(m_grid, c_at_this_M)
plt.show()

print(
# A particular perfect foresight agent's problem can be characterized by values of risk aversion $\rho$, discount factor $\beta$, and return factor $R$, along with sequences of income growth factors $\{ \Gamma_t \}$ and survival probabilities $\{\LivPrb_t = \LivPrb = 1\}$ (which are allowed to vary by age but which for present purposes we will assume are time invariant at $\LivPrb$.  To keep things simple, let's forget about "sequences" of income growth and mortality, and just think about an $\textit{infinite horizon}$ consumer with constant income growth and survival probability of $\LivFac=1$.
#
#
# Solve the model described above and in [PerfForesightCRRA](http://econ.jhu.edu/people/ccarroll/public/lecturenotes/consumption/PerfForesightCRRA)

# %%
PFexample = PerfForesightConsumerType(**Params.init_perfect_foresight)
PFexample.cycles = 0 # Make this type have an infinite horizon

PFexample.solve()
PFexample.unpackcFunc()

# Plot the perfect foresight consumption function
print('Linear consumption function:')
mMin = PFexample.solution[0].mNrmMin
plotFuncs(PFexample.cFunc[0],mMin,mMin+10)

PFexample.timeFwd()
PFexample.T_sim = 120 # Set number of simulation periods
PFexample.track_vars = ['mNrmNow']
PFexample.initializeSim()
PFexample.simulate()

# %% [markdown]
# ## Consumer with idiosyncratic income shocks
#
# Solve a model like the one analyzed in [BufferStockTheory](http://econ.jhu.edu/people/ccarroll/papers/BufferStockTheory/)
#
# Specifically, our new type of consumer receives two income shocks at the beginning of each period: a completely transitory shock $\newcommand{\tShkEmp}{\theta}{\tShkEmp_t}$ and a completely permanent shock $\newcommand{\pShk}{\psi}{\pShk_t}$.  Moreover, lenders will not let the agent borrow money such that his ratio of end-of-period assets $A_t$ to permanent income $P_t$ is less than $\underline{a}$.  As with the perfect foresight problem, this model can be framed in terms of $\textit{normalized}$ variables, e.g. $m_t \equiv M_t/P_t$.  (See [here](http://econ.jhu.edu/people/ccarroll/papers/BufferStockTheory/) for all the theory).
#
# \begin{eqnarray*}
Beispiel #7
0
# First, we define a standard lifecycle model, solve it and then

# %%
from HARK.ConsumptionSaving.ConsIndShockModel import IndShockConsumerType, init_lifecycle
import numpy as np
import matplotlib.pyplot as plt
LifecycleExample = IndShockConsumerType(init_lifecycle)
LifecycleExample.cycles = 1 # Make this consumer live a sequence of periods exactly once
LifecycleExample.solve()

# %% [markdown]
# Let's have a look at the solution in time period second period. We should then be able to

# %%
from HARK.utilities import plotFuncs
plotFuncs([LifecycleExample.solution[0].cFunc],LifecycleExample.solution[0].mNrmMin,10)

# %% [markdown]
# Let us then create a solver for the first period.

# %%
from HARK.ConsumptionSaving.ConsIndShockModel import ConsIndShockSolverBasic
solver = ConsIndShockSolverBasic(LifecycleExample.solution[1],
                                 LifecycleExample.IncomeDstn[0],
                                 LifecycleExample.LivPrb[0],
                                 LifecycleExample.DiscFac,
                                 LifecycleExample.CRRA,
                                 LifecycleExample.Rfree,
                                 LifecycleExample.PermGroFac[0],
                                 LifecycleExample.BoroCnstArt,
                                 LifecycleExample.aXtraGrid,
    np.array(4 * SerialUnemploymentExample.PermGroFac)
]
SerialUnemploymentExample.LivPrb = [SerialUnemploymentExample.LivPrb * np.ones(4)]

# %%
# Solve the serial unemployment consumer's problem and display solution
start_time = process_time()
SerialUnemploymentExample.solve()
end_time = process_time()
print(
    "Solving a Markov consumer with serially correlated unemployment took "
    + mystr(end_time - start_time)
    + " seconds."
)
print("Consumption functions for each discrete state:")
plotFuncs(SerialUnemploymentExample.solution[0].cFunc, 0, 50)
if SerialUnemploymentExample.vFuncBool:
    print("Value functions for each discrete state:")
    plotFuncs(SerialUnemploymentExample.solution[0].vFunc, 5, 50)

# %%
# Simulate some data; results stored in cHist, mNrmNow_hist, cNrmNow_hist, and MrkvNow_hist
if do_simulation:
    SerialUnemploymentExample.T_sim = 120
    SerialUnemploymentExample.MrkvPrbsInit = [0.25, 0.25, 0.25, 0.25]
    SerialUnemploymentExample.track_vars = ["mNrmNow", "cNrmNow"]
    SerialUnemploymentExample.makeShockHistory()  # This is optional
    SerialUnemploymentExample.initializeSim()
    SerialUnemploymentExample.simulate()

# %% [markdown]
Beispiel #9
0
    BasicType = Model.IndShockConsumerType(**Params.init_idiosyncratic_shocks)
    BasicType.cycles = 0
    BasicType(aXtraMax=100, aXtraCount=64)
    BasicType(vFuncBool=False, CubicBool=True)
    BasicType.updateAssetsGrid()
    BasicType.timeFwd()

    # Solve the basic type and plot the results, to make sure things are working
    start_time = clock()
    BasicType.solve()
    end_time = clock()
    print('Solving the basic consumer took ' + mystr(end_time - start_time) +
          ' seconds.')
    BasicType.unpackcFunc()
    print('Consumption function:')
    plotFuncs(BasicType.cFunc[0], 0, 5)  # plot consumption
    print('Marginal consumption function:')
    plotFuncsDer(BasicType.cFunc[0], 0, 5)  # plot MPC
    if BasicType.vFuncBool:
        print('Value function:')
        plotFuncs(BasicType.solution[0].vFunc, 0.2, 5)

    # Make many copies of the basic type, each with a different risk aversion
    BasicType.vFuncBool = False  # just in case it was set to True above
    my_agent_list = []
    CRRA_list = np.linspace(
        1, 8, type_count)  # All the values that CRRA will take on
    for i in range(type_count):
        this_agent = deepcopy(BasicType)  # Make a new copy of the basic type
        this_agent.assignParameters(
            CRRA=CRRA_list[i])  # Give it a unique CRRA value
# %%
print(PFexample.solution)

# %% [markdown]
# Each element of $\texttt{solution}$ has a few attributes. To see all of them, we can use the $\texttt{vars}$ built in function: the consumption functions are instantiated in the attribute $\texttt{cFunc}$ of each element of $\texttt{ConsumerType.solution}$.  This method creates a (time varying) attribute $\texttt{cFunc}$ that contains a list of consumption functions by age.

# %%
print(vars(PFexample.solution[0]))

# %% [markdown]
# The two most important attributes of a single period solution are the (normalized) consumption function $\texttt{cFunc}$ and the (normalized) value function $\texttt{vFunc}$; the marginal value function $\texttt{vPfunc}$ is also constructed.  Let's plot those functions near the lower bound of the permissible state space (the attribute $\texttt{mNrmMin}$ tells us the lower bound of $m_t$ where the consumption function is defined).

# %%
print('Linear perfect foresight consumption function:')
mMin = PFexample.solution[0].mNrmMin
plotFuncs(PFexample.solution[0].cFunc,mMin,mMin+10.)

# %%
print('Perfect foresight value function:')
plotFuncs(PFexample.solution[0].vFunc,mMin+0.1,mMin+10.1)

# %% [markdown]
# ## Solution Method
#
#
# ### Recursive Formula for $\kappa_{t}$
#
# The paper [BufferStockTheory](https://www.econ2.jhu.edu/people/ccarroll/papers/BufferStockTheory/) has a few other results that are used in the solution code.  One is [the recursive formula for the MPC](https://www.econ2.jhu.edu/people/ccarroll/papers/BufferStockTheory/#MPCnvrs). Starting with the last period, in which $\kappa_{T}=1$, the inverse MPC's (and therefore the MPC's themselves) can be constructed using the recursive formula:
#
# \begin{align}
# \kappa_{t}^{-1} & = & 1 + \kappa_{t+1}^{-1}(\Rfree \beta)^{1/\rho}/G 
Beispiel #11
0
t0 = time()
print("Now solving for the equilibrium of the Krusell-Smith (1998) model.  This might take a few minutes...")
KSeconomy.solve()
t1 = time()
print('Solving the Krusell-Smith model took ' + str(t1-t0) + ' seconds.')

# %%
# Plot the consumption function for each discrete state
state_names = ['bad economy, unemployed', 'bad economy, employed',
               'good economy, unemployed', 'good economy, employed']

for j in range(4):
    plt.xlabel(r'Idiosyncratic market resources $m$')
    plt.ylabel(r'Consumption $c$')
    plt.title('Consumption function by aggregate market resources: ' + state_names[j])
    plotFuncs(KStype.solution[0].cFunc[j].xInterpolators, 0., 50.)

# %%
# Extract history of aggregate capital and run a serial autoregression
mystr = lambda x : '{:.4f}'.format(x)
mystr2 = lambda x : '{:.7f}'.format(x)
K_hist = np.array(KSeconomy.history['Aprev'])[KSeconomy.T_discard:]
Mrkv_hist = KSeconomy.MrkvNow_hist[KSeconomy.T_discard:]
bad = Mrkv_hist[:-1] == 0
good = Mrkv_hist[:-1] == 1
logK_t = np.log(K_hist[:-1])
logK_tp1 = np.log(K_hist[1:])
results_bad = linregress(logK_t[bad], logK_tp1[bad])
results_good = linregress(logK_t[good], logK_tp1[good])
print('')
print('Equilibrium dynamics of aggregate capital:')
Beispiel #12
0
print('Normalized consumption function by pLvl for explicit permanent income consumer:')
pLvlGrid = ExplicitExample.pLvlGrid[0]
mNrmGrid = np.linspace(0,20,300)
for p in pLvlGrid:
    M_temp = mNrmGrid*p + ExplicitExample.solution[0].mLvlMin(p)
    C = ExplicitExample.solution[0].cFunc(M_temp,p*np.ones_like(M_temp))
    plt.plot(M_temp/p,C/p)

plt.xlim(0.,20.)
plt.xlabel('Normalized market resources mNrm')
plt.ylabel('Normalized consumption cNrm')
plt.show()

print('Consumption function for normalized problem (without explicit permanent income):')
mNrmMin = NormalizedExample.solution[0].mNrmMin
plotFuncs(NormalizedExample.solution[0].cFunc,mNrmMin,mNrmMin+20.)

# %% [markdown]
# The figures above show that the normalized consumption function for the "explicit permanent income" consumer is almost identical for every permanent income level (and the same as the normalized problem's $\texttt{cFunc}$), but is less accurate due to extrapolation outside the bounds of $\texttt{pLvlGrid}$. 
#
# The "explicit permanent income" solution deviates from the solution to the normalized problem because of errors from extrapolating beyond the bounds of the $\texttt{pLvlGrid}$. The error is largest for $\texttt{pLvl}$ values near the upper and lower bounds, and propagates toward the center of the distribution.
#

# %%
# Plot the value function at various permanent income levels
if ExplicitExample.vFuncBool:
    pGrid = np.linspace(0.1,3.0,24)
    M = np.linspace(0.001,5,300)
    for p in pGrid:
        M_temp = M+ExplicitExample.solution[0].mLvlMin(p)
        C = ExplicitExample.solution[0].vFunc(M_temp,p*np.ones_like(M_temp))
def main():
    # Import the HARK library.  The assumption is that this code is in a folder
    # contained in the HARK folder.  Also import the ConsumptionSavingModel
    import numpy as np  # numeric Python
    from HARK.utilities import plotFuncs  # basic plotting tools
    from .ConsMarkovModel import MarkovConsumerType  # An alternative, much longer way to solve the TBS model
    from time import clock  # timing utility

    do_simulation = True

    # Define the model primitives
    base_primitives = {
        'UnempPrb': .00625,  # Probability of becoming unemployed
        'DiscFac': 0.975,  # Intertemporal discount factor
        'Rfree': 1.01,  # Risk-free interest factor on assets
        'PermGroFac': 1.0025,  # Permanent income growth factor (uncompensated)
        'CRRA': 1.0
    }  # Coefficient of relative risk aversion

    # Define a dictionary to be used in case of simulation
    simulation_values = {
        'aLvlInitMean': 0.0,  # Mean of log initial assets for new agents
        'aLvlInitStd': 1.0,  # Stdev of log initial assets for new agents
        'AgentCount': 10000,  # Number of agents to simulate
        'T_sim': 120,  # Number of periods to simulate
        'T_cycle': 1
    }  # Number of periods in the cycle

    # Make and solve a tractable consumer type
    ExampleType = TractableConsumerType(**base_primitives)
    t_start = clock()
    ExampleType.solve()
    t_end = clock()
    print('Solving a tractable consumption-savings model took ' +
          str(t_end - t_start) + ' seconds.')

    # Plot the consumption function and whatnot
    m_upper = 1.5 * ExampleType.mTarg
    conFunc_PF = lambda m: ExampleType.h * ExampleType.PFMPC + ExampleType.PFMPC * m
    #plotFuncs([ExampleType.solution[0].cFunc,ExampleType.mSSfunc,ExampleType.cSSfunc],0,m_upper)
    plotFuncs([ExampleType.solution[0].cFunc, ExampleType.solution[0].cFunc_U],
              0, m_upper)

    if do_simulation:
        ExampleType(**
                    simulation_values)  # Set attributes needed for simulation
        ExampleType.track_vars = ['mLvlNow']
        ExampleType.makeShockHistory()
        ExampleType.initializeSim()
        ExampleType.simulate()

    # Now solve the same model using backward induction rather than the analytic method of TBS.
    # The TBS model is equivalent to a Markov model with two states, one of them absorbing (permanent unemployment).
    MrkvArray = np.array(
        [[1.0 - base_primitives['UnempPrb'], base_primitives['UnempPrb']],
         [0.0,
          1.0]])  # Define the two state, absorbing unemployment Markov array
    init_consumer_objects = {
        "CRRA":
        base_primitives['CRRA'],
        "Rfree":
        np.array(2 * [base_primitives['Rfree']
                      ]),  # Interest factor (same in both states)
        "PermGroFac": [
            np.array(2 * [
                base_primitives['PermGroFac'] /
                (1.0 - base_primitives['UnempPrb'])
            ])
        ],  # Unemployment-compensated permanent growth factor
        "BoroCnstArt":
        None,  # Artificial borrowing constraint
        "PermShkStd": [0.0],  # Permanent shock standard deviation
        "PermShkCount":
        1,  # Number of shocks in discrete permanent shock distribution
        "TranShkStd": [0.0],  # Transitory shock standard deviation
        "TranShkCount":
        1,  # Number of shocks in discrete permanent shock distribution
        "T_cycle":
        1,  # Number of periods in cycle
        "UnempPrb":
        0.0,  # Unemployment probability (not used, as the unemployment here is *permanent*, not transitory)
        "UnempPrbRet":
        0.0,  # Unemployment probability when retired (irrelevant here)
        "T_retire":
        0,  # Age at retirement (turned off)
        "IncUnemp":
        0.0,  # Income when unemployed (irrelevant)
        "IncUnempRet":
        0.0,  # Income when unemployed and retired (irrelevant)
        "aXtraMin":
        0.001,  # Minimum value of assets above minimum in grid
        "aXtraMax":
        ExampleType.mUpperBnd,  # Maximum value of assets above minimum in grid
        "aXtraCount":
        48,  # Number of points in assets grid
        "aXtraExtra": [None],  # Additional points to include in assets grid
        "aXtraNestFac":
        3,  # Degree of exponential nesting when constructing assets grid
        "LivPrb": [np.array([1.0, 1.0])],  # Survival probability
        "DiscFac":
        base_primitives['DiscFac'],  # Intertemporal discount factor
        'AgentCount':
        1,  # Number of agents in a simulation (irrelevant)
        'tax_rate':
        0.0,  # Tax rate on labor income (irrelevant)
        'vFuncBool':
        False,  # Whether to calculate the value function
        'CubicBool':
        True,  # Whether to use cubic splines (False --> linear splines)
        'MrkvArray': [MrkvArray]  # State transition probabilities
    }
    MarkovType = MarkovConsumerType(
        **init_consumer_objects)  # Make a basic consumer type
    employed_income_dist = [np.ones(1), np.ones(1),
                            np.ones(1)]  # Income distribution when employed
    unemployed_income_dist = [
        np.ones(1), np.ones(1), np.zeros(1)
    ]  # Income distribution when permanently unemployed
    MarkovType.IncomeDstn = [[employed_income_dist, unemployed_income_dist]
                             ]  # set the income distribution in each state
    MarkovType.cycles = 0

    # Solve the "Markov TBS" model
    t_start = clock()
    MarkovType.solve()
    t_end = clock()
    MarkovType.unpackcFunc()

    print('Solving the same model "the long way" took ' +
          str(t_end - t_start) + ' seconds.')
    #plotFuncs([ExampleType.solution[0].cFunc,ExampleType.solution[0].cFunc_U],0,m_upper)
    plotFuncs(MarkovType.cFunc[0], 0, m_upper)
    diffFunc = lambda m: ExampleType.solution[0].cFunc(m) - MarkovType.cFunc[
        0][0](m)
    print('Difference between the (employed) consumption functions:')
    plotFuncs(diffFunc, 0, m_upper)
    plt.ylim(0.0, None)
    plt.show()

if solve_agg_shocks_market:
    # Solve the "macroeconomic" model by searching for a "fixed point dynamic rule"
    t_start = process_time()
    print(
        "Now solving for the equilibrium of a Cobb-Douglas economy.  This might take a few minutes..."
    )
    EconomyExample.solve()
    t_end = process_time()
    print('Solving the "macroeconomic" aggregate shocks model took ' +
          str(t_end - t_start) + " seconds.")

    print("Aggregate savings as a function of aggregate market resources:")
    plotFuncs(EconomyExample.AFunc, 0, 2 * EconomyExample.kSS)
    print(
        "Consumption function at each aggregate market resources gridpoint (in general equilibrium):"
    )
    AggShockExample.unpack('cFunc')
    m_grid = np.linspace(0, 10, 200)
    AggShockExample.unpack('cFunc')
    for M in AggShockExample.Mgrid.tolist():
        mMin = AggShockExample.solution[0].mNrmMin(M)
        c_at_this_M = AggShockExample.cFunc[0](m_grid + mMin,
                                               M * np.ones_like(m_grid))
        plt.plot(m_grid + mMin, c_at_this_M)
    plt.ylim(0.0, None)
    plt.show()

# ### Example Implementations of AggShockMarkovConsumerType
# Running the $\texttt{solve}$ method creates the **attribute** of $\texttt{PFexample}$ named $\texttt{solution}.$  In fact, every subclass of $\texttt{AgentType}$ works the same way: The class definition contains the abstract algorithm that knows how to solve the model, but to obtain the particular solution for a specific instance (paramterization/configuration), that instance must be instructed to $\texttt{solve()}$ its problem.
#
# The $\texttt{solution}$ attribute is always a _list_ of solutions to a single period of the problem. In the case of an infinite horizon model like the one here, there is just one element in that list -- the solution to all periods of the infinite horizon problem.  The consumption function stored as the first element (element 0) of the solution list can be retrieved by:

# %%
PFexample.solution[0].cFunc

# %% [markdown]
# One of the results proven in the associated [the lecture notes](http://econ.jhu.edu/people/ccarroll/public/lecturenotes/consumption/PerfForesightCRRA/) is that, for the specific problem defined above, there is a solution in which the _ratio_ $c = C/P$ is a linear function of the _ratio_ of market resources to permanent income, $m = M/P$.
#
# This is why $\texttt{cFunc}$ can be represented by a linear interpolation.  It can be plotted using the command below:
#

# %%
mPlotTop = 10
plotFuncs(PFexample.solution[0].cFunc, 0., mPlotTop)

# %% [markdown]
# The figure illustrates one of the surprising features of the perfect foresight model: A person with zero money should be spending at a rate more than double their income ($\texttt{cFunc}(0.) \approx 2.08$). What gives?
#
# The answer is that we have not incorporated any constraint that would prevent the agent from borrowing against the entire PDV of future earnings -- human wealth.
#
# How much is that?  An equivalent question is: What's the minimum value of $m_t$ where the consumption function is defined (that is, where the consumer has a positive expected _total wealth_ (the sum of human and nonuman wealth)?  Let's check:

# %%
humanWealth = PFexample.solution[0].hNrm
mMinimum = PFexample.solution[0].mNrmMin
print("This agent's human wealth is " + str(humanWealth) +
      ' times his current income level.')
print("This agent's consumption function is defined down to m_t = " +
      str(mMinimum))
Beispiel #16
0
# Create an instance of the type of consumer we are interested in
KinkyExample = KinkedRconsumerType(**Params.init_kinked_R) 

# Make the example infinite horizon (not a life cycle model)
KinkyExample.cycles = 0 

# The consumer cannot borrow more than 0.4 times their permanent income
KinkyExample.BoroCnstArt = -0.4

# Solve the consumer's problem
KinkyExample.solve()

# Plot the results 
plt.ylabel('Consumption c')
plt.xlabel('Market Resources m')
plotFuncs([KinkyExample.solution[0].cFunc],KinkyExample.solution[0].mNrmMin,5)
# -

# 'Market Resources' $M$ is the total amount of money (assets plus current income) available to the consumer when the consumption decision is made.  Lower case $m = M/P$ is the ratio of $M$ to permanent income.  Likewise, $c = C/P$ is the ratio of consumption to permanent income.
#
# The line segment near $m=1$ captures the interval over which the consumer spends all of their market resources, because it's not worth it to borrow at the high credit card interest rate, but also not worth it to save at the low bank account interest rate.  
#
# The bottommost point on the consumption function is at $m=-0.4$, where consumption is zero.  This consumer would like to borrow to finance spending out of future income, but is already at the maximum borrowing limit.  
#
# The consumption function has a linear portion with a slope of 45 degrees along which the marginal propensity to consume out of extra market resources is 1.  But eventually resources get high enough that the consumer is willing to spend less than the maximum possible amount; this concave part of the consumption function terminates at the point where the consumer's desired borrowing reaches zero: The bottommost point on the line segment discussed above.

# ### Solution With A Tighter Constraint
#
# We are now interested in the solution to the problem when the constraint is tighter; concretely, the maximum amount of borrowing allowed is now 0.2, rather than 0.4.
#
Beispiel #17
0
            "aXtraMax": 50.0,
            "aXtraNestFac": 3,
            "aXtraCount": 48,
            "aXtraExtra": [None],
        })
        example = ConsIndShockModel.IndShockConsumerType(**params)
    else:
        params = copy.deepcopy(params)
        params.pop("PermShkStd", None)
        params.pop("TranShkStd", None)
        example = ConsIndShockModel.PerfForesightConsumerType(**params)
    examples.append(example)
    results.append(st.empty())

for i, example in enumerate(examples):
    example.solve()
    results[i].markdown(
        f"**Model {1+i}** agent's human wealth is {example.solution[0].hNrm:.02f} times "
        f"his current income level, with its consumption function is defined (consumption is "
        f"positive) down to m_t = {example.solution[0].mNrmMin:.02f}.")

st.pyplot(
    plotFuncs(
        [e.solution[0].cFunc for e in examples],
        0.0,
        10,
        legend_kwds={
            "labels": [f"Model {1 + i}" for i in range(len(examples))]
        },
    ))
Beispiel #18
0
               'pCount'        : pCount,
               'pref_shock_mag': pref_shock_mag,
               'pNextIntercept': pNextIntercept,
               'pNextSlope'    : pNextSlope,
               'pNextWidth'    : pNextWidth,
               'pNextCount'    : pNextCount,
               'pop_size'      : pop_size,
               'p_init'        : p_init
               }
# -

# Then we can create our test object via passing previously defined parameters.

TestType = FashionVictimType(**default_params)
print('Utility function:')
plotFuncs(TestType.conformUtilityFunc,0,1)

# To solve the TestType we can simply use solve method.

TestType.solve()

# And here we can observe the solution from illustrations.

print('Jock value function:')
plotFuncs(TestType.VfuncJock,0,1)
print('Punk value function:')
plotFuncs(TestType.VfuncPunk,0,1)
print('Jock switch probability:')
plotFuncs(TestType.switchFuncJock,0,1)
print('Punk switch probability:')
plotFuncs(TestType.switchFuncPunk,0,1)
        self.Bgrid = []
        for i in range(200):
            if Bgrid_uc[0, i] > -self.phi:
                self.Bgrid.append(Bgrid_uc[0, i])
        self.Bgrid = np.array(self.Bgrid).reshape(1, len(self.Bgrid))

        #initial Guess for Cpolicy
        Cguess = np.maximum(
            (self.Rfree - 1) * np.ones(13).reshape(13, 1).dot(self.Bgrid),
            cmin)

        self.solution_terminal_ = GLConsumerSolution(Cpol=Cguess, )

        AgentType.__init__(self,
                           solution_terminal=deepcopy(self.solution_terminal_),
                           cycles=cycles,
                           pseudo_terminal=False,
                           **kwds)

        self.verbose = verbose
        self.quiet = quiet
        self.solveOnePeriod = makeOnePeriodOOSolver(GLsolver)
        #set_verbosity_level((4 - verbose) * 10)


#-------------------------------------------------------------------------------
example = GLconsType(**init_GL)
example.solve()
plotFuncs(example.solution[0].cFuncs[2][0], -2, 12)
plotFuncs(example.solution[1].cFuncs[2][0], -2, 12)
# %%
# Make and solve a tractable consumer type
ExampleType = TractableConsumerType(**base_primitives)
t_start = process_time()
ExampleType.solve()
t_end = process_time()
print("Solving a tractable consumption-savings model took " +
      str(t_end - t_start) + " seconds.")

# %%
# Plot the consumption function and whatnot
m_upper = 1.5 * ExampleType.mTarg
conFunc_PF = lambda m: ExampleType.h * ExampleType.PFMPC + ExampleType.PFMPC * m
# plotFuncs([ExampleType.solution[0].cFunc,ExampleType.mSSfunc,ExampleType.cSSfunc],0,m_upper)
plotFuncs([ExampleType.solution[0].cFunc, ExampleType.solution[0].cFunc_U], 0,
          m_upper)

# %%
if do_simulation:
    ExampleType(**simulation_values)  # Set attributes needed for simulation
    ExampleType.track_vars = ["mLvlNow"]
    ExampleType.makeShockHistory()
    ExampleType.initializeSim()
    ExampleType.simulate()

# %%
# Now solve the same model using backward induction rather than the analytic method of TBS.
# The TBS model is equivalent to a Markov model with two states, one of them absorbing (permanent unemployment).
MrkvArray = np.array(
    [[1.0 - base_primitives["UnempPrb"], base_primitives["UnempPrb"]],
     [0.0, 1.0]])  # Define the two state, absorbing unemployment Markov array
Beispiel #21
0
def main():

    ###############################################################################
    ########## SMALL OPEN ECONOMY WITH MACROECONOMIC MARKOV STATE##################
    ###############################################################################

    if do_SOE:
        if run_models:
            # Make consumer types to inhabit the small open Markov economy
            StickySOEmarkovBaseType = StickyEmarkovConsumerType(
                **Params.init_SOE_mrkv_consumer)
            StickySOEmarkovBaseType.IncomeDstn[0] = Params.StateCount * [
                StickySOEmarkovBaseType.IncomeDstn[0]
            ]
            StickySOEmarkovBaseType.track_vars = [
                'aLvlNow', 'cLvlNow', 'yLvlNow', 'pLvlTrue', 't_age',
                'TranShkNow'
            ]
            StickySOEmarkovConsumers = []
            for n in range(Params.TypeCount):
                StickySOEmarkovConsumers.append(
                    deepcopy(StickySOEmarkovBaseType))
                StickySOEmarkovConsumers[-1].seed = n
                StickySOEmarkovConsumers[-1].DiscFac = Params.DiscFacSetSOE[n]

            # Make a small open economy for the agents
            StickySOmarkovEconomy = SmallOpenMarkovEconomy(
                agents=StickySOEmarkovConsumers, **Params.init_SOE_mrkv_market)
            StickySOmarkovEconomy.track_vars += ['TranShkAggNow', 'wRteNow']
            StickySOmarkovEconomy.makeAggShkHist(
            )  # Simulate a history of aggregate shocks
            for n in range(Params.TypeCount):
                StickySOEmarkovConsumers[n].getEconomyData(
                    StickySOmarkovEconomy
                )  # Have the consumers inherit relevant objects from the economy

            # Solve the small open Markov model
            t_start = clock()
            StickySOmarkovEconomy.solveAgents()
            t_end = clock()
            print('Solving the small open Markov economy took ' +
                  mystr(t_end - t_start) + ' seconds.')

            # Plot the consumption function in each Markov state
            print(
                'Consumption function for one type in the small open Markov economy:'
            )
            m = np.linspace(0, 20, 500)
            M = np.ones_like(m)
            c = np.zeros((Params.StateCount, m.size))
            for i in range(Params.StateCount):
                c[i, :] = StickySOEmarkovConsumers[0].solution[0].cFunc[i](m,
                                                                           M)
                plt.plot(m, c[i, :])
            plt.show()

            # Simulate the sticky small open Markov economy
            t_start = clock()
            for agent in StickySOmarkovEconomy.agents:
                agent(UpdatePrb=Params.UpdatePrb)
            StickySOmarkovEconomy.makeHistory()
            t_end = clock()
            print('Simulating the sticky small open Markov economy took ' +
                  mystr(t_end - t_start) + ' seconds.')

            # Make results for the sticky small open Markov economy
            desc = 'Results for the sticky small open Markov economy with update probability ' + mystr(
                Params.UpdatePrb)
            name = 'SOEmarkovSticky'
            makeStickyEdataFile(StickySOmarkovEconomy,
                                ignore_periods,
                                description=desc,
                                filename=name,
                                save_data=save_data,
                                calc_micro_stats=calc_micro_stats)
            if calc_micro_stats:
                sticky_SOEmarkov_micro_data = extractSampleMicroData(
                    StickySOmarkovEconomy,
                    np.minimum(
                        StickySOmarkovEconomy.act_T - ignore_periods - 1,
                        periods_to_sim_micro),
                    np.minimum(StickySOmarkovEconomy.agents[0].AgentCount,
                               AgentCount_micro), ignore_periods)
            DeltaLogC_stdev = np.genfromtxt(
                results_dir + 'SOEmarkovStickyResults.csv',
                delimiter=',')[3]  # For use in frictionless spec

            # Simulate the frictionless small open Markov economy
            t_start = clock()
            for agent in StickySOmarkovEconomy.agents:
                agent(UpdatePrb=1.0)
            StickySOmarkovEconomy.makeHistory()
            t_end = clock()
            print(
                'Simulating the frictionless small open Markov economy took ' +
                mystr(t_end - t_start) + ' seconds.')

            # Make results for the frictionless small open Markov economy
            desc = 'Results for the frictionless small open Markov economy (update probability 1.0)'
            name = 'SOEmarkovFrictionless'
            makeStickyEdataFile(StickySOmarkovEconomy,
                                ignore_periods,
                                description=desc,
                                filename=name,
                                save_data=save_data,
                                calc_micro_stats=calc_micro_stats,
                                meas_err_base=DeltaLogC_stdev)
            if calc_micro_stats:
                frictionless_SOEmarkov_micro_data = extractSampleMicroData(
                    StickySOmarkovEconomy,
                    np.minimum(
                        StickySOmarkovEconomy.act_T - ignore_periods - 1,
                        periods_to_sim_micro),
                    np.minimum(StickySOmarkovEconomy.agents[0].AgentCount,
                               AgentCount_micro), ignore_periods)
                makeMicroRegressionTable('CGrowCross', [
                    frictionless_SOEmarkov_micro_data,
                    sticky_SOEmarkov_micro_data
                ])

            if run_ucost_vs_pi:
                # Find the birth value and cost of stickiness as it varies with updating probability
                UpdatePrbVec = np.linspace(0.025, 1.0, 40)
                CRRA = StickySOmarkovEconomy.agents[0].CRRA
                vBirth_F = np.genfromtxt(results_dir +
                                         'SOEmarkovFrictionlessBirthValue.csv',
                                         delimiter=',')
                uCostVec = np.zeros_like(UpdatePrbVec)
                vVec = np.zeros_like(UpdatePrbVec)
                for j in range(UpdatePrbVec.size):
                    for agent in StickySOmarkovEconomy.agents:
                        agent(UpdatePrb=UpdatePrbVec[j])
                    StickySOmarkovEconomy.makeHistory()
                    makeStickyEdataFile(StickySOmarkovEconomy,
                                        ignore_periods,
                                        description='trash',
                                        filename='TEMP',
                                        save_data=False,
                                        calc_micro_stats=True)
                    vBirth_S = np.genfromtxt(results_dir +
                                             'TEMPBirthValue.csv',
                                             delimiter=',')
                    uCost = np.mean(1. - (vBirth_S / vBirth_F)**(1. /
                                                                 (1. - CRRA)))
                    uCostVec[j] = uCost
                    vVec[j] = np.mean(vBirth_S)
                    print('Found that uCost=' + str(uCost) + ' for Pi=' +
                          str(UpdatePrbVec[j]))
                with open(results_dir + 'SOEuCostbyUpdatePrb.csv', 'w') as f:
                    my_writer = csv.writer(f, delimiter=',')
                    my_writer.writerow(UpdatePrbVec)
                    my_writer.writerow(uCostVec)
                    f.close()
                with open(results_dir + 'SOEvVecByUpdatePrb.csv', 'w') as f:
                    my_writer = csv.writer(f, delimiter=',')
                    my_writer.writerow(UpdatePrbVec)
                    my_writer.writerow(vVec)
                    f.close()
                os.remove(results_dir + 'TEMPResults.csv')
                os.remove(results_dir + 'TEMPBirthValue.csv')

            if run_value_vs_aggvar:
                # Find value as it varies with updating probability
                PermShkAggVarBase = np.linspace(0.5, 1.5, 40)
                PermShkAggVarVec = PermShkAggVarBase * Params.PermShkAggVar
                vVec = np.zeros_like(PermShkAggVarVec)
                for j in range(PermShkAggVarVec.size):
                    StickySOmarkovEconomy.PermShkAggStd = Params.StateCount * [
                        np.sqrt(PermShkAggVarVec[j])
                    ]
                    StickySOmarkovEconomy.makeAggShkDstn()
                    StickySOmarkovEconomy.makeAggShkHist()
                    for agent in StickySOmarkovEconomy.agents:
                        agent(UpdatePrb=1.0)
                        agent.getEconomyData(StickySOmarkovEconomy)
                    StickySOmarkovEconomy.solveAgents()
                    StickySOmarkovEconomy.makeHistory()
                    makeStickyEdataFile(StickySOmarkovEconomy,
                                        ignore_periods,
                                        description='trash',
                                        filename='TEMP',
                                        save_data=False,
                                        calc_micro_stats=True)
                    vBirth_S = np.genfromtxt(results_dir +
                                             'TEMPBirthValue.csv',
                                             delimiter=',')
                    v = np.mean(vBirth_S)
                    vVec[j] = v
                    print('Found that v=' + str(v) + ' for PermShkAggVar=' +
                          str(PermShkAggVarVec[j]))
                with open(results_dir + 'SOEvVecByPermShkAggVar.csv',
                          'w') as f:
                    my_writer = csv.writer(f, delimiter=',')
                    my_writer.writerow(PermShkAggVarVec)
                    my_writer.writerow(vVec)
                    f.close()
                os.remove(results_dir + 'TEMPResults.csv')
                os.remove(results_dir + 'TEMPBirthValue.csv')

        # Process the coefficients, standard errors, etc into a LaTeX table
        if make_tables:
            t_start = clock()
            frictionless_panel = runRegressions('SOEmarkovFrictionlessData',
                                                interval_size, False, False,
                                                True)
            frictionless_me_panel = runRegressions('SOEmarkovFrictionlessData',
                                                   interval_size, True, False,
                                                   True)
            frictionless_long_panel = runRegressions(
                'SOEmarkovFrictionlessData', interval_size * interval_count,
                True, False, True)
            sticky_panel = runRegressions('SOEmarkovStickyData', interval_size,
                                          False, True, True)
            sticky_me_panel = runRegressions('SOEmarkovStickyData',
                                             interval_size, True, True, True)
            sticky_long_panel = runRegressions('SOEmarkovStickyData',
                                               interval_size * interval_count,
                                               True, True, True)
            makeResultsTable('Aggregate Consumption Dynamics in SOE Model',
                             [frictionless_me_panel, sticky_me_panel],
                             my_counts, 'SOEmrkvSimReg', 'tPESOEsim')
            makeResultsTable('Aggregate Consumption Dynamics in SOE Model',
                             [frictionless_panel, sticky_panel], my_counts,
                             'SOEmrkvSimRegNoMeasErr', 'tPESOEsimNoMeasErr')
            makeResultsTable('Aggregate Consumption Dynamics in SOE Model',
                             [frictionless_long_panel, sticky_long_panel],
                             alt_counts, 'SOEmrkvSimRegLong', 'tSOEsimLong')
            makeResultsTable(None, [frictionless_me_panel], my_counts,
                             'SOEmrkvSimRegF', 'tPESOEsimF')
            makeResultsTable(None, [sticky_me_panel], my_counts,
                             'SOEmrkvSimRegS', 'tPESOEsimS')
            t_end = clock()
            print(
                'Running time series regressions for the small open Markov economy took '
                + mystr(t_end - t_start) + ' seconds.')

    ###############################################################################
    ########## COBB-DOUGLAS ECONOMY WITH MACROECONOMIC MARKOV STATE ###############
    ###############################################################################

    if do_DSGE:
        if run_models:
            # Make consumers who will live in the Cobb-Douglas Markov economy
            StickyDSGEmarkovBaseType = StickyEmarkovConsumerType(
                **Params.init_DSGE_mrkv_consumer)
            StickyDSGEmarkovBaseType.IncomeDstn[0] = Params.StateCount * [
                StickyDSGEmarkovBaseType.IncomeDstn[0]
            ]
            StickyDSGEmarkovBaseType.track_vars = [
                'aLvlNow', 'cLvlNow', 'yLvlNow', 'pLvlTrue', 't_age',
                'TranShkNow'
            ]
            StickyDSGEmarkovConsumers = []
            for n in range(Params.TypeCount):
                StickyDSGEmarkovConsumers.append(
                    deepcopy(StickyDSGEmarkovBaseType))
                StickyDSGEmarkovConsumers[-1].seed = n
                StickyDSGEmarkovConsumers[-1].DiscFac = Params.DiscFacSetDSGE[
                    n]

            # Make a Cobb-Douglas economy for the agents
            StickyDSGEmarkovEconomy = StickyCobbDouglasMarkovEconomy(
                agents=StickyDSGEmarkovConsumers,
                **Params.init_DSGE_mrkv_market)
            StickyDSGEmarkovEconomy.track_vars += [
                'RfreeNow', 'wRteNow', 'TranShkAggNow'
            ]
            StickyDSGEmarkovEconomy.overwrite_hist = False
            StickyDSGEmarkovEconomy.makeAggShkHist(
            )  # Simulate a history of aggregate shocks
            for n in range(Params.TypeCount):
                StickyDSGEmarkovConsumers[n].getEconomyData(
                    StickyDSGEmarkovEconomy
                )  # Have the consumers inherit relevant objects from the economy
                StickyDSGEmarkovConsumers[n](UpdatePrb=Params.UpdatePrb)

            # Solve the sticky heterogeneous agent DSGE model
            t_start = clock()
            StickyDSGEmarkovEconomy.solve()
            t_end = clock()
            print('Solving the sticky Cobb-Douglas Markov economy took ' +
                  mystr(t_end - t_start) + ' seconds.')

            print(
                'Displaying the consumption functions for the Cobb-Douglas Markov economy would be too much.'
            )

            # Make results for the sticky Cobb-Douglas Markov economy
            desc = 'Results for the sticky Cobb-Douglas Markov economy with update probability ' + mystr(
                Params.UpdatePrb)
            name = 'DSGEmarkovSticky'
            makeStickyEdataFile(StickyDSGEmarkovEconomy,
                                ignore_periods,
                                description=desc,
                                filename=name,
                                save_data=save_data,
                                calc_micro_stats=calc_micro_stats)
            DeltaLogC_stdev = np.genfromtxt(
                results_dir + 'DSGEmarkovStickyResults.csv',
                delimiter=',')[3]  # For use in frictionless spec
            if calc_micro_stats:
                sticky_DSGEmarkov_micro_data = extractSampleMicroData(
                    StickyDSGEmarkovEconomy,
                    np.minimum(
                        StickyDSGEmarkovEconomy.act_T - ignore_periods - 1,
                        periods_to_sim_micro),
                    np.minimum(StickyDSGEmarkovEconomy.agents[0].AgentCount,
                               AgentCount_micro), ignore_periods)

            # Store the histories of MaggNow, wRteNow, and Rfree now in _overwrite attributes
            StickyDSGEmarkovEconomy.MaggNow_overwrite = deepcopy(
                StickyDSGEmarkovEconomy.MaggNow_hist)
            StickyDSGEmarkovEconomy.wRteNow_overwrite = deepcopy(
                StickyDSGEmarkovEconomy.wRteNow_hist)
            StickyDSGEmarkovEconomy.RfreeNow_overwrite = deepcopy(
                StickyDSGEmarkovEconomy.RfreeNow_hist)

            # Calculate the lifetime value of being frictionless when all other agents are sticky
            if calc_micro_stats:
                StickyDSGEmarkovEconomy.overwrite_hist = True  # History will be overwritten by sticky outcomes
                for agent in StickyDSGEmarkovEconomy.agents:
                    agent(UpdatePrb=1.0)  # Make agents frictionless
                StickyDSGEmarkovEconomy.makeHistory(
                )  # Simulate a history one more time

                # Save the birth value file in a temporary file and delete the other generated results files
                makeStickyEdataFile(StickyDSGEmarkovEconomy,
                                    ignore_periods,
                                    description=desc,
                                    filename=name + 'TEMP',
                                    save_data=False,
                                    calc_micro_stats=calc_micro_stats)
                os.remove(results_dir + name + 'TEMP' + 'Results.csv')
                sticky_name = name

            # Solve the frictionless heterogeneous agent DSGE model
            StickyDSGEmarkovEconomy.overwrite_hist = False
            for agent in StickyDSGEmarkovEconomy.agents:
                agent(UpdatePrb=1.0)
            t_start = clock()
            StickyDSGEmarkovEconomy.solve()
            t_end = clock()
            print(
                'Solving the frictionless Cobb-Douglas Markov economy took ' +
                mystr(t_end - t_start) + ' seconds.')

            print(
                'Displaying the consumption functions for the Cobb-Douglas Markov economy would be too much.'
            )

            # Make results for the frictionless Cobb-Douglas Markov economy
            desc = 'Results for the frictionless Cobb-Douglas Markov economy (update probability 1.0)'
            name = 'DSGEmarkovFrictionless'
            makeStickyEdataFile(StickyDSGEmarkovEconomy,
                                ignore_periods,
                                description=desc,
                                filename=name,
                                save_data=save_data,
                                calc_micro_stats=calc_micro_stats,
                                meas_err_base=DeltaLogC_stdev)
            if calc_micro_stats:
                os.remove(results_dir + name + 'BirthValue.csv'
                          )  # Delete the frictionless birth value file
                os.rename(
                    results_dir + sticky_name + 'TEMPBirthValue.csv',
                    results_dir + name + 'BirthValue.csv'
                )  # Replace just deleted file with "alternate" value calculation
                frictionless_DSGEmarkov_micro_data = extractSampleMicroData(
                    StickyDSGEmarkovEconomy,
                    np.minimum(
                        StickyDSGEmarkovEconomy.act_T - ignore_periods - 1,
                        periods_to_sim_micro),
                    np.minimum(StickyDSGEmarkovEconomy.agents[0].AgentCount,
                               AgentCount_micro), ignore_periods)
                makeMicroRegressionTable('CGrowCrossDSGE', [
                    frictionless_DSGEmarkov_micro_data,
                    sticky_DSGEmarkov_micro_data
                ])

        # Process the coefficients, standard errors, etc into a LaTeX table
        if make_tables:
            t_start = clock()
            frictionless_panel = runRegressions('DSGEmarkovFrictionlessData',
                                                interval_size, False, False,
                                                True)
            frictionless_me_panel = runRegressions(
                'DSGEmarkovFrictionlessData', interval_size, True, False, True)
            frictionless_long_panel = runRegressions(
                'DSGEmarkovFrictionlessData', interval_size * interval_count,
                True, False, True)
            sticky_panel = runRegressions('DSGEmarkovStickyData',
                                          interval_size, False, True, True)
            sticky_me_panel = runRegressions('DSGEmarkovStickyData',
                                             interval_size, True, True, True)
            sticky_long_panel = runRegressions('DSGEmarkovStickyData',
                                               interval_size * interval_count,
                                               True, True, True)
            makeResultsTable('Aggregate Consumption Dynamics in HA-DSGE Model',
                             [frictionless_me_panel, sticky_me_panel],
                             my_counts, 'DSGEmrkvSimReg', 'tDSGEsim')
            makeResultsTable('Aggregate Consumption Dynamics in HA-DSGE Model',
                             [frictionless_panel, sticky_panel], my_counts,
                             'DSGEmrkvSimRegNoMeasErr', 'tDSGEsimNoMeasErr')
            makeResultsTable('Aggregate Consumption Dynamics in HA-DSGE Model',
                             [frictionless_long_panel, sticky_long_panel],
                             alt_counts, 'DSGEmrkvSimRegLong', 'tDSGEsimLong')
            makeResultsTable(None, [frictionless_me_panel], my_counts,
                             'DSGEmrkvSimRegF', 'tDSGEsimF')
            makeResultsTable(None, [sticky_me_panel], my_counts,
                             'DSGEmrkvSimRegS', 'tDSGEsimS')
            t_end = clock()
            print(
                'Running time series regressions for the Cobb-Douglas Markov economy took '
                + mystr(t_end - t_start) + ' seconds.')

    ###############################################################################
    ########### REPRESENTATIVE AGENT ECONOMY WITH MARKOV STATE ####################
    ###############################################################################

    if do_RA:
        if run_models:
            # Make a representative agent consumer, then solve and simulate the model
            StickyRAmarkovConsumer = StickyEmarkovRepAgent(
                **Params.init_RA_mrkv_consumer)
            StickyRAmarkovConsumer.IncomeDstn[0] = Params.StateCount * [
                StickyRAmarkovConsumer.IncomeDstn[0]
            ]
            StickyRAmarkovConsumer.track_vars = [
                'cLvlNow', 'yNrmTrue', 'aLvlNow', 'pLvlTrue', 'TranShkNow',
                'MrkvNow'
            ]

            # Solve the representative agent Markov economy
            t_start = clock()
            StickyRAmarkovConsumer.solve()
            t_end = clock()
            print('Solving the representative agent Markov economy took ' +
                  mystr(t_end - t_start) + ' seconds.')

            print('Consumption functions for the Markov representative agent:')
            plotFuncs(StickyRAmarkovConsumer.solution[0].cFunc, 0, 50)

            # Simulate the sticky representative agent Markov economy
            t_start = clock()
            StickyRAmarkovConsumer(UpdatePrb=Params.UpdatePrb)
            StickyRAmarkovConsumer.initializeSim()
            StickyRAmarkovConsumer.simulate()
            t_end = clock()
            print(
                'Simulating the sticky representative agent Markov economy took '
                + mystr(t_end - t_start) + ' seconds.')

            # Make results for the sticky representative agent economy
            desc = 'Results for the sticky representative agent Markov economy'
            name = 'RAmarkovSticky'
            makeStickyEdataFile(StickyRAmarkovConsumer,
                                ignore_periods,
                                description=desc,
                                filename=name,
                                save_data=save_data,
                                calc_micro_stats=calc_micro_stats)
            DeltaLogC_stdev = np.genfromtxt(
                results_dir + 'RAmarkovStickyResults.csv',
                delimiter=',')[3]  # For use in frictionless spec

            # Simulate the frictionless representative agent Markov economy
            t_start = clock()
            StickyRAmarkovConsumer(UpdatePrb=1.0)
            StickyRAmarkovConsumer.initializeSim()
            StickyRAmarkovConsumer.simulate()
            t_end = clock()
            print(
                'Simulating the frictionless representative agent Markov economy took '
                + mystr(t_end - t_start) + ' seconds.')

            # Make results for the frictionless representative agent economy
            desc = 'Results for the frictionless representative agent Markov economy (update probability 1.0)'
            name = 'RAmarkovFrictionless'
            makeStickyEdataFile(StickyRAmarkovConsumer,
                                ignore_periods,
                                description=desc,
                                filename=name,
                                save_data=save_data,
                                calc_micro_stats=calc_micro_stats,
                                meas_err_base=DeltaLogC_stdev)

        if make_tables:
            # Process the coefficients, standard errors, etc into a LaTeX table
            t_start = clock()
            frictionless_panel = runRegressions('RAmarkovFrictionlessData',
                                                interval_size, False, False,
                                                True)
            frictionless_me_panel = runRegressions('RAmarkovFrictionlessData',
                                                   interval_size, True, False,
                                                   True)
            frictionless_long_panel = runRegressions(
                'RAmarkovFrictionlessData', interval_size * interval_count,
                True, False, True)
            sticky_panel = runRegressions('RAmarkovStickyData', interval_size,
                                          False, True, True)
            sticky_me_panel = runRegressions('RAmarkovStickyData',
                                             interval_size, True, True, True)
            sticky_long_panel = runRegressions('RAmarkovStickyData',
                                               interval_size * interval_count,
                                               True, True, True)
            makeResultsTable('Aggregate Consumption Dynamics in RA Model',
                             [frictionless_me_panel, sticky_me_panel],
                             my_counts, 'RepAgentMrkvSimReg', 'tRAsim')
            makeResultsTable('Aggregate Consumption Dynamics in RA Model',
                             [frictionless_panel, sticky_panel], my_counts,
                             'RepAgentMrkvSimRegNoMeasErr', 'tRAsimNoMeasErr')
            makeResultsTable('Aggregate Consumption Dynamics in RA Model',
                             [frictionless_long_panel, sticky_long_panel],
                             alt_counts, 'RepAgentMrkvSimRegLong',
                             'tRAsimLong')
            t_end = clock()
            print(
                'Running time series regressions for the representative agent Markov economy took '
                + mystr(t_end - t_start) + ' seconds.')

    ###############################################################################
    ########### MAKE OTHER TABLES AND FIGURES #####################################
    ###############################################################################
    if make_tables:
        makeEquilibriumTable('Eqbm', [
            'SOEmarkovFrictionless', 'SOEmarkovSticky',
            'DSGEmarkovFrictionless', 'DSGEmarkovSticky'
        ], Params.init_SOE_consumer['CRRA'])
        makeParameterTable('Calibration', Params)

    if run_ucost_vs_pi:
        makeuCostVsPiFig('SOEuCostbyUpdatePrb')
        makeValueVsPiFig('SOEvVecByUpdatePrb')

    if run_value_vs_aggvar:
        makeValueVsAggShkVarFig('SOEvVecByPermShkAggVar')
Beispiel #22
0
#
# The cell below creates an infinite horizon instance of $\texttt{KinkedRconsumerType}$ and solves its model by calling its $\texttt{solve}$ method.

# %%
KinkyExample = KinkedRconsumerType(**KinkedRdict)
KinkyExample.cycles = 0  # Make the example infinite horizon
KinkyExample.solve()

# %% [markdown]
# An element of a $\texttt{KinkedRconsumerType}$'s solution will have all the same attributes as that of a $\texttt{IndShockConsumerType}$; see that notebook for details.
#
# We can plot the consumption function of our "kinked R" example, as well as the MPC:

# %%
print("Kinked R consumption function:")
plotFuncs(KinkyExample.solution[0].cFunc, KinkyExample.solution[0].mNrmMin, 5)

print("Kinked R marginal propensity to consume:")
plotFuncsDer(KinkyExample.solution[0].cFunc, KinkyExample.solution[0].mNrmMin, 5)

# %% [markdown]
# ## Simulating the "kinked R" model
#
# In order to generate simulated data, an instance of $\texttt{KinkedRconsumerType}$ needs to know how many agents there are that share these particular parameters (and are thus *ex ante* homogeneous), the distribution of states for newly "born" agents, and how many periods to simulated.  These simulation parameters are described in the table below, along with example values.
#
# | Description | Code | Example value |
# | :---: | --- | --- |
# | Number of consumers of this type | $\texttt{AgentCount}$ | $10000$ |
# | Number of periods to simulate | $\texttt{T_sim}$ | $500$ |
# | Mean of initial log (normalized) assets | $\texttt{aNrmInitMean}$ | $-6.0$ |
# | Stdev of initial log  (normalized) assets | $\texttt{aNrmInitStd}$ | $1.0$ |
Beispiel #23
0
def main():
    import HARK.ConsumptionSaving.ConsumerParameters as Params
    import matplotlib.pyplot as plt
    from HARK.utilities import plotFuncs
    from time import clock
    mystr = lambda number: "{:.4f}".format(number)

    do_simulation = True

    # Make and solve a preference shock consumer
    PrefShockExample = PrefShockConsumerType(**Params.init_preference_shocks)
    PrefShockExample.cycles = 0  # Infinite horizon

    t_start = clock()
    PrefShockExample.solve()
    t_end = clock()
    print('Solving a preference shock consumer took ' + str(t_end - t_start) +
          ' seconds.')

    # Plot the consumption function at each discrete shock
    m = np.linspace(PrefShockExample.solution[0].mNrmMin, 5, 200)
    print('Consumption functions at each discrete shock:')
    for j in range(PrefShockExample.PrefShkDstn[0][1].size):
        PrefShk = PrefShockExample.PrefShkDstn[0][1][j]
        c = PrefShockExample.solution[0].cFunc(m, PrefShk * np.ones_like(m))
        plt.plot(m, c)
    plt.xlim([0., None])
    plt.ylim([0., None])
    plt.show()

    print('Consumption function (and MPC) when shock=1:')
    c = PrefShockExample.solution[0].cFunc(m, np.ones_like(m))
    k = PrefShockExample.solution[0].cFunc.derivativeX(m, np.ones_like(m))
    plt.plot(m, c)
    plt.plot(m, k)
    plt.xlim([0., None])
    plt.ylim([0., None])
    plt.show()

    if PrefShockExample.vFuncBool:
        print('Value function (unconditional on shock):')
        plotFuncs(PrefShockExample.solution[0].vFunc,
                  PrefShockExample.solution[0].mNrmMin + 0.5, 5)

    # Test the simulator for the pref shock class
    if do_simulation:
        PrefShockExample.T_sim = 120
        PrefShockExample.track_vars = ['cNrmNow']
        PrefShockExample.makeShockHistory()  # This is optional
        PrefShockExample.initializeSim()
        PrefShockExample.simulate()

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

    # Make and solve a "kinky preferece" consumer, whose model combines KinkedR and PrefShock
    KinkyPrefExample = KinkyPrefConsumerType(**Params.init_kinky_pref)
    KinkyPrefExample.cycles = 0  # Infinite horizon

    t_start = clock()
    KinkyPrefExample.solve()
    t_end = clock()
    print('Solving a kinky preference consumer took ' + str(t_end - t_start) +
          ' seconds.')

    # Plot the consumption function at each discrete shock
    m = np.linspace(KinkyPrefExample.solution[0].mNrmMin, 5, 200)
    print('Consumption functions at each discrete shock:')
    for j in range(KinkyPrefExample.PrefShkDstn[0][1].size):
        PrefShk = KinkyPrefExample.PrefShkDstn[0][1][j]
        c = KinkyPrefExample.solution[0].cFunc(m, PrefShk * np.ones_like(m))
        plt.plot(m, c)
    plt.ylim([0., None])
    plt.show()

    print('Consumption function (and MPC) when shock=1:')
    c = KinkyPrefExample.solution[0].cFunc(m, np.ones_like(m))
    k = KinkyPrefExample.solution[0].cFunc.derivativeX(m, np.ones_like(m))
    plt.plot(m, c)
    plt.plot(m, k)
    plt.ylim([0., None])
    plt.show()

    if KinkyPrefExample.vFuncBool:
        print('Value function (unconditional on shock):')
        plotFuncs(KinkyPrefExample.solution[0].vFunc,
                  KinkyPrefExample.solution[0].mNrmMin + 0.5, 5)

    # Test the simulator for the kinky preference class
    if do_simulation:
        KinkyPrefExample.T_sim = 120
        KinkyPrefExample.track_vars = ['cNrmNow', 'PrefShkNow']
        KinkyPrefExample.initializeSim()
        KinkyPrefExample.simulate()
RA_params = deepcopy(init_idiosyncratic_shocks)
RA_params["DeprFac"] = 0.05
RA_params["CapShare"] = 0.36
RA_params["UnempPrb"] = 0.0
RA_params["LivPrb"] = [1.0]

# %%
# Make and solve a rep agent model
RAexample = RepAgentConsumerType(**RA_params)
t_start = time()
RAexample.solve()
t_end = time()
print(
    "Solving a representative agent problem took " + str(t_end - t_start) + " seconds."
)
plotFuncs(RAexample.solution[0].cFunc, 0, 20)

# %%
# Simulate the representative agent model
RAexample.T_sim = 2000
RAexample.track_vars = ["cNrmNow", "mNrmNow", "Rfree", "wRte"]
RAexample.initializeSim()
t_start = time()
RAexample.simulate()
t_end = time()
print(
    "Simulating a representative agent for "
    + str(RAexample.T_sim)
    + " periods took "
    + str(t_end - t_start)
    + " seconds."
Beispiel #25
0
# Import a useful plotting function from HARK.utilities
from HARK.utilities import plotFuncs
import pylab as plt # We need this module to change the y-axis on the graphs


# Declare the upper limit for the graph
x_max = 10.


# Note that plotFuncs takes four arguments: (1) a list of the arguments to plot,
# (2) the lower bound for the plots, (3) the upper bound for the plots, and (4) keywords to pass
# to the legend for the plot.

# Plot the consumption functions to compare them
# The only difference is that the XtraCredit function has a credit limit that is looser
# by a tiny amount
print('The XtraCredit consumption function allows the consumer to spend a tiny bit more') 
print('The difference is so small that the baseline is obscured by the XtraCredit solution') 
plotFuncs([BaselineExample.solution[0].cFunc,XtraCreditExample.solution[0].cFunc],
           BaselineExample.solution[0].mNrmMin,x_max,
           legend_kwds = {'loc': 'upper left', 'labels': ["Baseline","XtraCredit"]})


# Plot the MPCs to compare them
print('MPC out of Credit v MPC out of Income')
plt.ylim([0.,1.2])
plotFuncs([FirstDiffMPC_Credit,FirstDiffMPC_Income],
          BaselineExample.solution[0].mNrmMin,x_max,
          legend_kwds = {'labels': ["MPC out of Credit","MPC out of Income"]})
Beispiel #26
0
# Hey, there's a lot of parameters we didn't tell you about!  Yes, but you don't need to
# think about them for now.

# %% [markdown]
# As before, we need to import the relevant subclass of $\texttt{AgentType}$ into our workspace, then create an instance by passing the dictionary to the class as if the class were a function.

# %%
from HARK.ConsumptionSaving.ConsIndShockModel import IndShockConsumerType
IndShockExample = IndShockConsumerType(**IndShockDictionary)

# %% [markdown]
# Now we can solve our new agent's problem just like before, using the $\texttt{solve}$ method.

# %%
IndShockExample.solve()
plotFuncs(IndShockExample.solution[0].cFunc, 0., 10.)

# %% [markdown]
# ## Changing Constructed Attributes
#
# In the parameter dictionary above, we chose values for HARK to use when constructing its numeric representation of $F_t$, the joint distribution of permanent and transitory income shocks. When $\texttt{IndShockExample}$ was created, those parameters ($\texttt{TranShkStd}$, etc) were used by the **constructor** or **initialization** method of $\texttt{IndShockConsumerType}$ to construct an attribute called $\texttt{IncomeDstn}$.
#
# Suppose you were interested in changing (say) the amount of permanent income risk.  From the section above, you might think that you could simply change the attribute $\texttt{TranShkStd}$, solve the model again, and it would work.
#
# That's _almost_ true-- there's one extra step. $\texttt{TranShkStd}$ is a primitive input, but it's not the thing you _actually_ want to change. Changing $\texttt{TranShkStd}$ doesn't actually update the income distribution... unless you tell it to (just like changing an agent's preferences does not change the consumption function that was stored for the old set of parameters -- until you invoke the $\texttt{solve}$ method again).  In the cell below, we invoke the method $\texttt{updateIncomeProcess}$ so HARK knows to reconstruct the attribute $\texttt{IncomeDstn}$.

# %%
OtherExample = deepcopy(
    IndShockExample)  # Make a copy so we can compare consumption functions
OtherExample.PermShkStd = [
    0.2
Beispiel #27
0
# %% [markdown]
# Each element of $\texttt{solution}$ has a few attributes. To see all of them, we can use the \texttt{vars} built in function:
#
# the consumption functions reside in the attribute $\texttt{cFunc}$ of each element of $\texttt{ConsumerType.solution}$.  This method creates a (time varying) attribute $\texttt{cFunc}$ that contains a list of consumption functions.

# %%
print(vars(PFexample.solution[0]))

# %% [markdown]
# The two most important attributes of a single period solution of this model are the (normalized) consumption function $\texttt{cFunc}$ and the (normalized) value function $\texttt{vFunc}$.  Let's plot those functions near the lower bound of the permissible state space (the attribute $\texttt{mNrmMin}$ tells us the lower bound of $m_t$ where the consumption function is defined).

# %%
print("Linear perfect foresight consumption function:")
mMin = PFexample.solution[0].mNrmMin
plotFuncs(PFexample.solution[0].cFunc, mMin, mMin + 10.0)

# %%
print("Perfect foresight value function:")
plotFuncs(PFexample.solution[0].vFunc, mMin + 0.1, mMin + 10.1)

# %% [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.
#
# ### Liquidity constrained perfect foresight example
#
# Without an artificial borrowing constraint, a perfect foresight consumer is free to borrow against the PDV of his entire future stream of labor income-- his "human wealth" $\texttt{hNrm}$-- and he will consume a constant proportion of his total wealth (market resources plus human wealth).  If we introduce an artificial borrowing constraint, both of these features vanish.  In the cell below, we define a parameter dictionary that prevents the consumer from borrowing *at all*, create and solve a new instance of $\texttt{PerfForesightConsumerType}$ with it, and then plot its consumption function.

# %% pycharm={"name": "#%%\n"}
LiqConstrDict = copy(PerfForesightDict)
LiqConstrDict["BoroCnstArt"] = 0.0  # Set the artificial borrowing constraint to zero
Beispiel #28
0
    'aNrmNow', 'pLvlNow', 'mNrmNow', 'cNrmNow', 'TranShkNow'
]

LifeCyclePop.T_sim = 120  # Nobody lives to be older than 145 years (=25+120)
LifeCyclePop.initializeSim(
)  # Construct the age-25 distribution of income and assets
LifeCyclePop.simulate(
)  # Simulate a population behaving according to this model

# %% {"code_folding": [0]}
# Plot the consumption functions during working life

print('Consumption as a function of market resources while working:')
mMin = min(
    [LifeCyclePop.solution[t].mNrmMin for t in range(LifeCyclePop.T_cycle)])
plotFuncs(LifeCyclePop.cFunc[:LifeCyclePop.T_retire], mMin, 5)


# %% {"code_folding": [0]}
# Define the saving rate function
def savingRateFunc(SomeType, m):
    """
    Parameters:
    ----------
        SomeType: 
             Agent type that has been solved and simulated.
        
        
    Returns:
    --------
        SavingRate: float
# %% [markdown]
# Now we can finally run our experiment.  In the cell below, we generate a plot of the change in aggregate consumption vs the (underlying) standard deviation of permanent income shocks.

# %% {"code_folding": [0]}
# Calculate the consequences of an "MIT shock" to the standard deviation of permanent shocks
ratio_min = 0.8  # minimum number to multiply uncertainty parameter by
TargetChangeInC = -6.3  # Source: FRED
num_points = 10  # number of parameter values to plot in graphs. More=slower

# First change the variance of the permanent income shock
perm_ratio_max = 2.0  # Put whatever value in you want!  maximum number to multiply std of perm income shock by

perm_min = BaselineType.PermShkStd[0] * ratio_min
perm_max = BaselineType.PermShkStd[0] * perm_ratio_max

plt.ylabel('% Change in Consumption')
plt.xlabel('Std. Dev. of Perm. Income Shock (Baseline = ' +
           str(round(BaselineType.PermShkStd[0], 2)) + ')')
plt.title('Change in Cons. Following Increase in Perm. Income Uncertainty')
plt.ylim(-20., 5.)
plt.hlines(TargetChangeInC, perm_min, perm_max)
# The expression below shows the power of python
plotFuncs([calcConsChangeAfterPermShkChange], perm_min, perm_max, N=num_points)

# %% [markdown] {"collapsed": true}
# The figure shows that if people's beliefs about the standard deviation of permanent shocks to their incomes had changed from 0.06 (the default value) to about 0.095, the model would predict an immediate drop in consumption spending of about the magnitude seen in 2008.
#
# The question is whether this is a reasonable or an unreasonable magnitude for a change in uncertainty.  Some perspective on that question is offered by the large literature that attempts to estimate the magnitude of persistent or permanent shocks to household income.  The answer varies substantially across household types, countries, and time periods, but our sense of the literature is that the whole span of the territory between 0.04 and ranging nearly up to 0.20 is well populated (in the sense that substantial populations of people or countries have been estimated to experience shocks of this magnitude).
#
# So, the degree to which income uncertainty would have had to rise in order to explain the drop in consumption in the Great Recession is quite moderate, compared to the variation that is estimated already to exist across people, places, times, and countries.
Beispiel #30
0
                'cLvlNow', 'yNrmTrue', 'aLvlNow', 'pLvlTrue', 'TranShkNow',
                'MrkvNow'
            ]

            # Solve the representative agent Markov economy
            t_start = clock()
            StickyRAmarkovConsumer.solve()
            t_end = clock()
            print('Solving the representative agent Markov economy took ' +
                  mystr(t_end - t_start) + ' seconds.')

            if verbose_main:
                print(
                    'Consumption functions for the Markov representative agent:'
                )
                plotFuncs(StickyRAmarkovConsumer.solution[0].cFunc, 0, 50)

            # Simulate the sticky representative agent Markov economy
            t_start = clock()
            StickyRAmarkovConsumer(UpdatePrb=Params.UpdatePrb)
            StickyRAmarkovConsumer.initializeSim()
            StickyRAmarkovConsumer.simulate()
            t_end = clock()
            print(
                'Simulating the sticky representative agent Markov economy took '
                + mystr(t_end - t_start) + ' seconds.')

            # Make results for the sticky representative agent economy
            desc = 'Results for the sticky representative agent Markov economy'
            name = 'RAmarkovSticky'
            makeStickyEdataFile(StickyRAmarkovConsumer,