-
-
Notifications
You must be signed in to change notification settings - Fork 195
/
ConsIndShockModel.py
3584 lines (3076 loc) · 142 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://github.com/econ-ark/HARK/blob/master/Documentation/NARK/NARK.pdf 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 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,
DiscreteDistributionLabeled,
IndexDistribution,
Lognormal,
MeanOneLogNormal,
Uniform,
add_discrete_outcome_constant_mean,
combine_indep_dstns,
expected,
)
from HARK.interpolation import (
CubicInterp,
LinearInterp,
LowerEnvelope,
MargMargValueFuncCRRA,
MargValueFuncCRRA,
ValueFuncCRRA,
)
from HARK.metric import MetricObject
from HARK.rewards import (
CRRAutility,
CRRAutility_inv,
CRRAutility_invP,
CRRAutilityP,
CRRAutilityP_inv,
CRRAutilityP_invP,
CRRAutilityPP,
UtilityFuncCRRA,
)
from HARK.utilities import (
construct_assets_grid,
gen_tran_matrix_1D,
gen_tran_matrix_2D,
jump_to_grid_1D,
jump_to_grid_2D,
make_grid_exp_mult,
)
from scipy import sparse as sp
from scipy.optimize import newton
from HARK import (
AgentType,
NullFunc,
_log,
set_verbosity_level,
)
__all__ = [
"ConsumerSolution",
"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 ===
# =====================================================================
def solve_one_period_ConsPF(
solution_next, DiscFac, LivPrb, CRRA, Rfree, PermGroFac, BoroCnstArt, MaxKinks
):
"""
Solves one period of a basic perfect foresight consumption-saving model with
a single risk free asset and permanent income growth.
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.
Returns
-------
solution_now : ConsumerSolution
Solution to the current period of a perfect foresight consumption-saving
problem.
"""
# Define the utility function and effective discount factor
uFunc = UtilityFuncCRRA(CRRA)
DiscFacEff = DiscFac * LivPrb # Effective = pure x LivPrb
# Prevent comparing None and float if there is no borrowing constraint
if BoroCnstArt is None:
BoroCnstArt = -np.inf # Can borrow as much as we want
# Calculate human wealth this period
hNrmNow = (PermGroFac / Rfree) * (solution_next.hNrm + 1.0)
# Calculate the lower bound of the marginal propensity to consume
PatFac = ((Rfree * DiscFacEff) ** (1.0 / CRRA)) / Rfree
MPCmin = 1.0 / (1.0 + PatFac / 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 = solution_next.cFunc.x_list[:-1]
cNrmNext = solution_next.cFunc.y_list[:-1]
vNext = PermGroFac ** (1.0 - CRRA) * uFunc(
solution_next.vFunc.vFuncNvrs.y_list[:-1]
)
EndOfPrdv = DiscFacEff * vNext
# 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 = (PermGroFac / Rfree) * (mNrmNext - 1.0)
cNrmNow = (DiscFacEff * Rfree) ** (-1.0 / CRRA) * (PermGroFac * cNrmNext)
mNrmNow = aNrmNow + cNrmNow
# Calculate (pseudo-inverse) value at each consumption kink point
vNow = uFunc(cNrmNow) + EndOfPrdv
vNvrsNow = uFunc.inverse(vNow)
vNvrsSlopeMin = MPCmin ** (-CRRA / (1.0 - CRRA))
# 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] + MPCmin)
vNvrsNow = np.append(vNvrsNow, vNvrsNow[-1] + vNvrsSlopeMin)
# 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) :]))
# Adjust the vNvrs grid to account for the borrowing constraint
v0 = vNvrsNow[idx]
v1 = vNvrsNow[idx + 1]
vNvrsCrit = v0 + alpha * (v1 - v0)
vNvrsNow = np.concatenate(([0.0, vNvrsCrit], vNvrsNow[(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 - MPCmin)
mCrit = mNrmNow[-1] + mXtra
cCrit = mCrit - BoroCnstArt
mNrmNow = np.array([BoroCnstArt, mCrit, mCrit + 1.0])
cNrmNow = np.array([0.0, cCrit, cCrit + MPCmin])
# Adjust vNvrs grid for this three node structure
mNextCrit = BoroCnstArt * Rfree + 1.0
vNextCrit = PermGroFac ** (1.0 - CRRA) * solution_next.vFunc(mNextCrit)
vCrit = uFunc(cCrit) + DiscFacEff * vNextCrit
vNvrsCrit = uFunc.inverse(vCrit)
vNvrsNow = np.array([0.0, vNvrsCrit, vNvrsCrit + vNvrsSlopeMin])
# 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 > MaxKinks:
mNrmNow = np.concatenate((mNrmNow[:-2], [mNrmNow[-3] + 1.0]))
cNrmNow = np.concatenate((cNrmNow[:-2], [cNrmNow[-3] + MPCmin]))
vNvrsNow = np.concatenate((vNvrsNow[:-2], [vNvrsNow[-3] + vNvrsSlopeMin]))
# Construct the consumption function as a linear interpolation.
cFunc = LinearInterp(mNrmNow, cNrmNow)
# Calculate the upper bound of the MPC as the slope of the bottom segment.
MPCmax = (cNrmNow[1] - cNrmNow[0]) / (mNrmNow[1] - mNrmNow[0])
mNrmMinNow = mNrmNow[0]
# Construct the (marginal) value function for this period
# See the PerfForesightConsumerType.ipynb documentation notebook for the derivations
vFuncNvrs = LinearInterp(mNrmNow, vNvrsNow)
vFunc = ValueFuncCRRA(vFuncNvrs, CRRA)
vPfunc = MargValueFuncCRRA(cFunc, CRRA)
# Construct and return the solution
solution_now = ConsumerSolution(
cFunc=cFunc,
vFunc=vFunc,
vPfunc=vPfunc,
mNrmMin=mNrmMinNow,
hNrm=hNrmNow,
MPCmin=MPCmin,
MPCmax=MPCmax,
)
return solution_now
def solve_one_period_ConsIndShock(
solution_next,
IncShkDstn,
LivPrb,
DiscFac,
CRRA,
Rfree,
PermGroFac,
BoroCnstArt,
aXtraGrid,
vFuncBool,
CubicBool,
):
"""
Solves one period of a consumption-saving model with idiosyncratic shocks to
permanent and transitory income, with one risk free asset and CRRA utility.
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 interpolation.
Returns
-------
solution_now : ConsumerSolution
Solution to this period's consumption-saving problem with income risk.
"""
# Define the current period utility function and effective discount factor
uFunc = UtilityFuncCRRA(CRRA)
DiscFacEff = DiscFac * LivPrb # "effective" discount factor
# Unpack next period's income shock distribution
ShkPrbsNext = IncShkDstn.pmv
PermShkValsNext = IncShkDstn.atoms[0]
TranShkValsNext = IncShkDstn.atoms[1]
PermShkMinNext = np.min(PermShkValsNext)
TranShkMinNext = np.min(TranShkValsNext)
# Calculate the probability that we get the worst possible income draw
IncNext = PermShkValsNext * TranShkValsNext
WorstIncNext = PermShkMinNext * TranShkMinNext
WorstIncPrb = np.sum(ShkPrbsNext[IncNext == WorstIncNext])
# WorstIncPrb is the "Weierstrass p" concept: the odds we get the WORST thing
# Unpack next period's (marginal) value function
vFuncNext = solution_next.vFunc # This is None when vFuncBool is False
vPfuncNext = solution_next.vPfunc
vPPfuncNext = solution_next.vPPfunc # This is None when CubicBool is False
# Update the bounding MPCs and PDV of human wealth:
PatFac = ((Rfree * DiscFacEff) ** (1.0 / CRRA)) / Rfree
try:
MPCminNow = 1.0 / (1.0 + PatFac / solution_next.MPCmin)
except:
MPCminNow = 0.0
Ex_IncNext = np.dot(ShkPrbsNext, TranShkValsNext * PermShkValsNext)
hNrmNow = PermGroFac / Rfree * (Ex_IncNext + solution_next.hNrm)
temp_fac = (WorstIncPrb ** (1.0 / CRRA)) * PatFac
MPCmaxNow = 1.0 / (1.0 + temp_fac / solution_next.MPCmax)
cFuncLimitIntercept = MPCminNow * hNrmNow
cFuncLimitSlope = MPCminNow
# Calculate the minimum allowable value of money resources in this period
PermGroFacEffMin = (PermGroFac * PermShkMinNext) / Rfree
BoroCnstNat = (solution_next.mNrmMin - TranShkMinNext) * PermGroFacEffMin
# Set the minimum allowable (normalized) market resources based on the natural
# and artificial borrowing constraints
if BoroCnstArt is None:
mNrmMinNow = BoroCnstNat
else:
mNrmMinNow = np.max([BoroCnstNat, BoroCnstArt])
# Set the upper limit of the MPC (at mNrmMinNow) based on whether the natural
# or artificial borrowing constraint actually binds
if BoroCnstNat < mNrmMinNow:
MPCmaxEff = 1.0 # If actually constrained, MPC near limit is 1
else:
MPCmaxEff = MPCmaxNow # Otherwise, it's the MPC calculated above
# Define the borrowing-constrained consumption function
cFuncNowCnst = LinearInterp(
np.array([mNrmMinNow, mNrmMinNow + 1.0]), np.array([0.0, 1.0])
)
# Construct the assets grid by adjusting aXtra by the natural borrowing constraint
aNrmNow = np.asarray(aXtraGrid) + BoroCnstNat
# Define local functions for taking future expectations
def calc_mNrmNext(S, a, R):
return R / (PermGroFac * S["PermShk"]) * a + S["TranShk"]
def calc_vNext(S, a, R):
return (S["PermShk"] ** (1.0 - CRRA) * PermGroFac ** (1.0 - CRRA)) * vFuncNext(
calc_mNrmNext(S, a, R)
)
def calc_vPnext(S, a, R):
return S["PermShk"] ** (-CRRA) * vPfuncNext(calc_mNrmNext(S, a, R))
def calc_vPPnext(S, a, R):
return S["PermShk"] ** (-CRRA - 1.0) * vPPfuncNext(calc_mNrmNext(S, a, R))
# Calculate end-of-period marginal value of assets at each gridpoint
vPfacEff = DiscFacEff * Rfree * PermGroFac ** (-CRRA)
EndOfPrdvP = vPfacEff * expected(calc_vPnext, IncShkDstn, args=(aNrmNow, Rfree))
# Invert the first order condition to find optimal cNrm from each aNrm gridpoint
cNrmNow = uFunc.derinv(EndOfPrdvP, order=(1, 0))
mNrmNow = cNrmNow + aNrmNow # Endogenous mNrm gridpoints
# Limiting consumption is zero as m approaches mNrmMin
c_for_interpolation = np.insert(cNrmNow, 0, 0.0)
m_for_interpolation = np.insert(mNrmNow, 0, BoroCnstNat)
# Construct the consumption function as a cubic or linear spline interpolation
if CubicBool:
# Calculate end-of-period marginal marginal value of assets at each gridpoint
vPPfacEff = DiscFacEff * Rfree * Rfree * PermGroFac ** (-CRRA - 1.0)
EndOfPrdvPP = vPPfacEff * expected(
calc_vPPnext, IncShkDstn, args=(aNrmNow, Rfree)
)
dcda = EndOfPrdvPP / uFunc.der(np.array(cNrmNow), order=2)
MPC = dcda / (dcda + 1.0)
MPC_for_interpolation = np.insert(MPC, 0, MPCmaxNow)
# Construct the unconstrained consumption function as a cubic interpolation
cFuncNowUnc = CubicInterp(
m_for_interpolation,
c_for_interpolation,
MPC_for_interpolation,
cFuncLimitIntercept,
cFuncLimitSlope,
)
else:
# Construct the unconstrained consumption function as a linear interpolation
cFuncNowUnc = LinearInterp(
m_for_interpolation,
c_for_interpolation,
cFuncLimitIntercept,
cFuncLimitSlope,
)
# Combine the constrained and unconstrained functions into the true consumption function.
# LowerEnvelope should only be used when BoroCnstArt is True
cFuncNow = LowerEnvelope(cFuncNowUnc, cFuncNowCnst, nan_bool=False)
# Make the marginal value function and the marginal marginal value function
vPfuncNow = MargValueFuncCRRA(cFuncNow, CRRA)
# Define this period's marginal marginal value function
if CubicBool:
vPPfuncNow = MargMargValueFuncCRRA(cFuncNow, CRRA)
else:
vPPfuncNow = NullFunc() # Dummy object
# Construct this period's value function if requested
if vFuncBool:
# Calculate end-of-period value, its derivative, and their pseudo-inverse
EndOfPrdv = DiscFacEff * expected(calc_vNext, IncShkDstn, args=(aNrmNow, Rfree))
EndOfPrdvNvrs = uFunc.inv(
EndOfPrdv
) # value transformed through inverse utility
EndOfPrdvNvrsP = EndOfPrdvP * uFunc.derinv(EndOfPrdv, order=(0, 1))
EndOfPrdvNvrs = np.insert(EndOfPrdvNvrs, 0, 0.0)
EndOfPrdvNvrsP = np.insert(EndOfPrdvNvrsP, 0, EndOfPrdvNvrsP[0])
# This is a very good approximation, vNvrsPP = 0 at the asset minimum
# Construct the end-of-period value function
aNrm_temp = np.insert(aNrmNow, 0, BoroCnstNat)
EndOfPrd_vNvrsFunc = CubicInterp(aNrm_temp, EndOfPrdvNvrs, EndOfPrdvNvrsP)
EndOfPrd_vFunc = ValueFuncCRRA(EndOfPrd_vNvrsFunc, CRRA)
# Compute expected value and marginal value on a grid of market resources
mNrm_temp = mNrmMinNow + aXtraGrid
cNrm_temp = cFuncNow(mNrm_temp)
aNrm_temp = mNrm_temp - cNrm_temp
v_temp = uFunc(cNrm_temp) + EndOfPrd_vFunc(aNrm_temp)
vP_temp = uFunc.der(cNrm_temp)
# Construct the beginning-of-period value function
vNvrs_temp = uFunc.inv(v_temp) # value transformed through inv utility
vNvrsP_temp = vP_temp * uFunc.derinv(v_temp, order=(0, 1))
mNrm_temp = np.insert(mNrm_temp, 0, mNrmMinNow)
vNvrs_temp = np.insert(vNvrs_temp, 0, 0.0)
vNvrsP_temp = np.insert(vNvrsP_temp, 0, MPCmaxEff ** (-CRRA / (1.0 - CRRA)))
MPCminNvrs = MPCminNow ** (-CRRA / (1.0 - CRRA))
vNvrsFuncNow = CubicInterp(
mNrm_temp, vNvrs_temp, vNvrsP_temp, MPCminNvrs * hNrmNow, MPCminNvrs
)
vFuncNow = ValueFuncCRRA(vNvrsFuncNow, CRRA)
else:
vFuncNow = NullFunc() # Dummy object
# Create and return this period's solution
solution_now = ConsumerSolution(
cFunc=cFuncNow,
vFunc=vFuncNow,
vPfunc=vPfuncNow,
vPPfunc=vPPfuncNow,
mNrmMin=mNrmMinNow,
hNrm=hNrmNow,
MPCmin=MPCminNow,
MPCmax=MPCmaxEff,
)
return solution_now
def solve_one_period_ConsKinkedR(
solution_next,
IncShkDstn,
LivPrb,
DiscFac,
CRRA,
Rboro,
Rsave,
PermGroFac,
BoroCnstArt,
aXtraGrid,
vFuncBool,
CubicBool,
):
"""
Solves one period of a consumption-saving model with idiosyncratic shocks to
permanent and transitory income, with a risk free asset and CRRA utility.
In this variation, the interest rate on borrowing Rboro exceeds the interest
rate on saving Rsave.
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.
Rboro: float
Interest factor on assets between this period and the succeeding
period when assets are negative.
Rsave: float
Interest factor on assets between this period and the succeeding
period when assets are positive.
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.
Returns
-------
solution_now : ConsumerSolution
Solution to this period's consumption-saving problem with income risk.
"""
# Verifiy that there is actually a kink in the interest factor
assert (
Rboro >= Rsave
), "Interest factor on debt less than interest factor on savings!"
# If the kink is in the wrong direction, code should break here. If there's
# no kink at all, then just use the ConsIndShockModel solver.
if Rboro == Rsave:
solution_now = solve_one_period_ConsIndShock(
solution_next,
IncShkDstn,
LivPrb,
DiscFac,
CRRA,
Rboro,
PermGroFac,
BoroCnstArt,
aXtraGrid,
vFuncBool,
CubicBool,
)
return solution_now
# Define the current period utility function and effective discount factor
uFunc = UtilityFuncCRRA(CRRA)
DiscFacEff = DiscFac * LivPrb # "effective" discount factor
# Unpack next period's income shock distribution
ShkPrbsNext = IncShkDstn.pmv
PermShkValsNext = IncShkDstn.atoms[0]
TranShkValsNext = IncShkDstn.atoms[1]
PermShkMinNext = np.min(PermShkValsNext)
TranShkMinNext = np.min(TranShkValsNext)
# Calculate the probability that we get the worst possible income draw
IncNext = PermShkValsNext * TranShkValsNext
WorstIncNext = PermShkMinNext * TranShkMinNext
WorstIncPrb = np.sum(ShkPrbsNext[IncNext == WorstIncNext])
# WorstIncPrb is the "Weierstrass p" concept: the odds we get the WORST thing
# Unpack next period's (marginal) value function
vFuncNext = solution_next.vFunc # This is None when vFuncBool is False
vPfuncNext = solution_next.vPfunc
vPPfuncNext = solution_next.vPPfunc # This is None when CubicBool is False
# Update the bounding MPCs and PDV of human wealth:
PatFac = ((Rsave * DiscFacEff) ** (1.0 / CRRA)) / Rsave
PatFacAlt = ((Rboro * DiscFacEff) ** (1.0 / CRRA)) / Rboro
try:
MPCminNow = 1.0 / (1.0 + PatFac / solution_next.MPCmin)
except:
MPCminNow = 0.0
Ex_IncNext = np.dot(ShkPrbsNext, TranShkValsNext * PermShkValsNext)
hNrmNow = (PermGroFac / Rsave) * (Ex_IncNext + solution_next.hNrm)
temp_fac = (WorstIncPrb ** (1.0 / CRRA)) * PatFacAlt
MPCmaxNow = 1.0 / (1.0 + temp_fac / solution_next.MPCmax)
cFuncLimitIntercept = MPCminNow * hNrmNow
cFuncLimitSlope = MPCminNow
# Calculate the minimum allowable value of money resources in this period
PermGroFacEffMin = (PermGroFac * PermShkMinNext) / Rboro
BoroCnstNat = (solution_next.mNrmMin - TranShkMinNext) * PermGroFacEffMin
# Set the minimum allowable (normalized) market resources based on the natural
# and artificial borrowing constraints
if BoroCnstArt is None:
mNrmMinNow = BoroCnstNat
else:
mNrmMinNow = np.max([BoroCnstNat, BoroCnstArt])
# Set the upper limit of the MPC (at mNrmMinNow) based on whether the natural
# or artificial borrowing constraint actually binds
if BoroCnstNat < mNrmMinNow:
MPCmaxEff = 1.0 # If actually constrained, MPC near limit is 1
else:
MPCmaxEff = MPCmaxNow # Otherwise, it's the MPC calculated above
# Define the borrowing-constrained consumption function
cFuncNowCnst = LinearInterp(
np.array([mNrmMinNow, mNrmMinNow + 1.0]), np.array([0.0, 1.0])
)
# Construct the assets grid by adjusting aXtra by the natural borrowing constraint
aNrmNow = np.sort(
np.hstack((np.asarray(aXtraGrid) + mNrmMinNow, np.array([0.0, 0.0])))
)
# Make a 1D array of the interest factor at each asset gridpoint
Rfree = Rsave * np.ones_like(aNrmNow)
Rfree[aNrmNow < 0] = Rboro
i_kink = np.argwhere(aNrmNow == 0.0)[0][0]
Rfree[i_kink] = Rboro
# Define local functions for taking future expectations
def calc_mNrmNext(S, a, R):
return R / (PermGroFac * S["PermShk"]) * a + S["TranShk"]
def calc_vNext(S, a, R):
return (S["PermShk"] ** (1.0 - CRRA) * PermGroFac ** (1.0 - CRRA)) * vFuncNext(
calc_mNrmNext(S, a, R)
)
def calc_vPnext(S, a, R):
return S["PermShk"] ** (-CRRA) * vPfuncNext(calc_mNrmNext(S, a, R))
def calc_vPPnext(S, a, R):
return S["PermShk"] ** (-CRRA - 1.0) * vPPfuncNext(calc_mNrmNext(S, a, R))
# Calculate end-of-period marginal value of assets at each gridpoint
vPfacEff = DiscFacEff * Rfree * PermGroFac ** (-CRRA)
EndOfPrdvP = vPfacEff * expected(calc_vPnext, IncShkDstn, args=(aNrmNow, Rfree))
# Invert the first order condition to find optimal cNrm from each aNrm gridpoint
cNrmNow = uFunc.derinv(EndOfPrdvP, order=(1, 0))
mNrmNow = cNrmNow + aNrmNow # Endogenous mNrm gridpoints
# Limiting consumption is zero as m approaches mNrmMin
c_for_interpolation = np.insert(cNrmNow, 0, 0.0)
m_for_interpolation = np.insert(mNrmNow, 0, BoroCnstNat)
# Construct the consumption function as a cubic or linear spline interpolation
if CubicBool:
# Calculate end-of-period marginal marginal value of assets at each gridpoint
vPPfacEff = DiscFacEff * Rfree * Rfree * PermGroFac ** (-CRRA - 1.0)
EndOfPrdvPP = vPPfacEff * expected(
calc_vPPnext, IncShkDstn, args=(aNrmNow, Rfree)
)
dcda = EndOfPrdvPP / uFunc.der(np.array(cNrmNow), order=2)
MPC = dcda / (dcda + 1.0)
MPC_for_interpolation = np.insert(MPC, 0, MPCmaxNow)
# Construct the unconstrained consumption function as a cubic interpolation
cFuncNowUnc = CubicInterp(
m_for_interpolation,
c_for_interpolation,
MPC_for_interpolation,
cFuncLimitIntercept,
cFuncLimitSlope,
)
# Adjust the coefficients on the kinked portion of the cFunc
cFuncNowUnc.coeffs[i_kink + 2] = [
c_for_interpolation[i_kink + 1],
m_for_interpolation[i_kink + 2] - m_for_interpolation[i_kink + 1],
0.0,
0.0,
]
else:
# Construct the unconstrained consumption function as a linear interpolation
cFuncNowUnc = LinearInterp(
m_for_interpolation,
c_for_interpolation,
cFuncLimitIntercept,
cFuncLimitSlope,
)
# Combine the constrained and unconstrained functions into the true consumption function.
# LowerEnvelope should only be used when BoroCnstArt is True
cFuncNow = LowerEnvelope(cFuncNowUnc, cFuncNowCnst, nan_bool=False)
# Make the marginal value function and the marginal marginal value function
vPfuncNow = MargValueFuncCRRA(cFuncNow, CRRA)
# Define this period's marginal marginal value function
if CubicBool:
vPPfuncNow = MargMargValueFuncCRRA(cFuncNow, CRRA)
else:
vPPfuncNow = NullFunc() # Dummy object
# Construct this period's value function if requested
if vFuncBool:
# Calculate end-of-period value, its derivative, and their pseudo-inverse
EndOfPrdv = DiscFacEff * expected(calc_vNext, IncShkDstn, args=(aNrmNow, Rfree))
EndOfPrdvNvrs = uFunc.inv(
EndOfPrdv
) # value transformed through inverse utility
EndOfPrdvNvrsP = EndOfPrdvP * uFunc.derinv(EndOfPrdv, order=(0, 1))
EndOfPrdvNvrs = np.insert(EndOfPrdvNvrs, 0, 0.0)
EndOfPrdvNvrsP = np.insert(EndOfPrdvNvrsP, 0, EndOfPrdvNvrsP[0])
# This is a very good approximation, vNvrsPP = 0 at the asset minimum
# Construct the end-of-period value function
aNrm_temp = np.insert(aNrmNow, 0, BoroCnstNat)
EndOfPrdvNvrsFunc = CubicInterp(aNrm_temp, EndOfPrdvNvrs, EndOfPrdvNvrsP)
EndOfPrdvFunc = ValueFuncCRRA(EndOfPrdvNvrsFunc, CRRA)
# Compute expected value and marginal value on a grid of market resources
mNrm_temp = mNrmMinNow + aXtraGrid
cNrm_temp = cFuncNow(mNrm_temp)
aNrm_temp = mNrm_temp - cNrm_temp
v_temp = uFunc(cNrm_temp) + EndOfPrdvFunc(aNrm_temp)
vP_temp = uFunc.der(cNrm_temp)
# Construct the beginning-of-period value function
vNvrs_temp = uFunc.inv(v_temp) # value transformed through inv utility
vNvrsP_temp = vP_temp * uFunc.derinv(v_temp, order=(0, 1))
mNrm_temp = np.insert(mNrm_temp, 0, mNrmMinNow)
vNvrs_temp = np.insert(vNvrs_temp, 0, 0.0)
vNvrsP_temp = np.insert(vNvrsP_temp, 0, MPCmaxEff ** (-CRRA / (1.0 - CRRA)))
MPCminNvrs = MPCminNow ** (-CRRA / (1.0 - CRRA))
vNvrsFuncNow = CubicInterp(
mNrm_temp, vNvrs_temp, vNvrsP_temp, MPCminNvrs * hNrmNow, MPCminNvrs
)
vFuncNow = ValueFuncCRRA(vNvrsFuncNow, CRRA)
else:
vFuncNow = NullFunc() # Dummy object
# Create and return this period's solution
solution_now = ConsumerSolution(
cFunc=cFuncNow,
vFunc=vFuncNow,
vPfunc=vPfuncNow,
vPPfunc=vPPfuncNow,
mNrmMin=mNrmMinNow,
hNrm=hNrmNow,
MPCmin=MPCminNow,
MPCmax=MPCmaxEff,
)
return solution_now
# ============================================================================
# == Classes for representing types of consumer agents (and things they do) ==
# ============================================================================
# Make a dictionary to specify a perfect foresight consumer type
init_perfect_foresight = {
"cycles": 1, # Finite, non-cyclic model
"CRRA": 2.0, # Coefficient of relative risk aversion,
"Rfree": 1.03, # Interest factor on assets
"DiscFac": 0.96, # Intertemporal discount factor
"LivPrb": [0.98], # Survival probability
"PermGroFac": [1.01], # Permanent income growth factor
"BoroCnstArt": None, # Artificial borrowing constraint
# Maximum number of grid points to allow in cFunc (should be large)
"MaxKinks": 400,
# Number of agents of this type (only matters for simulation)
"AgentCount": 10000,
# Mean of log initial assets (only matters for simulation)
"aNrmInitMean": 0.0,
# Standard deviation of log initial assets (only for simulation)
"aNrmInitStd": 1.0,
# Mean of log initial permanent income (only matters for simulation)
"pLvlInitMean": 0.0,
# Standard deviation of log initial permanent income (only matters for simulation)
"pLvlInitStd": 0.0,
# Aggregate permanent income growth factor: portion of PermGroFac attributable to aggregate productivity growth (only matters for simulation)
"PermGroFacAgg": 1.0,
"T_age": None, # Age after which simulated agents are automatically killed
"T_cycle": 1, # Number of periods in the cycle for this agent type
"PerfMITShk": False,
# Do Perfect Foresight MIT Shock: Forces Newborns to follow solution path of the agent he/she replaced when True
}
class PerfForesightConsumerType(AgentType):
"""
A perfect foresight consumer type who has no uncertainty other than mortality.
His problem is defined by a coefficient of relative risk aversion, intertemporal
discount factor, interest factor, an artificial borrowing constraint (maybe)
and time sequences of the permanent income growth rate and survival probability.
Parameters
----------
"""
# Define some universal values for all consumer types
cFunc_terminal_ = LinearInterp([0.0, 1.0], [0.0, 1.0]) # c=m in terminal period
vFunc_terminal_ = LinearInterp([0.0, 1.0], [0.0, 0.0]) # This is overwritten
solution_terminal_ = ConsumerSolution(
cFunc=cFunc_terminal_,
vFunc=vFunc_terminal_,
mNrmMin=0.0,
hNrm=0.0,
MPCmin=1.0,
MPCmax=1.0,
)
time_vary_ = ["LivPrb", "PermGroFac"]
time_inv_ = ["CRRA", "DiscFac", "MaxKinks", "BoroCnstArt"]
state_vars = ["pLvl", "PlvlAgg", "bNrm", "mNrm", "aNrm", "aLvl"]
shock_vars_ = []
def __init__(self, verbose=1, quiet=False, **kwds):
params = init_perfect_foresight.copy()
params.update(kwds)
kwds = params
# Initialize a basic AgentType
AgentType.__init__(
self,
solution_terminal=deepcopy(self.solution_terminal_),
pseudo_terminal=False,
**kwds,
)
# Add consumer-type specific objects, copying to create independent versions
self.time_vary = deepcopy(self.time_vary_)
self.time_inv = deepcopy(self.time_inv_)
self.shock_vars = deepcopy(self.shock_vars_)
self.verbose = verbose
self.quiet = quiet
self.solve_one_period = solve_one_period_ConsPF
set_verbosity_level((4 - verbose) * 10)
self.bilt = {}
self.update_Rfree() # update interest rate if time varying
def pre_solve(self):
"""
Method that is run automatically just before solution by backward iteration.
Solves the (trivial) terminal period and does a quick check on the borrowing
constraint and MaxKinks attribute (only relevant in constrained, infinite
horizon problems).
"""
self.update_solution_terminal() # Solve the terminal period problem
if not self.quiet:
self.check_conditions(verbose=self.verbose)
# Fill in BoroCnstArt and MaxKinks if they're not specified or are irrelevant.
# If no borrowing constraint specified...
if not hasattr(self, "BoroCnstArt"):
self.BoroCnstArt = None # ...assume the user wanted none
if not hasattr(self, "MaxKinks"):
if self.cycles > 0: # If it's not an infinite horizon model...
self.MaxKinks = np.inf # ...there's no need to set MaxKinks
elif self.BoroCnstArt is None: # If there's no borrowing constraint...
self.MaxKinks = np.inf # ...there's no need to set MaxKinks
else:
raise (
AttributeError(
"PerfForesightConsumerType requires the attribute MaxKinks to be specified when BoroCnstArt is not None and cycles == 0."
)
)
def post_solve(self):
"""
Method that is run automatically at the end of a call to solve. Here, it
simply calls calc_stable_points() if appropriate: an infinite horizon
problem with a single repeated period in its cycle.
Parameters
----------