Exemplo n.º 1
0
    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.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.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
Exemplo n.º 2
0
ratio_min = 1. # minimum number to multiply income parameter by
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 = ??? # 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)
Exemplo n.º 3
0
 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.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.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.sim_periods = 120
     PrefShockExample.makeIncShkHist()
     PrefShockExample.makePrefShkHist()
     PrefShockExample.initializeSim()
     PrefShockExample.simConsHistory()
     
 ###########################################################################
     
 # Make and solve a "kinky preferece" consumer, whose model combines KinkedR and PrefShock
 KinkyPrefExample = KinkyPrefConsumerType(**Params.init_kinky_pref)
 KinkyPrefExample.cycles = 0 # Infinite horizon
 
Exemplo n.º 4
0
    start_time = clock()
    LifecycleExample.solve()
    end_time = clock()
    print('Solving a lifecycle consumer took ' + mystr(end_time - start_time) +
          ' seconds.')
    LifecycleExample.unpackcFunc()
    LifecycleExample.timeFwd()

    # Plot the consumption functions during working life
    print('Consumption functions while working:')
    mMin = min([
        LifecycleExample.solution[t].mNrmMin
        for t in range(LifecycleExample.T_cycle)
    ])
    plotFuncs(LifecycleExample.cFunc[:LifecycleExample.T_retire], mMin, 5)

    # Plot the consumption functions during retirement
    print('Consumption functions while retired:')
    plotFuncs(LifecycleExample.cFunc[LifecycleExample.T_retire:], 0, 5)
    LifecycleExample.timeRev()

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

    # Make and solve a "cyclical" consumer type who lives the same four quarters repeatedly.
    # The consumer has income that greatly fluctuates throughout the year.
    CyclicalExample = IndShockConsumerType(**Params.init_cyclical)
    CyclicalExample.cycles = 0

    start_time = clock()
    CyclicalExample.solve()
Exemplo n.º 5
0
 # Have the consumers inherit relevant objects from the economy
 AggShockExample.getEconomyData(EconomyExample)
 
 # Solve the microeconomic model for the aggregate shocks example type (and display results)
 t_start = clock()
 AggShockExample.solve()
 t_end = clock()
 print('Solving an aggregate shocks consumer took ' + mystr(t_end-t_start) + ' seconds.')
 print('Consumption function at each capital-to-labor ratio gridpoint:')
 m_grid = np.linspace(0,10,200)
 AggShockExample.unpackcFunc()
 for k in AggShockExample.kGrid.tolist():
     c_at_this_k = AggShockExample.cFunc[0](m_grid,k*np.ones_like(m_grid))
     plt.plot(m_grid,c_at_this_k)
 plt.show()
 
 # Solve the "macroeconomic" model by searching for a "fixed point dynamic rule"
 t_start = clock()
 EconomyExample.solve()
 t_end = clock()
 print('Solving the "macroeconomic" aggregate shocks model took ' + str(t_end - t_start) + ' seconds.')
 print('Next capital-to-labor ratio as function of current ratio:')
 plotFuncs(EconomyExample.kNextFunc,0,2*EconomyExample.kSS)
 print('Consumption function at each capital-to-labor ratio gridpoint (in general equilibrium):')
 AggShockExample.unpackcFunc()
 m_grid = np.linspace(0,10,200)
 for k in AggShockExample.kGrid.tolist():
     c_at_this_k = AggShockExample.cFunc[0](m_grid,k*np.ones_like(m_grid))
     plt.plot(m_grid,c_at_this_k)
 plt.show()
 
Exemplo n.º 6
0
    t_end = clock()
    print('Solving an aggregate shocks consumer took ' +
          mystr(t_end - t_start) + ' seconds.')
    print('Consumption function at each capital-to-labor ratio gridpoint:')
    m_grid = np.linspace(0, 10, 200)
    AggShockExample.unpackcFunc()
    for k in AggShockExample.kGrid.tolist():
        c_at_this_k = AggShockExample.cFunc[0](m_grid,
                                               k * np.ones_like(m_grid))
        plt.plot(m_grid, c_at_this_k)
    plt.show()

    # Solve the "macroeconomic" model by searching for a "fixed point dynamic rule"
    t_start = clock()
    EconomyExample.solve()
    t_end = clock()
    print('Solving the "macroeconomic" aggregate shocks model took ' +
          str(t_end - t_start) + ' seconds.')
    print('Next capital-to-labor ratio as function of current ratio:')
    plotFuncs(EconomyExample.kNextFunc, 0, 2 * EconomyExample.kSS)
    print(
        'Consumption function at each capital-to-labor ratio gridpoint (in general equilibrium):'
    )
    AggShockExample.unpackcFunc()
    m_grid = np.linspace(0, 10, 200)
    for k in AggShockExample.kGrid.tolist():
        c_at_this_k = AggShockExample.cFunc[0](m_grid,
                                               k * np.ones_like(m_grid))
        plt.plot(m_grid, c_at_this_k)
    plt.show()
