-
-
Notifications
You must be signed in to change notification settings - Fork 195
/
ConsIndShockModel.py
3890 lines (3277 loc) · 146 KB
/
ConsIndShockModel.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Classes to solve canonical consumption-saving models with idiosyncratic shocks
to income. All models here assume CRRA utility with geometric discounting, no
bequest motive, and income shocks that are fully transitory or fully permanent.
It currently solves three types of models:
1) A very basic "perfect foresight" consumption-savings model with no uncertainty.
2) A consumption-savings model with risk over transitory and permanent income shocks.
3) The model described in (2), with an interest rate for debt that differs
from the interest rate for savings.
See NARK https://HARK.githhub.io/Documentation/NARK for information on variable naming conventions.
See HARK documentation for mathematical descriptions of the models being solved.
"""
from copy import copy, deepcopy
import numpy as np
from scipy import sparse as sp
from scipy.optimize import newton
from HARK import (
AgentType,
MetricObject,
NullFunc,
_log,
make_one_period_oo_solver,
set_verbosity_level,
)
from HARK.Calibration.Income.IncomeTools import (
Cagetti_income,
parse_income_spec,
parse_time_params,
)
from HARK.datasets.life_tables.us_ssa.SSATools import parse_ssa_life_table
from HARK.datasets.SCF.WealthIncomeDist.SCFDistTools import income_wealth_dists_from_scf
from HARK.distribution import (
DiscreteDistribution,
IndexDistribution,
Lognormal,
MeanOneLogNormal,
Uniform,
add_discrete_outcome_constant_mean,
combine_indep_dstns,
expected,
)
from HARK.interpolation import CubicHermiteInterp as CubicInterp
from HARK.interpolation import (
CubicInterp,
LinearInterp,
LowerEnvelope,
MargMargValueFuncCRRA,
MargValueFuncCRRA,
ValueFuncCRRA,
)
from HARK.utilities import (
CRRAutility,
CRRAutility_inv,
CRRAutility_invP,
CRRAutilityP,
CRRAutilityP_inv,
CRRAutilityP_invP,
CRRAutilityPP,
construct_assets_grid,
gen_tran_matrix_1D,
gen_tran_matrix_2D,
jump_to_grid_1D,
jump_to_grid_2D,
make_grid_exp_mult,
)
__all__ = [
"ConsumerSolution",
"ConsPerfForesightSolver",
"ConsIndShockSetup",
"ConsIndShockSolverBasic",
"ConsIndShockSolver",
"ConsKinkedRsolver",
"PerfForesightConsumerType",
"IndShockConsumerType",
"KinkedRconsumerType",
"init_perfect_foresight",
"init_idiosyncratic_shocks",
"init_kinked_R",
"init_lifecycle",
"init_cyclical",
]
utility = CRRAutility
utilityP = CRRAutilityP
utilityPP = CRRAutilityPP
utilityP_inv = CRRAutilityP_inv
utility_invP = CRRAutility_invP
utility_inv = CRRAutility_inv
utilityP_invP = CRRAutilityP_invP
# =====================================================================
# === Classes that help solve consumption-saving models ===
# =====================================================================
class ConsumerSolution(MetricObject):
"""
A class representing the solution of a single period of a consumption-saving
problem. The solution must include a consumption function and marginal
value function.
Here and elsewhere in the code, Nrm indicates that variables are normalized
by permanent income.
Parameters
----------
cFunc : function
The consumption function for this period, defined over market
resources: c = cFunc(m).
vFunc : function
The beginning-of-period value function for this period, defined over
market resources: v = vFunc(m).
vPfunc : function
The beginning-of-period marginal value function for this period,
defined over market resources: vP = vPfunc(m).
vPPfunc : function
The beginning-of-period marginal marginal value function for this
period, defined over market resources: vPP = vPPfunc(m).
mNrmMin : float
The minimum allowable market resources for this period; the consump-
tion function (etc) are undefined for m < mNrmMin.
hNrm : float
Human wealth after receiving income this period: PDV of all future
income, ignoring mortality.
MPCmin : float
Infimum of the marginal propensity to consume this period.
MPC --> MPCmin as m --> infinity.
MPCmax : float
Supremum of the marginal propensity to consume this period.
MPC --> MPCmax as m --> mNrmMin.
"""
distance_criteria = ["vPfunc"]
def __init__(
self,
cFunc=None,
vFunc=None,
vPfunc=None,
vPPfunc=None,
mNrmMin=None,
hNrm=None,
MPCmin=None,
MPCmax=None,
):
# Change any missing function inputs to NullFunc
self.cFunc = cFunc if cFunc is not None else NullFunc()
self.vFunc = vFunc if vFunc is not None else NullFunc()
self.vPfunc = vPfunc if vPfunc is not None else NullFunc()
# vPFunc = NullFunc() if vPfunc is None else vPfunc
self.vPPfunc = vPPfunc if vPPfunc is not None else NullFunc()
self.mNrmMin = mNrmMin
self.hNrm = hNrm
self.MPCmin = MPCmin
self.MPCmax = MPCmax
def append_solution(self, new_solution):
"""
Appends one solution to another to create a ConsumerSolution whose
attributes are lists. Used in ConsMarkovModel, where we append solutions
*conditional* on a particular value of a Markov state to each other in
order to get the entire solution.
Parameters
----------
new_solution : ConsumerSolution
The solution to a consumption-saving problem; each attribute is a
list representing state-conditional values or functions.
Returns
-------
None
"""
if type(self.cFunc) != list:
# Then we assume that self is an empty initialized solution instance.
# Begin by checking this is so.
assert (
NullFunc().distance(self.cFunc) == 0
), "append_solution called incorrectly!"
# We will need the attributes of the solution instance to be lists. Do that here.
self.cFunc = [new_solution.cFunc]
self.vFunc = [new_solution.vFunc]
self.vPfunc = [new_solution.vPfunc]
self.vPPfunc = [new_solution.vPPfunc]
self.mNrmMin = [new_solution.mNrmMin]
else:
self.cFunc.append(new_solution.cFunc)
self.vFunc.append(new_solution.vFunc)
self.vPfunc.append(new_solution.vPfunc)
self.vPPfunc.append(new_solution.vPPfunc)
self.mNrmMin.append(new_solution.mNrmMin)
# =====================================================================
# === Classes and functions that solve consumption-saving models ===
# =====================================================================
class ConsPerfForesightSolver(MetricObject):
"""
A class for solving a one period perfect foresight
consumption-saving problem.
An instance of this class is created by the function solvePerfForesight
in each period.
Parameters
----------
solution_next : ConsumerSolution
The solution to next period's one-period problem.
DiscFac : float
Intertemporal discount factor for future utility.
LivPrb : float
Survival probability; likelihood of being alive at the beginning of
the next period.
CRRA : float
Coefficient of relative risk aversion.
Rfree : float
Risk free interest factor on end-of-period assets.
PermGroFac : float
Expected permanent income growth factor at the end of this period.
BoroCnstArt : float or None
Artificial borrowing constraint, as a multiple of permanent income.
Can be None, indicating no artificial constraint.
MaxKinks : int
Maximum number of kink points to allow in the consumption function;
additional points will be thrown out. Only relevant in infinite
horizon model with artificial borrowing constraint.
"""
def __init__(
self,
solution_next,
DiscFac,
LivPrb,
CRRA,
Rfree,
PermGroFac,
BoroCnstArt,
MaxKinks,
):
self.solution_next = solution_next
self.DiscFac = DiscFac
self.LivPrb = LivPrb
self.CRRA = CRRA
self.Rfree = Rfree
self.PermGroFac = PermGroFac
self.BoroCnstArt = BoroCnstArt
self.MaxKinks = MaxKinks
def def_utility_funcs(self):
"""
Defines CRRA utility function for this period (and its derivatives),
saving them as attributes of self for other methods to use.
Parameters
----------
None
Returns
-------
None
"""
self.u = lambda c: utility(c, gam=self.CRRA) # utility function
# marginal utility function
self.uP = lambda c: utilityP(c, gam=self.CRRA)
self.uPP = lambda c: utilityPP(
c, gam=self.CRRA
) # marginal marginal utility function
def def_value_funcs(self):
"""
Defines the value and marginal value functions for this period.
Uses the fact that for a perfect foresight CRRA utility problem,
if the MPC in period t is :math:`\kappa_{t}`, and relative risk
aversion :math:`\rho`, then the inverse value vFuncNvrs has a
constant slope of :math:`\kappa_{t}^{-\rho/(1-\rho)}` and
vFuncNvrs has value of zero at the lower bound of market resources
mNrmMin. See PerfForesightConsumerType.ipynb documentation notebook
for a brief explanation and the links below for a fuller treatment.
https://www.econ2.jhu.edu/people/ccarroll/public/lecturenotes/consumption/PerfForesightCRRA/#vFuncAnalytical
https://www.econ2.jhu.edu/people/ccarroll/SolvingMicroDSOPs/#vFuncPF
Parameters
----------
None
Returns
-------
None
"""
# See the PerfForesightConsumerType.ipynb documentation notebook for the derivations
vFuncNvrsSlope = self.MPCmin ** (-self.CRRA / (1.0 - self.CRRA))
vFuncNvrs = LinearInterp(
np.array([self.mNrmMinNow, self.mNrmMinNow + 1.0]),
np.array([0.0, vFuncNvrsSlope]),
)
self.vFunc = ValueFuncCRRA(vFuncNvrs, self.CRRA)
self.vPfunc = MargValueFuncCRRA(self.cFunc, self.CRRA)
def make_cFunc_PF(self):
"""
Makes the (linear) consumption function for this period.
Parameters
----------
None
Returns
-------
None
"""
# Use a local value of BoroCnstArt to prevent comparing None and float below.
if self.BoroCnstArt is None:
BoroCnstArt = -np.inf
else:
BoroCnstArt = self.BoroCnstArt
# Calculate human wealth this period
self.hNrmNow = (self.PermGroFac / self.Rfree) * (self.solution_next.hNrm + 1.0)
# Calculate the lower bound of the marginal propensity to consume
PatFac = ((self.Rfree * self.DiscFacEff) ** (1.0 / self.CRRA)) / self.Rfree
self.MPCmin = 1.0 / (1.0 + PatFac / self.solution_next.MPCmin)
# Extract the discrete kink points in next period's consumption function;
# don't take the last one, as it only defines the extrapolation and is not a kink.
mNrmNext = self.solution_next.cFunc.x_list[:-1]
cNrmNext = self.solution_next.cFunc.y_list[:-1]
# Calculate the end-of-period asset values that would reach those kink points
# next period, then invert the first order condition to get consumption. Then
# find the endogenous gridpoint (kink point) today that corresponds to each kink
aNrmNow = (self.PermGroFac / self.Rfree) * (mNrmNext - 1.0)
cNrmNow = (self.DiscFacEff * self.Rfree) ** (-1.0 / self.CRRA) * (
self.PermGroFac * cNrmNext
)
mNrmNow = aNrmNow + cNrmNow
# Add an additional point to the list of gridpoints for the extrapolation,
# using the new value of the lower bound of the MPC.
mNrmNow = np.append(mNrmNow, mNrmNow[-1] + 1.0)
cNrmNow = np.append(cNrmNow, cNrmNow[-1] + self.MPCmin)
# If the artificial borrowing constraint binds, combine the constrained and
# unconstrained consumption functions.
if BoroCnstArt > mNrmNow[0]:
# Find the highest index where constraint binds
cNrmCnst = mNrmNow - BoroCnstArt
CnstBinds = cNrmCnst < cNrmNow
idx = np.where(CnstBinds)[0][-1]
if idx < (mNrmNow.size - 1):
# If it is not the *very last* index, find the the critical level
# of mNrm where the artificial borrowing contraint begins to bind.
d0 = cNrmNow[idx] - cNrmCnst[idx]
d1 = cNrmCnst[idx + 1] - cNrmNow[idx + 1]
m0 = mNrmNow[idx]
m1 = mNrmNow[idx + 1]
alpha = d0 / (d0 + d1)
mCrit = m0 + alpha * (m1 - m0)
# Adjust the grids of mNrm and cNrm to account for the borrowing constraint.
cCrit = mCrit - BoroCnstArt
mNrmNow = np.concatenate(([BoroCnstArt, mCrit], mNrmNow[(idx + 1) :]))
cNrmNow = np.concatenate(([0.0, cCrit], cNrmNow[(idx + 1) :]))
else:
# If it *is* the very last index, then there are only three points
# that characterize the consumption function: the artificial borrowing
# constraint, the constraint kink, and the extrapolation point.
mXtra = (cNrmNow[-1] - cNrmCnst[-1]) / (1.0 - self.MPCmin)
mCrit = mNrmNow[-1] + mXtra
cCrit = mCrit - BoroCnstArt
mNrmNow = np.array([BoroCnstArt, mCrit, mCrit + 1.0])
cNrmNow = np.array([0.0, cCrit, cCrit + self.MPCmin])
# If the mNrm and cNrm grids have become too large, throw out the last
# kink point, being sure to adjust the extrapolation.
if mNrmNow.size > self.MaxKinks:
mNrmNow = np.concatenate((mNrmNow[:-2], [mNrmNow[-3] + 1.0]))
cNrmNow = np.concatenate((cNrmNow[:-2], [cNrmNow[-3] + self.MPCmin]))
# Construct the consumption function as a linear interpolation.
self.cFunc = LinearInterp(mNrmNow, cNrmNow)
# Calculate the upper bound of the MPC as the slope of the bottom segment.
self.MPCmax = (cNrmNow[1] - cNrmNow[0]) / (mNrmNow[1] - mNrmNow[0])
# Add two attributes to enable calculation of steady state market resources.
self.Ex_IncNext = 1.0 # Perfect foresight income of 1
# Relabeling for compatibility with add_mNrmStE
self.mNrmMinNow = mNrmNow[0]
def add_mNrmTrg(self, solution):
"""
Finds value of (normalized) market resources m at which individual consumer
expects m not to change.
This will exist if the GICNrm holds.
https://econ-ark.github.io/BufferStockTheory#UniqueStablePoints
Parameters
----------
solution : ConsumerSolution
Solution to this period's problem, which must have attribute cFunc.
Returns
-------
solution : ConsumerSolution
Same solution that was passed, but now with the attribute mNrmStE.
"""
# If no uncertainty, return the degenerate targets for the PF model
if hasattr(self, "TranShkMinNext"): # Then it has transitory shocks
# Handle the degenerate case where shocks are of size zero
if (self.TranShkMinNext == 1.0) and (self.PermShkMinNext == 1.0):
# but they are of zero size (and also permanent are zero)
if self.GICRaw: # max of nat and art boro cnst
if type(self.BoroCnstArt) == type(None):
solution.mNrmStE = -self.hNrmNow
solution.mNrmTrg = -self.hNrmNow
else:
bNrmNxt = -self.BoroCnstArt * self.Rfree / self.PermGroFac
solution.mNrmStE = bNrmNxt + 1.0
solution.mNrmTrg = bNrmNxt + 1.0
else: # infinity
solution.mNrmStE = float("inf")
solution.mNrmTrg = float("inf")
return solution
# First find
# \bar{\mathcal{R}} = E_t[R/Gamma_{t+1}] = R/Gamma E_t[1/psi_{t+1}]
if type(self) == ConsPerfForesightSolver:
Ex_PermShkInv = 1.0
else:
Ex_PermShkInv = np.dot(1 / self.PermShkValsNext, self.ShkPrbsNext)
Ex_RNrmFac = (self.Rfree / self.PermGroFac) * Ex_PermShkInv
# mNrmTrg solves Rcalbar*(m - c(m)) + E[inc_next] = m. Define a
# rearranged version.
Ex_m_tp1_minus_m_t = (
lambda m: Ex_RNrmFac * (m - solution.cFunc(m)) + self.Ex_IncNext - m
)
# Minimum market resources plus next income is okay starting guess
m_init_guess = self.mNrmMinNow + self.Ex_IncNext
try:
mNrmTrg = newton(Ex_m_tp1_minus_m_t, m_init_guess)
except:
mNrmTrg = None
# Add mNrmTrg to the solution and return it
solution.mNrmTrg = mNrmTrg
return solution
def add_mNrmStE(self, solution):
"""
Finds market resources ratio at which 'balanced growth' is expected.
This is the m ratio such that the expected growth rate of the M level
matches the expected growth rate of permanent income. This value does
not exist if the Growth Impatience Condition does not hold.
https://econ-ark.github.io/BufferStockTheory#Unique-Stable-Points
Parameters
----------
solution : ConsumerSolution
Solution to this period's problem, which must have attribute cFunc.
Returns
-------
solution : ConsumerSolution
Same solution that was passed, but now with the attribute mNrmStE
"""
# Probably should test whether GICRaw holds and log error if it does not
# using check_conditions
# All combinations of c and m that yield E[PermGroFac PermShkVal mNext] = mNow
# https://econ-ark.github.io/BufferStockTheory/#The-Individual-Steady-State
PF_RNrm = self.Rfree / self.PermGroFac
# If we are working with a model that permits uncertainty but that
# uncertainty has been set to zero, return the correct answer
# by hand because in this degenerate case numerical search may
# have trouble
if hasattr(self, "TranShkMinNext"): # Then it has transitory shocks
if (self.TranShkMinNext == 1.0) and (self.PermShkMinNext == 1.0):
# but they are of zero size (and permanent shocks also not there)
if self.GICRaw: # max of nat and art boro cnst
# breakpoint()
if type(self.BoroCnstArt) == type(None):
solution.mNrmStE = -self.hNrmNow
solution.mNrmTrg = -self.hNrmNow
else:
bNrmNxt = -self.BoroCnstArt * self.Rfree / self.PermGroFac
solution.mNrmStE = bNrmNxt + 1.0
solution.mNrmTrg = bNrmNxt + 1.0
else: # infinity
solution.mNrmStE = float("inf")
solution.mNrmTrg = float("inf")
return solution
Ex_PermShk_tp1_times_m_tp1_minus_m_t = (
lambda mStE: PF_RNrm * (mStE - solution.cFunc(mStE)) + 1.0 - mStE
)
# Minimum market resources plus next income is okay starting guess
m_init_guess = self.mNrmMinNow + self.Ex_IncNext
try:
mNrmStE = newton(Ex_PermShk_tp1_times_m_tp1_minus_m_t, m_init_guess)
except:
mNrmStE = None
solution.mNrmStE = mNrmStE
return solution
def add_stable_points(self, solution):
"""
Checks necessary conditions for the existence of the individual steady
state and target levels of market resources (see above).
If the conditions are satisfied, computes and adds the stable points
to the solution.
Parameters
----------
solution : ConsumerSolution
Solution to this period's problem, which must have attribute cFunc.
Returns
-------
solution : ConsumerSolution
Same solution that was provided, augmented with attributes mNrmStE and
mNrmTrg, if they exist.
"""
# 0. There is no non-degenerate steady state for any unconstrained PF model.
# 1. There is a non-degenerate SS for constrained PF model if GICRaw holds.
# Therefore
# Check if (GICRaw and BoroCnstArt) and if so compute them both
thorn = (self.Rfree * self.DiscFacEff) ** (1 / self.CRRA)
GICRaw = 1 > thorn / self.PermGroFac
if self.BoroCnstArt is not None and GICRaw:
solution = self.add_mNrmStE(solution)
solution = self.add_mNrmTrg(solution)
return solution
def solve(self):
"""
Solves the one period perfect foresight consumption-saving problem.
Parameters
----------
None
Returns
-------
solution : ConsumerSolution
The solution to this period's problem.
"""
self.def_utility_funcs()
self.DiscFacEff = self.DiscFac * self.LivPrb # Effective=pure x LivPrb
self.make_cFunc_PF()
self.def_value_funcs()
solution = ConsumerSolution(
cFunc=self.cFunc,
vFunc=self.vFunc,
vPfunc=self.vPfunc,
mNrmMin=self.mNrmMinNow,
hNrm=self.hNrmNow,
MPCmin=self.MPCmin,
MPCmax=self.MPCmax,
)
solution = self.add_stable_points(solution)
return solution
###############################################################################
###############################################################################
class ConsIndShockSetup(ConsPerfForesightSolver):
"""
A superclass for solvers of one period consumption-saving problems with
constant relative risk aversion utility and permanent and transitory shocks
to income. Has methods to set up but not solve the one period problem.
Parameters
----------
solution_next : ConsumerSolution
The solution to next period's one period problem.
IncShkDstn : distribution.Distribution
A discrete
approximation to the income process between the period being solved
and the one immediately following (in solution_next).
LivPrb : float
Survival probability; likelihood of being alive at the beginning of
the succeeding period.
DiscFac : float
Intertemporal discount factor for future utility.
CRRA : float
Coefficient of relative risk aversion.
Rfree : float
Risk free interest factor on end-of-period assets.
PermGroFac : float
Expected permanent income growth factor at the end of this period.
BoroCnstArt: float or None
Borrowing constraint for the minimum allowable assets to end the
period with. If it is less than the natural borrowing constraint,
then it is irrelevant; BoroCnstArt=None indicates no artificial bor-
rowing constraint.
aXtraGrid: np.array
Array of "extra" end-of-period asset values-- assets above the
absolute minimum acceptable level.
vFuncBool: boolean
An indicator for whether the value function should be computed and
included in the reported solution.
CubicBool: boolean
An indicator for whether the solver should use cubic or linear inter-
polation.
"""
def __init__(
self,
solution_next,
IncShkDstn,
LivPrb,
DiscFac,
CRRA,
Rfree,
PermGroFac,
BoroCnstArt,
aXtraGrid,
vFuncBool,
CubicBool,
):
"""
Constructor for a new solver-setup for problems with income subject to
permanent and transitory shocks.
"""
self.solution_next = solution_next
self.IncShkDstn = IncShkDstn
self.LivPrb = LivPrb
self.DiscFac = DiscFac
self.CRRA = CRRA
self.Rfree = Rfree
self.PermGroFac = PermGroFac
self.BoroCnstArt = BoroCnstArt
self.aXtraGrid = aXtraGrid
self.vFuncBool = vFuncBool
self.CubicBool = CubicBool
self.def_utility_funcs()
def def_utility_funcs(self):
"""
Defines CRRA utility function for this period (and its derivatives,
and their inverses), saving them as attributes of self for other methods
to use.
Parameters
----------
none
Returns
-------
none
"""
ConsPerfForesightSolver.def_utility_funcs(self)
self.uPinv = lambda u: utilityP_inv(u, gam=self.CRRA)
self.uPinvP = lambda u: utilityP_invP(u, gam=self.CRRA)
self.uinvP = lambda u: utility_invP(u, gam=self.CRRA)
if self.vFuncBool:
self.uinv = lambda u: utility_inv(u, gam=self.CRRA)
def set_and_update_values(self, solution_next, IncShkDstn, LivPrb, DiscFac):
"""
Unpacks some of the inputs (and calculates simple objects based on them),
storing the results in self for use by other methods. These include:
income shocks and probabilities, next period's marginal value function
(etc), the probability of getting the worst income shock next period,
the patience factor, human wealth, and the bounding MPCs.
Parameters
----------
solution_next : ConsumerSolution
The solution to next period's one period problem.
IncShkDstn : distribution.DiscreteDistribution
A DiscreteDistribution with a pmv
and two point value arrays in atoms, order:
permanent shocks, transitory shocks.
LivPrb : float
Survival probability; likelihood of being alive at the beginning of
the succeeding period.
DiscFac : float
Intertemporal discount factor for future utility.
Returns
-------
None
"""
self.DiscFacEff = DiscFac * LivPrb # "effective" discount factor
self.IncShkDstn = IncShkDstn
self.ShkPrbsNext = IncShkDstn.pmv
self.PermShkValsNext = IncShkDstn.atoms[0]
self.TranShkValsNext = IncShkDstn.atoms[1]
self.PermShkMinNext = np.min(self.PermShkValsNext)
self.TranShkMinNext = np.min(self.TranShkValsNext)
self.vPfuncNext = solution_next.vPfunc
self.WorstIncPrb = np.sum(
self.ShkPrbsNext[
(self.PermShkValsNext * self.TranShkValsNext)
== (self.PermShkMinNext * self.TranShkMinNext)
]
)
if self.CubicBool:
self.vPPfuncNext = solution_next.vPPfunc
if self.vFuncBool:
self.vFuncNext = solution_next.vFunc
# Update the bounding MPCs and PDV of human wealth:
self.PatFac = ((self.Rfree * self.DiscFacEff) ** (1.0 / self.CRRA)) / self.Rfree
self.MPCminNow = 1.0 / (1.0 + self.PatFac / solution_next.MPCmin)
self.Ex_IncNext = np.dot(
self.ShkPrbsNext, self.TranShkValsNext * self.PermShkValsNext
)
self.hNrmNow = (
self.PermGroFac / self.Rfree * (self.Ex_IncNext + solution_next.hNrm)
)
self.MPCmaxNow = 1.0 / (
1.0
+ (self.WorstIncPrb ** (1.0 / self.CRRA))
* self.PatFac
/ solution_next.MPCmax
)
self.cFuncLimitIntercept = self.MPCminNow * self.hNrmNow
self.cFuncLimitSlope = self.MPCminNow
def def_BoroCnst(self, BoroCnstArt):
"""
Defines the constrained portion of the consumption function as cFuncNowCnst,
an attribute of self. Uses the artificial and natural borrowing constraints.
Parameters
----------
BoroCnstArt : float or None
Borrowing constraint for the minimum allowable assets to end the
period with. If it is less than the natural borrowing constraint,
then it is irrelevant; BoroCnstArt=None indicates no artificial bor-
rowing constraint.
Returns
-------
none
"""
# Calculate the minimum allowable value of money resources in this period
self.BoroCnstNat = (
(self.solution_next.mNrmMin - self.TranShkMinNext)
* (self.PermGroFac * self.PermShkMinNext)
/ self.Rfree
)
# Note: need to be sure to handle BoroCnstArt==None appropriately.
# In Py2, this would evaluate to 5.0: np.max([None, 5.0]).
# However in Py3, this raises a TypeError. Thus here we need to directly
# address the situation in which BoroCnstArt == None:
if BoroCnstArt is None:
self.mNrmMinNow = self.BoroCnstNat
else:
self.mNrmMinNow = np.max([self.BoroCnstNat, BoroCnstArt])
if self.BoroCnstNat < self.mNrmMinNow:
self.MPCmaxEff = 1.0 # If actually constrained, MPC near limit is 1
else:
self.MPCmaxEff = self.MPCmaxNow
# Define the borrowing constraint (limiting consumption function)
self.cFuncNowCnst = LinearInterp(
np.array([self.mNrmMinNow, self.mNrmMinNow + 1]), np.array([0.0, 1.0])
)
def prepare_to_solve(self):
"""
Perform preparatory work before calculating the unconstrained consumption
function.
Parameters
----------
none
Returns
-------
none
"""
self.set_and_update_values(
self.solution_next, self.IncShkDstn, self.LivPrb, self.DiscFac
)
self.def_BoroCnst(self.BoroCnstArt)
####################################################################################################
####################################################################################################
class ConsIndShockSolverBasic(ConsIndShockSetup):
"""
This class solves a single period of a standard consumption-saving problem,
using linear interpolation and without the ability to calculate the value
function. ConsIndShockSolver inherits from this class and adds the ability
to perform cubic interpolation and to calculate the value function.
Note that this class does not have its own initializing method. It initial-
izes the same problem in the same way as ConsIndShockSetup, from which it
inherits.
"""
def prepare_to_calc_EndOfPrdvP(self):
"""
Prepare to calculate end-of-period marginal value by creating an array
of market resources that the agent could have next period, considering
the grid of end-of-period assets and the distribution of shocks he might
experience next period.
Parameters
----------
none
Returns
-------
aNrmNow : np.array
A 1D array of end-of-period assets; also stored as attribute of self.
"""
# We define aNrmNow all the way from BoroCnstNat up to max(self.aXtraGrid)
# even if BoroCnstNat < BoroCnstArt, so we can construct the consumption
# function as the lower envelope of the (by the artificial borrowing con-
# straint) uconstrained consumption function, and the artificially con-
# strained consumption function.
self.aNrmNow = np.asarray(self.aXtraGrid) + self.BoroCnstNat
return self.aNrmNow
def m_nrm_next(self, shocks, a_nrm, Rfree):
"""
Computes normalized market resources of the next period
from income shocks and current normalized market resources.
Parameters
----------
shocks: [float]
Permanent and transitory income shock levels.
a_nrm: float
Normalized market assets this period
Returns
-------
float
normalized market resources in the next period
"""
return Rfree / (self.PermGroFac * shocks[0]) * a_nrm + shocks[1]
def calc_EndOfPrdvP(self):
"""
Calculate end-of-period marginal value of assets at each point in aNrmNow.
Does so by taking a weighted sum of next period marginal values across
income shocks (in a preconstructed grid self.mNrmNext).
Parameters
----------
none
Returns
-------
EndOfPrdvP : np.array
A 1D array of end-of-period marginal value of assets
"""
def vp_next(shocks, a_nrm, Rfree):
return shocks[0] ** (-self.CRRA) * self.vPfuncNext(
self.m_nrm_next(shocks, a_nrm, Rfree)
)
EndOfPrdvP = (
self.DiscFacEff
* self.Rfree
* self.PermGroFac ** (-self.CRRA)
* expected(vp_next, self.IncShkDstn, args=(self.aNrmNow, self.Rfree))
)
return EndOfPrdvP
def get_points_for_interpolation(self, EndOfPrdvP, aNrmNow):
"""
Finds interpolation points (c,m) for the consumption function.
Parameters
----------
EndOfPrdvP : np.array
Array of end-of-period marginal values.
aNrmNow : np.array
Array of end-of-period asset values that yield the marginal values
in EndOfPrdvP.
Returns
-------
c_for_interpolation : np.array
Consumption points for interpolation.
m_for_interpolation : np.array
Corresponding market resource points for interpolation.
"""
cNrmNow = self.uPinv(EndOfPrdvP)
mNrmNow = cNrmNow + aNrmNow
# Limiting consumption is zero as m approaches mNrmMin
c_for_interpolation = np.insert(cNrmNow, 0, 0.0, axis=-1)
m_for_interpolation = np.insert(mNrmNow, 0, self.BoroCnstNat, axis=-1)
# Store these for calcvFunc
self.cNrmNow = cNrmNow
self.mNrmNow = mNrmNow
return c_for_interpolation, m_for_interpolation
def use_points_for_interpolation(self, cNrm, mNrm, interpolator):
"""
Constructs a basic solution for this period, including the consumption
function and marginal value function.
Parameters
----------
cNrm : np.array
(Normalized) consumption points for interpolation.
mNrm : np.array
(Normalized) corresponding market resource points for interpolation.
interpolator : function
A function that constructs and returns a consumption function.
Returns
-------
solution_now : ConsumerSolution
The solution to this period's consumption-saving problem, with a
consumption function, marginal value function, and minimum m.
"""
# Construct the unconstrained consumption function
cFuncNowUnc = interpolator(mNrm, cNrm)
# Combine the constrained and unconstrained functions into the true consumption function
# breakpoint() # LowerEnvelope should only be used when BoroCnstArt is true
cFuncNow = LowerEnvelope(cFuncNowUnc, self.cFuncNowCnst, nan_bool=False)
# Make the marginal value function and the marginal marginal value function
vPfuncNow = MargValueFuncCRRA(cFuncNow, self.CRRA)
# Pack up the solution and return it
solution_now = ConsumerSolution(
cFunc=cFuncNow, vPfunc=vPfuncNow, mNrmMin=self.mNrmMinNow
)
return solution_now
def make_basic_solution(self, EndOfPrdvP, aNrm, interpolator):
"""
Given end of period assets and end of period marginal value, construct
the basic solution for this period.
Parameters
----------
EndOfPrdvP : np.array
Array of end-of-period marginal values.
aNrm : np.array
Array of end-of-period asset values that yield the marginal values
in EndOfPrdvP.
interpolator : function
A function that constructs and returns a consumption function.
Returns
-------
solution_now : ConsumerSolution
The solution to this period's consumption-saving problem, with a
consumption function, marginal value function, and minimum m.
"""
cNrm, mNrm = self.get_points_for_interpolation(EndOfPrdvP, aNrm)
solution_now = self.use_points_for_interpolation(cNrm, mNrm, interpolator)
return solution_now
def add_MPC_and_human_wealth(self, solution):
"""
Take a solution and add human wealth and the bounding MPCs to it.