Exemplo n.º 7
0
## Now, plot the functions we want

# Import a useful plotting function from HARKutilities
from HARKutilities 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
print('Consumption functions:')
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"]})

Exemplo n.º 8
0
            StickySOEconomy.makeAggShkHist()
            for n in range(Params.TypeCount):
                StickySOEconsumers[n].getEconomyData(StickySOEconomy)

            # Solve the small open economy and display some output
            t_start = clock()
            StickySOEconomy.solveAgents()
            t_end = clock()
            print('Solving the small open economy took ' +
                  str(t_end - t_start) + ' seconds.')

            print(
                'Consumption function for one type in the small open economy:')
            cFunc = lambda m: StickySOEconsumers[0].solution[0].cFunc(
                m, np.ones_like(m))
            plotFuncs(cFunc, 0.0, 20.0)

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

            # Make results for the frictionless representative agent economy
            desc = 'Results for the frictionless small open economy (update probability 1.0)'
            name = 'SOEsimpleFrictionless'
            makeStickyEdataFile(StickySOEconomy,
                                ignore_periods,
Exemplo n.º 9
0
sys.path.insert(0,'../')

from HARKutilities import plotFunc, plotFuncs
import DiscreteChoice as Model
import numpy as np

x_grid = np.linspace(0,10,200)
sigma = 0.2

vFuncA = lambda x : x**0.5
vFuncB = lambda x : (2.0*(x-1.0))**0.5
vFuncC = lambda x : (3.0*(x-2.0))**0.5
vPfuncA = lambda x : 0.5*x**(-0.5)
vPfuncB = lambda x : (2.0*(x-1.0))**(-0.5)
vPfuncC = lambda x : 1.5*(3.0*(x-2.0))**(-0.5)

vFunc = [vFuncA, vFuncB, vFuncC]
vPfunc = [vPfuncA, vPfuncB, vPfuncC]

transFunc = lambda Z : Z
transFuncP = lambda Z : np.ones(Z.shape)
#transFunc = lambda x : x**2
#transFuncP = lambda x : 2*x

solution_tp1 = Model.DiscreteChoiceSolution(vFunc,vPfunc)
solution_tp1.bonus = 'break on through'

solution_t = Model.discreteChoiceContinuousStateSolver(solution_tp1,x_grid,sigma,transFunc,transFuncP)
plotFuncs([solution_t.vFunc,vFuncA,vFuncB,vFuncC],0,10)
plotFuncs([solution_t.vPfunc,vPfuncA,vPfuncB,vPfuncC],0,10)
Exemplo n.º 10
0
                          a_max = 20,
                          a_size = 48,
                          calc_vFunc = True,
                          cubic_splines = False,
                          constrained = True,
                          income_distrib = [None,TestType.income_distrib],
                          p_zero_income = [None,TestType.p_zero_income],
                          solveAPeriod = [discreteChoiceContinuousStateSolver, occupationalChoiceSolver],
                          tolerance = 0.0001,
                          cycles = 0)
TestType.updateAssetsGrid()
TestType.updateSolutionTerminal()
transformations = makeCRRAtransformations(TestType.rho,do_Q=True,do_T=True,do_Z=True)
TestType(transformations = transformations)
#TestType(transformations = None)
TestType.time_inv += ['transformations','state_grid']
TestType.time_vary += ['sigma_epsilon','solveAPeriod']

# Solve the income insurance problem
t_start = clock()
TestType.solve()
t_end = clock()
print('Took ' + str(t_end-t_start) + ' seconds to solve occupational choice problem.')

plotFuncs(TestType.solution[1].vFunc,0.1,3)
Q = transformations.Qfunc
f = lambda x : Q(TestType.solution[1].vFunc[2](x)) - Q(TestType.solution[1].vFunc[0](x))
g = lambda x : Q(TestType.solution[1].vFunc[1](x)) - Q(TestType.solution[1].vFunc[0](x))
plotFuncs([f, g],0.1,50)

Exemplo n.º 11
0
  # single-threading (looping), due to overhead.
  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
      my_agent_list.append(this_agent)   # Addd it to the list of agent types
      
Exemplo n.º 12
0
Params.init_consumer_objects['beta'] = 0.96
TestType = RetiringConsumerType(**Params.init_consumer_objects)
TestType(survival_prob = 0.9,
          beta = 0.96,
          Gamma = 1.00,
          rho = 2.0,
          sigma_epsilon = [0.0001,None],
          state_grid = setupGridsExpMult(0.001, 50, 64, 3),
          a_max = 20,
          a_size = 48,
          calc_vFunc = True,
          cubic_splines = False,
          constrained = True,
          income_distrib = [None,TestType.income_distrib],
          p_zero_income = [None,TestType.p_zero_income],
          labor_supply = 0.5,
          alpha = 1.0,
          tolerance = 0.0001,
          cycles=0)
TestType.updateAssetsGrid()
transformations = makeCRRAtransformations(TestType.rho,do_Q=True,do_T=True,do_Z=True)
TestType(transformations = transformations)

t_start = time()
TestType.solve()
t_end = time()
print('Took ' + str(t_end-t_start) + ' seconds to solve retirement choice problem.')

plotFuncs(TestType.solution[1].vFunc,20,100)
plotFunc(TestType.solution[0].vFunc,20,100)
Exemplo n.º 13
0
import scipy.stats as stats
import FashionVictimParams as Params
from copy import copy

from time import clock
from HARKcore 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)
Exemplo n.º 14
0
 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
     my_agent_list.append(this_agent)   # Addd it to the list of agent types
     
 # Make a list of commands to be run in parallel; these should be methods of ConsumerType
 do_this_stuff = ['updateSolutionTerminal()','solve()','unpack_cFunc()']
 
 # Solve the model for each type by looping over the types (not multithreading)
 start_time = clock()
 multiThreadCommandsFake(my_agent_list, do_this_stuff) # Fake multithreading, just loops
 end_time = clock()
 print('Solving ' + str(type_count) +  ' types without multithreading took ' + mystr(end_time-start_time) + ' seconds.')
 
 # Plot the consumption functions for all types on one figure
 plotFuncs([this_type.cFunc[0] for this_type in my_agent_list],0,5)
 
 # Delete the solution for each type to make sure we're not just faking it
 for i in range(type_count):
     my_agent_list[i].solution = None
     my_agent_list[i].cFunc = None
     my_agent_list[i].time_vary.remove('solution')
     my_agent_list[i].time_vary.remove('cFunc')
 
 # And here's HARK's initial attempt at multithreading:
 start_time = clock()
 multiThreadCommands(my_agent_list, do_this_stuff) # Actual multithreading
 end_time = clock()
 print('Solving ' + str(type_count) +  ' types with multithreading took ' + mystr(end_time-start_time) + ' seconds.')
 
 # Plot the consumption functions for all types on one figure to see if it worked
Exemplo n.º 15
0
    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
Exemplo n.º 16
0
  # single-threading (looping), due to overhead.
  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
      my_agent_list.append(this_agent)   # Addd it to the list of agent types
      
Exemplo n.º 17
0
    # 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]])
Exemplo n.º 18
0
                      '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
Exemplo n.º 19
0
    unemployed_income_dist = [np.ones(1),np.ones(1),np.zeros(1)] # Definitely don't
    SerialUnemploymentExample.IncomeDstn = [[employed_income_dist,unemployed_income_dist,employed_income_dist,
                              unemployed_income_dist]]
    
    # Interest factor and permanent growth rates are constant arrays
    SerialUnemploymentExample.Rfree = np.array(4*[SerialUnemploymentExample.Rfree])
    SerialUnemploymentExample.PermGroFac = [np.array(4*SerialUnemploymentExample.PermGroFac)]
    
    # Solve the serial unemployment consumer's problem and display solution
    SerialUnemploymentExample.timeFwd()
    start_time = clock()
    SerialUnemploymentExample.solve()
    end_time = clock()
    print('Solving a Markov consumer 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, mHist, bHist, aHist, MPChist, and pHist
    if do_simulation:
        SerialUnemploymentExample.sim_periods = 120
        SerialUnemploymentExample.Mrkv_init = np.zeros(SerialUnemploymentExample.Nagents,dtype=int)
        SerialUnemploymentExample.makeMrkvHist()
        SerialUnemploymentExample.makeIncShkHist()
        SerialUnemploymentExample.initializeSim()
        SerialUnemploymentExample.simConsHistory()
        
###############################################################################
Exemplo n.º 20
0
        my_agent_list.append(this_agent)  # Addd it to the list of agent types

    # Make a list of commands to be run in parallel; these should be methods of ConsumerType
    do_this_stuff = ['updateSolutionTerminal()', 'solve()', 'unpack_cFunc()']

    # Solve the model for each type by looping over the types (not multithreading)
    start_time = clock()
    multiThreadCommandsFake(my_agent_list,
                            do_this_stuff)  # Fake multithreading, just loops
    end_time = clock()
    print('Solving ' + str(type_count) +
          ' types without multithreading took ' +
          mystr(end_time - start_time) + ' seconds.')

    # Plot the consumption functions for all types on one figure
    plotFuncs([this_type.cFunc[0] for this_type in my_agent_list], 0, 5)

    # Delete the solution for each type to make sure we're not just faking it
    for i in range(type_count):
        my_agent_list[i].solution = None
        my_agent_list[i].cFunc = None
        my_agent_list[i].time_vary.remove('solution')
        my_agent_list[i].time_vary.remove('cFunc')

    # And here's HARK's initial attempt at multithreading:
    start_time = clock()
    multiThreadCommands(my_agent_list, do_this_stuff)  # Actual multithreading
    end_time = clock()
    print('Solving ' + str(type_count) + ' types with multithreading took ' +
          mystr(end_time - start_time) + ' seconds.')
Exemplo n.º 21
0
                      '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
Exemplo n.º 22
0
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.0


# 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
print("Consumption functions:")
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.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"]},
)
Exemplo n.º 23
0
###############################################################################
###############################################################################
if __name__ == '__main__':
    from time import clock
    from HARKcore 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)
        
Exemplo n.º 24
0
# Make a small open economy and the consumers who live in it
StickySOEconsumers     = StickyEconsumerSOEType(**init_SOE_consumer)
StickySOEconomy        = SmallOpenEconomy(**init_SOE_market)
StickySOEconomy.agents = [StickySOEconsumers]
StickySOEconomy.makeAggShkHist()
StickySOEconsumers.getEconomyData(StickySOEconomy)
StickySOEconsumers.track_vars = ['aLvlNow','mNrmNow','cNrmNow','pLvlNow','pLvlErrNow']

# Solve the model and display some output
StickySOEconomy.solveAgents()
StickySOEconomy.makeHistory()

# Plot some of the results
cFunc = lambda m : StickySOEconsumers.solution[0].cFunc(m,np.ones_like(m))
plotFuncs(cFunc,0.0,20.0)

plt.plot(np.mean(StickySOEconsumers.aLvlNow_hist,axis=1))
plt.show()

plt.plot(np.mean(StickySOEconsumers.mNrmNow_hist*StickySOEconsumers.pLvlNow_hist,axis=1))
plt.show()

plt.plot(np.mean(StickySOEconsumers.cNrmNow_hist*StickySOEconsumers.pLvlNow_hist,axis=1))
plt.show()

plt.plot(np.mean(StickySOEconsumers.pLvlNow_hist,axis=1))
plt.plot(np.mean(StickySOEconsumers.pLvlErrNow_hist,axis=1))
plt.show()

print('Average aggregate assets = ' + str(np.mean(StickySOEconsumers.aLvlNow_hist[ignore_periods:,:])))
Exemplo n.º 25
0
# Define the model primitives
base_primitives = {"mho": 0.015, "beta": 0.9, "R": 1.1, "G": 1.05, "rho": 0.95}


# Make and solve a tractable consumer type
ExampleType = Model.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.m_targ
conFunc_PF = lambda m: ExampleType.h * ExampleType.kappa_PF + ExampleType.kappa_PF * 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)

# Now solve the same model using backward induction
init_consumer_objects = {
    "rho": base_primitives["rho"],
    "R": base_primitives["R"],
    "Gamma": [base_primitives["G"] / (1.0 - base_primitives["mho"])],
    "constraint": False,
    "psi_sigma": [0.0],
    "psi_N": 1,
    "xi_sigma": [0.0],
    "xi_N": 1,
    "T_total": 1,
    "p_unemploy": 0.0,
    "p_unemploy_retire": 0.0,
    "T_retire": 0,