-
Notifications
You must be signed in to change notification settings - Fork 3
/
PublicationPlots.jl
2497 lines (1928 loc) · 91.7 KB
/
PublicationPlots.jl
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
using LaTeXStrings
using Plots
using StatsPlots
using StatsBase
using OrderedCollections
using Formatting
using Random
using LinearAlgebra
default(legend_font_halign=:left) # Align legend font left
pgfplotsx()
function generatePublicationPlots()
# Set plotting backend
pgfplotsx()
# Settings
inputFolder = "Results/HANKWageRigidities/Results"
outputFolder = "Figures/HANKWageRigidities/PublicationPlotsInequalityAndZLB"
# Inflation targets (in ascending order)
πTargets = [1.7:0.1:1.8; collect(2.0:0.5:4.0)] / 100
# Idiosyncratic volatility
σLevels = [0.075, 0.0, 0.095]
σLabels = ["ZLB-HANK" "ZLB-RANK" "ZLB-HANK with High Idiosyncratic Risk"]
# Initalize filename and model lists
filenames = []
modelsCompStat = Array{String,2}(undef, length(πTargets), length(σLevels)) # Contains model definitions for comparative statics
for (ii, σ) in enumerate(σLevels)
for (jj, π) in enumerate(πTargets)
# Generate filename
πStr = replace(string(round(π, digits = 4)), "." => "_")
τStr = "0_0"
ELBStr = "1_0"
σStr = replace(string(round(σ, digits = 4)), "." => "_")
ZLBStr = "ZLB"
if σ > 0.0
filenameExt = "BaselineConfig_$(ZLBStr)_pitilde_$(πStr)_sig_$(σStr)"
filename = "Results/HANKWageRigidities/HANKWageRigidities_$(filenameExt).bson"
elseif σ == 0.0
filenameExt = "RANKWageRigidities_BaselineConfig_$(ZLBStr)_pitilde_$(πStr)"
filename = "Results/RANKWageRigidities/$(filenameExt).bson"
elseif σ == -1.0
filenameExt = "RANKWageRigidities_BaselineConfig_$(ZLBStr)_pitilde_$(πStr)_Recalibrated"
filename = "Results/RANKWageRigidities/$(filenameExt).bson"
end
# Add file to be loaded
push!(filenames, filename)
modelsCompStat[jj, ii] = filenameExt
end
end
# Add RANK without ZLB
modelsCompStatPlus = Array{String,2}(undef, length(πTargets), 1)
for (jj, π) in enumerate(πTargets)
# Generate filename
πStr = replace(string(round(π, digits = 4)), "." => "_")
ZLBStr = "NoZLB"
filenameExt = "RANKWageRigidities_BaselineConfig_$(ZLBStr)_pitilde_$(πStr)"
filename = "Results/RANKWageRigidities/$(filenameExt).bson"
# Add file to be loaded
push!(filenames, filename)
modelsCompStatPlus[jj, 1] = filenameExt
end
# Additional required files
push!(filenames,
"Results/HANKWageRigidities/HANKWageRigidities_BaselineConfig_NoZLB_pitilde_0_02_sig_0_075.bson",
"Results/HANKWageRigidities/HANKWageRigidities_BaselineConfig_ZLB_pitilde_0_02_sig_0_075_LinearRegression.bson",
"Results/HANKWageRigidities/HANKWageRigidities_BaselineConfig_ZLB_pitilde_0_02_sig_0_075_DualRegression.bson",
"Results/HANKWageRigidities/HANKWageRigidities_BaselineConfig_ZLB_pitilde_0_02_sig_0_075_QuadRegression.bson",
"Results/HANKWageRigidities/HANKWageRigidities_BaselineConfig_ZLB_pitilde_0_02_sig_0_075_HigherAccuracy.bson",
"Results/HANKWageRigidities/HANKWageRigidities_BaselineConfig_ZLB_pitilde_0_02_sig_0_075_HigherAccuracy_HighRotembergCost.bson",
"Results/RANKWageRigidities/RANKWageRigidities_BaselineConfig_ZLB_pitilde_0_02_HighRotembergCost.bson",
"Results/RANKWageRigidities/RANKWageRigidities_BaselineConfig_NoZLB_pitilde_0_02.bson",
)
# Main model definitions
modelZLB = "BaselineConfig_ZLB_pitilde_0_02_sig_0_075_HigherAccuracy"
modelZLBLinear = "BaselineConfig_ZLB_pitilde_0_02_sig_0_075_LinearRegression"
modelZLBDualLinear = "BaselineConfig_ZLB_pitilde_0_02_sig_0_075_DualRegression"
modelZLBQuadLinear = "BaselineConfig_ZLB_pitilde_0_02_sig_0_075_QuadRegression"
modelNoZLB = "BaselineConfig_NoZLB_pitilde_0_02_sig_0_075"
modelZLBRANK = "RANKWageRigidities_BaselineConfig_ZLB_pitilde_0_02"
modelNoZLBRANK = "RANKWageRigidities_BaselineConfig_NoZLB_pitilde_0_02"
# Additional model definitions
modelZLBHighRotembergCost = "BaselineConfig_ZLB_pitilde_0_02_sig_0_075_HigherAccuracy_HighRotembergCost"
modelZLBRANKHighRotembergCost = "RANKWageRigidities_BaselineConfig_ZLB_pitilde_0_02_HighRotembergCost"
# Create the output folder
if !isdir(outputFolder)
mkpath(outputFolder)
end
# Create the output folder for additional figures
outputFolderAdditional = outputFolder * "/Additional"
if !isdir(outputFolderAdditional)
mkpath(outputFolderAdditional)
end
# Load the results
res = HANKWageRigidities.loadAllResults(filenames, inputFolder, loadSimulationResults = true, loadSimulationPlusResults = true)
# PLM Inflation (Figure 1)
plotPLMInflation(res, modelZLB, outputFolder)
# Forecast errors inflation (Figure 2)
plotForecastErrorsInflation(res, modelZLB, modelZLBLinear, outputFolder)
# Ergodic distribution (Figure 3)
plotErgodicDistribution(res, modelZLB, modelNoZLB, outputFolder)
# Impulse responses (Figure 4)
plotImpulseResponseFunctions(res, modelZLB, modelNoZLB, outputFolder)
# Impact response decomposition (Figures 5-6)
plotResponseDecomposition(res, modelZLB, modelNoZLB, outputFolder; prodTypes = [:all], skipAdditionalFigure = false, outputFolderAdditional)
# Comparative statics (includes Figure 7-8)
plotComparativeStatics(res, modelsCompStat, σLabels, outputFolder)
# DSS and SSS comparison table (Table 2)
generateDSSSSSErgodicMeanTable(res, modelZLB, modelNoZLB, modelZLBRANK, modelNoZLBRANK, outputFolder)
# Rate decomposition table (Table 3)
generateSmallRateDecompositionTable(res, modelZLB, modelZLBRANK, outputFolder)
# Additional figures
plotForecastErrorsInflationExpectations(res, modelZLB, modelZLBLinear, outputFolderAdditional)
plotForecastErrorsInflation(res, modelZLB, modelZLBDualLinear, outputFolderAdditional; labelLinear = "Piecewise Linear", filename = "ForecastErrorsInflationPiecewise")
plotForecastErrorsInflationExpectations(res, modelZLB, modelZLBDualLinear, outputFolderAdditional; labelLinear = "Piecewise Linear", filename = "ForecastErrorsInflationExpectationPiecewise")
plotForecastErrorsInflation(res, modelZLB, modelZLBQuadLinear, outputFolderAdditional; labelLinear = "Piecewise Linear (4 Regions)", filename = "ForecastErrorsInflationPiecewise4Regions")
plotForecastErrorsInflationExpectations(res, modelZLB, modelZLBQuadLinear, outputFolderAdditional; labelLinear = "Piecewise Linear (4 Regions)", filename = "ForecastErrorsInflationExpectationPiecewise4Regions")
plotErgodicDistribution(res, modelZLB, modelZLBRANK, outputFolderAdditional; labelNoZLB = "ZLB-RANK", filename = "ErgodicDistributionHANKvsRANK")
plotImpulseResponseFunctions(res, modelZLB, modelZLBRANK, outputFolderAdditional; labelNoZLB = "ZLB-RANK", filename = "IRFComparisonHANKvsRANK")
plotPhaseDiagram(res, modelZLB, outputFolderAdditional)
plotPolicyFunctionComparison(res, modelZLB, modelNoZLB, outputFolderAdditional)
plotComparativeStaticsAdditional(res, modelsCompStat, σLabels, outputFolderAdditional)
plotResponseDecomposition(res, modelZLB, modelNoZLB, outputFolderAdditional; prodTypes = [:all], plotType = :modelAOnly, skipAdditionalFigure = true)
plotResponseDecomposition(res, modelZLB, modelNoZLB, outputFolderAdditional; prodTypes = [:all], plotType = :modelBOnly, skipAdditionalFigure = true)
# Additional tables
generateDSSSSSErgodicMeanTable(res, modelZLB, modelNoZLB, outputFolderAdditional)
generateDSSSSSErgodicMeanTable(res, modelZLB, modelZLBRANK, outputFolderAdditional; labelNoZLB = "ZLB-RANK", filename = "SteadyStatesAndErgodicMeansHANKvsRANK")
generateRateDecompositionTable(res, modelZLB, modelZLBRANK, outputFolderAdditional,)
generateRateDecompositionTable(res, modelZLBHighRotembergCost, modelZLBRANKHighRotembergCost, outputFolderAdditional, "HighRotembergCost")
generateComparativeStaticsTable(res, modelZLB, modelsCompStat, modelsCompStatPlus, σLabels, πTargets, outputFolderAdditional)
# Additional statistics only shown in REPL
computeAdditionalStatistics(res, modelZLB)
computeAdditionalStatistics(res, modelNoZLB)
display("Plots generated!")
nothing
end
"""
plotPLMInflation(res, modelZLB, outputFolder)
Plots the PLM for inflation for a given solution file.
"""
function plotPLMInflation(res, modelZLB, outputFolder; filename = "PLMInflation")
# Make some variables more easily accesible
DSS = res[modelZLB][:DSS]
simSeries = res[modelZLB][:simSeriesPlus] # To make it easier to draw use simSeriesPlus which only has 10000 samples
P = res[modelZLB][:P]
πwALM = res[modelZLB][:πwALM]
# Add simulated data points and differentiate between cases where the ZLB is binding and where it's not
ZLBCheck = HANKWageRigidities.checkZLB.(Ref(P), Ref(DSS), simSeries[:π][2:end], simSeries[:Y][2:end], simSeries[:RStar][1:end-1])
RStarSimZLB = simSeries[:RStar][1:end-1][ZLBCheck .== 1]
πSimZLB = simSeries[:π][2:end][ZLBCheck .== 1]
ζSimZLB = simSeries[:ζ][2:end][ZLBCheck .== 1]
RStarSimNotZLB = simSeries[:RStar][1:end-1][ZLBCheck .== 0]
πSimNotZLB = simSeries[:π][2:end][ZLBCheck .== 0]
ζSimNotZLB = simSeries[:ζ][2:end][ZLBCheck .== 0]
smplZLB = 1:1:length(ζSimZLB)
smplNotZLB = 1:1:length(ζSimNotZLB)
p1 = scatter3d(log.(RStarSimZLB[smplZLB])*400, ζSimZLB[smplZLB], log.(πSimZLB[smplZLB])*400,
color = palette(:RdYlGn_9)[1],
markersize = 2,
markerstrokewidth = 0.4,
xlabel = L"Nominal Rate $R_{t-1}$ (\%)",
ylabel = L"Preference Shock $\xi_t$",
zlabel = L"Inflation $\pi_t$ (\%)",
camera = (-60,20),
legend = :none, margin = 5Plots.PlotMeasures.mm, cbar = :none)
scatter3d!(p1, log.(RStarSimNotZLB[smplNotZLB])*400, ζSimNotZLB[smplNotZLB], log.(πSimNotZLB[smplNotZLB])*400,
color = palette(:RdYlGn_9)[9],
markersize = 2,
markerstrokewidth = 0.4)
zlims!(-4.0, 5.0)
ylims!(0.945, 1.055)
#display(p1)
#savefig(p1, "$(outputFolder)/PLMInflationOnlySimulatedData.pdf")
p2 = surface(log.(P.RDenseGrid)*400, P.ζDenseGrid, log.(πwALM')*400,
xlabel = L"Nominal Rate $R_{t-1}$ (\%)",
ylabel = L"Preference Shock $\xi_t$",
zlabel = L"Inflation $\pi_t$ (\%)",
camera = (-60,20),
legend = :none, margin = 5Plots.PlotMeasures.mm, cbar = :none,
colormap_name = "viridis",
extra_kwargs = :subplot)
zlims!(-4.0, 5.0)
ylims!(0.945, 1.055)
#display(p2)
#savefig(p2, "$(outputFolder)/PLMInflation.pdf")
title!(p1, L"\textrm{(b) Simulated Inflation }\pi(\xi_t,R_{t-1})")
title!(p2, L"\textrm{(a) Perceived Inflation }\hat{\pi}(\xi_t,R_{t-1})")
p = plot(p2, p1, layout = grid(1,2), size = (900, 300))
display(p)
savefig(p, "$(outputFolder)/$(filename).pdf")
savefig(p, "$(outputFolder)/$(filename).png")
#savefig(p, "$(outputFolder)/$(filename).tex")
nothing
end
"""
plotForecastErrorsInflation(res, modelZLB, modelZLBLinear, outputFolder)
Plots the forecast errors for inflation for given solution files.
"""
function plotForecastErrorsInflation(res, modelZLB, modelZLBLinear, outputFolder;
nbins = -0.5:0.02:1.5, minError = -0.25, maxError = 1.0, filename = "ForecastErrorsInflation",
labelZLB = "Neural Network", labelLinear = "Linear")
# Make some variables more easily accesible
P = res[modelZLB][:P]
DSS = res[modelZLB][:DSS] # DSS is the same in both modelZLB and modelZLBLinear
simSeries = res[modelZLB][:simSeries]
simSeriesLinear = res[modelZLBLinear][:simSeries]
πwALMInterpol = res[modelZLB][:πwALMInterpol]
πwALMInterpolLinear = res[modelZLBLinear][:πwALMInterpol]
# Forecast errors inflation PLM
errorsNN, statsNN = computeForecastErrorsInflationPLM(simSeries[:πw], simSeries[:RStar], simSeries[:ζ], πwALMInterpol; rescaleErrors = true)
errorsLinear, statsLinear = computeForecastErrorsInflationPLM(simSeriesLinear[:πw], simSeriesLinear[:RStar], simSeriesLinear[:ζ], πwALMInterpolLinear; rescaleErrors = true)
p1 = histogram(errorsNN,
label = L"%$labelZLB (R$^2$ = %$(round(statsNN.R2*100, digits = 2))%)",
xlim = (minError, maxError),
linewidth = 0.2,
fillalpha = 0.5,
xlabel = "Errors (pp)",
normalize = :density,
nbins = nbins,
legend = :topright)
histogram!(errorsLinear,
label = L"%$labelLinear (R$^2$ = %$(round(statsLinear.R2*100, digits = 2))%)",
xlim = (minError, maxError),
linewidth = 0.2,
fillalpha = 0.5,
normalize = :density,
nbins = nbins,
legend = :topright)
# Forecast errors for ZLB periods only
ZLBCheck = HANKWageRigidities.checkZLB.(Ref(P), Ref(DSS), simSeries[:π][2:end], simSeries[:Y][2:end], simSeries[:RStar][1:end-1])
errorsNN, statsNN = computeForecastErrorsInflationPLMZLBOnly(simSeries[:πw], simSeries[:RStar], simSeries[:ζ], πwALMInterpol, ZLBCheck; rescaleErrors = true)
ZLBCheckLinear = HANKWageRigidities.checkZLB.(Ref(P), Ref(DSS), simSeriesLinear[:π][2:end], simSeriesLinear[:Y][2:end], simSeriesLinear[:RStar][1:end-1])
errorsLinear, statsLinear = computeForecastErrorsInflationPLMZLBOnly(simSeriesLinear[:πw], simSeriesLinear[:RStar], simSeriesLinear[:ζ], πwALMInterpolLinear, ZLBCheckLinear; rescaleErrors = true)
p2 = histogram(errorsNN,
label = L"%$labelZLB (R$^2$ = %$(round(statsNN.R2*100, digits = 2))%)",
xlim = (minError, maxError),
linewidth = 0.2,
fillalpha = 0.5,
xlabel = "Errors (pp)",
normalize = :density,
nbins = nbins,
legend = :topright)
histogram!(errorsLinear,
label = L"%$labelLinear (R$^2$ = %$(round(statsLinear.R2*100, digits = 2))%)",
xlim = (minError, maxError),
linewidth = 0.2,
fillalpha = 0.5,
normalize = :density,
nbins = nbins,
legend = :topright)
#display(p2)
#savefig(p2, "$(outputFolder)/PLMForecastErrorsInflationZLBOnly.pdf")
plot!(p1, title = "(a) All Simulated Periods")
plot!(p2, title = "(b) Only Periods with binding ZLB")
p = plot(p1, p2, layout = grid(1,2), size = (900, 300))
display(p)
savefig(p, "$(outputFolder)/$(filename).pdf")
nothing
end
"""
plotForecastErrorsInflationExpectations(res, modelZLB, modelZLBLinear, outputFolder)
Plots the forecast errors for inflation expectations for given solution files.
"""
function plotForecastErrorsInflationExpectations(res, modelZLB, modelZLBLinear, outputFolder;
nbins = -0.5:0.02:1.5, minError = -0.25, maxError = 1.0, filename = "ForecastErrorsInflationExpectation",
labelZLB = "Neural Network", labelLinear = "Linear")
# Make some variables more easily accesible
P = res[modelZLB][:P]
DSS = res[modelZLB][:DSS] # DSS is the same in both modelZLB and modelZLBLinear
simSeries = res[modelZLB][:simSeries]
simSeriesLinear = res[modelZLBLinear][:simSeries]
EπwCondALMInterpol = res[modelZLB][:EπwCondALMInterpol]
EπwCondALMInterpolLinear = res[modelZLBLinear][:EπwCondALMInterpol]
# Forecast errors inflation expectation PLM
errorsNN, statsNN = computeForecastErrorsInflationExpectationPLM(simSeries[:EπwCond], simSeries[:RStar], simSeries[:ζ], EπwCondALMInterpol; rescaleErrors = true)
errorsLinear, statsLinear = computeForecastErrorsInflationExpectationPLM(simSeriesLinear[:EπwCond], simSeriesLinear[:RStar], simSeriesLinear[:ζ], EπwCondALMInterpolLinear; rescaleErrors = true)
p1 = histogram(errorsNN,
label = L"%$labelZLB (R$^2$ = %$(round(statsNN.R2*100, digits = 2))%)",
xlim = (minError, maxError),
linewidth = 0.2,
fillalpha = 0.5,
xlabel = "Errors (pp)",
normalize = :density,
nbins = nbins,
legend = :topright)
histogram!(errorsLinear,
label = L"%$labelLinear (R$^2$ = %$(round(statsLinear.R2*100, digits = 2))%)",
xlim = (minError, maxError),
linewidth = 0.2,
fillalpha = 0.5,
normalize = :density,
nbins = nbins,
legend = :topright)
#display(p1)
#savefig(p1, "$(outputFolder)/PLMForecastErrorsInflationExpectation.pdf")
# Forecast errors inflation expectations for ZLB periods only
ZLBCheck = HANKWageRigidities.checkZLB.(Ref(P), Ref(DSS), simSeries[:π][2:end-1], simSeries[:Y][2:end-1], simSeries[:RStar][1:end-2])
errorsNN, statsNN = computeForecastErrorsInflationExpectationPLMZLBOnly(simSeries[:EπwCond], simSeries[:RStar], simSeries[:ζ], EπwCondALMInterpol, ZLBCheck; rescaleErrors = true)
ZLBCheckLinear = HANKWageRigidities.checkZLB.(Ref(P), Ref(DSS), simSeriesLinear[:π][2:end-1], simSeriesLinear[:Y][2:end-1], simSeriesLinear[:RStar][1:end-2])
errorsLinear, statsLinear = computeForecastErrorsInflationExpectationPLMZLBOnly(simSeriesLinear[:EπwCond], simSeriesLinear[:RStar], simSeriesLinear[:ζ], EπwCondALMInterpolLinear, ZLBCheckLinear; rescaleErrors = true)
p2 = histogram(errorsNN,
label = L"%$labelZLB (R$^2$ = %$(round(statsNN.R2*100, digits = 2))%)",
xlim = (minError, maxError),
linewidth = 0.2,
fillalpha = 0.5,
xlabel = "Errors (pp)",
normalize = :density,
nbins = nbins,
legend = :topright)
histogram!(errorsLinear,
label = L"%$labelLinear (R$^2$ = %$(round(statsLinear.R2*100, digits = 2))%)",
xlim = (minError, maxError),
linewidth = 0.2,
fillalpha = 0.5,
normalize = :density,
nbins = nbins,
legend = :topright)
#display(p2)
#savefig(p2, "$(outputFolder)/PLMForecastErrorsInflationExpectationZLBOnly.pdf")
plot!(p1, title = "(a) All Simulated Periods")
plot!(p2, title = "(b) Only Periods with binding ZLB")
p = plot(p1, p2, size = (900, 300))
display(p)
savefig(p, "$(outputFolder)/$(filename).pdf")
end
"""
plotErgodicDistribution(res, modelZLB, modelNoZLB, outputFolder)
Plots a comparison of the ergodic distribution of two given solution files
"""
function plotErgodicDistribution(res, modelZLB, modelNoZLB, outputFolder;
labelZLB = "ZLB-HANK", labelNoZLB = "HANK", filename = "ErgodicDistributionZLBvsNoZLB")
function plotHist(x1, x2, nbins, xlabel; normalize = :probability)
p = histogram(x1,
xlabel = xlabel,
linewidth = 0.2,
fillalpha = 0.5,
normalize = normalize,
nbins = nbins,
label = "",
legend = :topleft)
histogram!(x2,
linewidth = 0.2,
fillalpha = 0.5,
normalize = normalize,
nbins = nbins,
label = "")
return p
end
# Inflation
p1 = plotHist(log.(res[modelZLB][:simSeries][:π])*400,
log.(res[modelNoZLB][:simSeries][:π])*400,
-6:0.25:10,
L"Inflation $\pi_t$ (\%)")
# Nominal Interest Rate
p2 = plotHist(log.(res[modelZLB][:simSeries][:R])*400,
log.(res[modelNoZLB][:simSeries][:R])*400,
-6:0.25:10,
L"Nominal Rate $R_{t-1}$ (\%)")
# Real Interest Rate
p3 = plotHist(log.(res[modelZLB][:simSeries][:r])*400,
log.(res[modelNoZLB][:simSeries][:r])*400,
-6:0.25:10,
L"Real Rate $r_t$ (\%)")
# Aggregate Consumption
p4 = plotHist(res[modelZLB][:simSeries][:C],
res[modelNoZLB][:simSeries][:C],
0.9:0.0025:1.05,
L"Aggregate Consumption $C_t$")
p1.series_list[1][:label] = labelZLB
p1.series_list[3][:label] = labelNoZLB
p = plot(p1, p2, p3, p4, layout = grid(2,2), size = (900, 600))
display(p)
savefig(p, "$(outputFolder)/$(filename).pdf")
nothing
end
"""
plotImpulseResponseFunctions(res, modelZLB, modelNoZLB, outputFolder)
Plot comparison of impulse responses.
"""
function plotImpulseResponseFunctions(res, modelZLB, modelNoZLB, outputFolder;
labelZLB = "ZLB-HANK", labelNoZLB = "HANK", filename = "IRFComparisonZLBvsNoZLB")
linewidth = 2
# Collect the IRFs
IRFs = [res[modelZLB][:IRFs1],
res[modelZLB][:IRFs3],
res[modelNoZLB][:IRFs1],
res[modelNoZLB][:IRFs3]]
# Collect the SSS associated to the IRFs
SSSs = [res[modelZLB][:SSS],
res[modelZLB][:SSS],
res[modelNoZLB][:SSS],
res[modelNoZLB][:SSS]]
# Define labels for the IRFs
IRFLabels = ["$labelZLB (1 std)",
"$labelZLB (3 std)",
"$labelNoZLB (1 std)",
"$labelNoZLB (3 std)"]
# Define the IRF colors and line
IRFStyles = [(color = palette(:Paired_10)[5], linestyle = :solid),
(color = palette(:Paired_10)[6], linestyle = :solid),
(color = palette(:Paired_10)[1], linestyle = :dash),
(color = palette(:Paired_10)[2], linestyle = :dash)]
# Define variables to be plotted
variables = [:π, :r, :R, :Y, :T, :ξ] # Note: τ_t = -T_t have the same IRFs
variableNames = [L"Inflation $\pi_t$ (pp)",
L"Real Rate $r_t$ (pp)",
L"Nominal Rate $R_{t}$ (pp)",
L"Output $Y_t$ (\%)",
L"Taxes $\tau_t$ (\%)",
L"Preference Shock $\xi_t$ (\%)"]
# Define which variables are interest rates
interestRateList = [:r, :π, :R]
# Shown period
period = 1:8
# Create the IRF plot
pAll = plotIRFComparison(IRFs, SSSs, IRFLabels, IRFStyles, variables, variableNames, interestRateList, period, linewidth)
p = plot(pAll..., layout = grid(3,2), size = (720, 720))
display(p)
savefig(p, "$(outputFolder)/$(filename).pdf")
nothing
end
"""
generateDSSSSSErgodicMeanTable(res, modelZLB, modelNoZLB, outputFolder)
Generates table with comparison of DSS, SSS and Ergodic Means for two given solution files.
"""
function generateDSSSSSErgodicMeanTable(res, modelZLB, modelNoZLB, outputFolder;
labelZLB = "ZLB-HANK", labelNoZLB = "HANK", filename = "SteadyStatesAndErgodicMeansZLBvsNoZLB")
# Settings
numberFormat = "%2.2f"
addGroupLines = true
# Define table caption
caption = "Comparison of DSS, SSS and Ergodic Means ($labelZLB vs $labelNoZLB)"
# Define the variables to be printed
variables = OrderedDict(:r => "Real Rate (\$r_t\$; \\%)",
:π => "Inflation (\$\\pi_t\$; \\%)",
:R => "Nominal Rate (\$R_t\$; \\%)",
:Y => "Output (\$Y_t\$)",
:C => "Consumption (\$C_t\$)",
:w => "Wage (\$w_t\$)",
:ZLBFreq => "(Shadow) ZLB Frequency (\\%)",
:ZLBSpellMean => "(Shadow) ZLB Spell Duration"
)
# Define which variables are (quarterly) interest rates
interestRateList = [:r, :π, :R]
# Define which variables are in percent
percentList = [:ZLBFreq]
# Function that returns a named tuple with simulation averages
function getSimAverages(res, model)
# Compute means of the existing variables
varNames = Tuple(keys(res[model][:simSeries]))
varValues = [mean(x) for x in values(res[model][:simSeries])]
# Compute ZLB spell duration and ZLB frequency
bindingZLBIndicator = res[model][:simSeries][:RStar] .<= 1.0
freqZLB = sum(bindingZLBIndicator) / length(bindingZLBIndicator)
durations = Int64[]
tmpDur = 0
for ii in 1:length(bindingZLBIndicator)
if bindingZLBIndicator[ii]
tmpDur += 1
else
if tmpDur != 0
push!(durations, tmpDur)
tmpDur = 0
end
end
end
meanDuration = mean(durations)
# Add the new variables
varNames = tuple(varNames..., :ZLBFreq, :ZLBSpellMean)
varValues = [varValues; freqZLB; meanDuration]
return NamedTuple{varNames}(varValues)
end
# Collect the SSS and DSS variables
steadyStates = [res[modelZLB][:DSS],
res[modelZLB][:SSS],
getSimAverages(res, modelZLB),
res[modelNoZLB][:DSS],
res[modelNoZLB][:SSS],
getSimAverages(res, modelNoZLB)]
# Define labels for the steady states
steadyStateLabels = ["DSS",
"SSS",
"Mean",
"DSS",
"SSS",
"Mean"]
superLabels = [(labelZLB, 3), (labelNoZLB, 3)]
#
allLines = []
# Add headings
push!(allLines, "\\begin{table}[h]")
push!(allLines, "\\centering")
push!(allLines, "\\caption{$(caption)}")
push!(allLines, "\\begin{tabular}{l*{$(length(steadyStateLabels))}{S[table-format=2.2]}}")
push!(allLines, "\\toprule")
# Generate the column "super" labels
if length(superLabels) > 0
currentLine = " "
for ii in 1:length(superLabels)
if superLabels[ii][2] == 1
currentLine *= " & {$(superLabels[ii][1])}"
else
currentLine *= " & \\multicolumn{$(superLabels[ii][2])}{c}{$(superLabels[ii][1])}"
end
end
currentLine *= "\\\\"
push!(allLines, currentLine)
end
# Add lines below HANK, RANK, etc.
if addGroupLines
currentLine = ""
currentColumn = 2
for ii in 1:length(superLabels)
if superLabels[ii][1] != ""
currentLine *= "\\cmidrule(lr){$(currentColumn)-$(currentColumn+superLabels[ii][2]-1)}"
end
currentColumn = currentColumn + superLabels[ii][2]
end
push!(allLines, currentLine)
end
# Generate the column labels
currentLine = "Variables "
for ii in 1:length(steadyStateLabels)
currentLine *= " & {$(steadyStateLabels[ii])}"
end
currentLine *= "\\\\"
push!(allLines, currentLine)
push!(allLines, "\\midrule")
# Generate the main contents of the table
for var in keys(variables)
currentLine = variables[var]
for ii in 1:length(steadyStates)
if haskey(steadyStates[ii], var)
if var in interestRateList
currentValue = sprintf1(numberFormat, log(steadyStates[ii][var])*400)
elseif var in percentList
currentValue = sprintf1(numberFormat, steadyStates[ii][var]*100)
else
currentValue = sprintf1(numberFormat, steadyStates[ii][var])
end
else
currentValue = "{-}"
end
currentLine *= " & $(currentValue)"
end
currentLine *= "\\\\"
push!(allLines, currentLine)
end
# Finish the table
push!(allLines, "\\bottomrule")
push!(allLines, "\\end{tabular}")
push!(allLines, "\\end{table}")
display(allLines)
# Write the table to a file
open("$(outputFolder)/$(filename).tex", "w") do f
for line in allLines
println(f, line)
end
end
end
"""
generateDSSSSSTable(res, modelZLB, modelNoZLB, modelZLBRANK, modelNoZLBRANK, outputFolder)
Generates table with comparison of DSS and SSS for four given solution files.
"""
function generateDSSSSSErgodicMeanTable(res, modelZLB, modelNoZLB, modelZLBRANK, modelNoZLBRANK, outputFolder;
labelZLB = "ZLB-HANK", labelNoZLB = "HANK", labelZLBRANK = "ZLB-RANK", labelNoZLBRANK = "RANK",
filename = "SteadyStatesZLBvsNoZLB")
# Settings
numberFormat = "%2.2f"
addGroupLines = true
# Define table caption
caption = "Comparison of DSS and SSS in $labelZLB, $labelNoZLB, $labelZLBRANK, and $labelNoZLBRANK."
# Define the variables to be printed
variables = OrderedDict(
:π => "Inflation",
:R => "Nominal Rate",
:r => "Real Rate",
:ZLBFreq => "(Shadow) ZLB Frequency"
)
# Define which variables are (quarterly) interest rates
interestRateList = [:r, :π, :R]
# Define which variables are in percent
percentList = [:ZLBFreq]
# Define which variables arise from simulations
simList = [:ZLBFreq]
# Function that returns a named tuple with simulation averages
function getSimAverages(res, model)
# Compute means of the existing variables
varNames = Tuple(keys(res[model][:simSeries]))
varValues = [mean(x) for x in values(res[model][:simSeries])]
# Compute ZLB spell duration and ZLB frequency
bindingZLBIndicator = res[model][:simSeries][:RStar] .<= 1.0
freqZLB = sum(bindingZLBIndicator) / length(bindingZLBIndicator)
durations = Int64[]
tmpDur = 0
for ii in 1:length(bindingZLBIndicator)
if bindingZLBIndicator[ii]
tmpDur += 1
else
if tmpDur != 0
push!(durations, tmpDur)
tmpDur = 0
end
end
end
meanDuration = mean(durations)
# Add the new variables
varNames = tuple(varNames..., :ZLBFreq, :ZLBSpellMean)
varValues = [varValues; freqZLB; meanDuration]
return NamedTuple{varNames}(varValues)
end
# Collect the SSS and DSS variables
steadyStates = [res[modelZLB][:DSS],
res[modelZLB][:SSS],
res[modelNoZLB][:DSS],
res[modelNoZLB][:SSS],
res[modelZLBRANK][:DSS],
res[modelZLBRANK][:SSS],
res[modelNoZLBRANK][:DSS],
res[modelNoZLBRANK][:SSS],]
simStats = [(dummy=NaN,),
getSimAverages(res, modelZLB),
(dummy=NaN,),
getSimAverages(res, modelNoZLB),
(dummy=NaN,),
getSimAverages(res, modelZLBRANK),
(dummy=NaN,),
getSimAverages(res, modelNoZLBRANK),]
# Define labels for the steady states
steadyStateLabels = ["DSS",
"SSS",
"DSS",
"SSS",
"DSS",
"SSS",
"DSS",
"SSS",]
superLabels = [(labelZLB, 2), (labelNoZLB, 2), (labelZLBRANK, 2), (labelNoZLBRANK, 2)]
#
allLines = []
# Add headings
push!(allLines, "\\begin{table}[h]")
push!(allLines, "\\centering")
push!(allLines, "\\caption{$(caption)}")
push!(allLines, "\\begin{tabular}{l*{$(length(steadyStateLabels))}{S[table-format=2.2]}}")
push!(allLines, "\\toprule")
# Generate the column "super" labels
if length(superLabels) > 0
currentLine = " "
for ii in 1:length(superLabels)
if superLabels[ii][2] == 1
currentLine *= " & {$(superLabels[ii][1])}"
else
currentLine *= " & \\multicolumn{$(superLabels[ii][2])}{c}{$(superLabels[ii][1])}"
end
end
currentLine *= "\\\\"
push!(allLines, currentLine)
end
# Add lines below HANK, RANK, etc.
if addGroupLines
currentLine = ""
currentColumn = 2
for ii in 1:length(superLabels)
if superLabels[ii][1] != ""
currentLine *= "\\cmidrule(lr){$(currentColumn)-$(currentColumn+superLabels[ii][2]-1)}"
end
currentColumn = currentColumn + superLabels[ii][2]
end
push!(allLines, currentLine)
end
# Generate the column labels
currentLine = "Variables "
for ii in 1:length(steadyStateLabels)
currentLine *= " & {$(steadyStateLabels[ii])}"
end
currentLine *= "\\\\"
push!(allLines, currentLine)
push!(allLines, "\\midrule")
# Generate the main contents of the table
for var in keys(variables)
currentLine = variables[var]
for ii in 1:length(steadyStates)
if haskey(steadyStates[ii], var) && var ∉ simList
if var in interestRateList
currentValue = sprintf1(numberFormat, log(steadyStates[ii][var])*400)
currentValue *= "\\%"
elseif var in percentList
currentValue = sprintf1(numberFormat, steadyStates[ii][var]*100)
currentValue *= "\\%"
else
currentValue = sprintf1(numberFormat, steadyStates[ii][var])
end
elseif haskey(simStats[ii], var) && var ∈ simList
if var in interestRateList
currentValue = sprintf1(numberFormat, log(simStats[ii][var])*400)
currentValue *= "\\%"
elseif var in percentList
currentValue = sprintf1(numberFormat, simStats[ii][var]*100)
currentValue *= "\\%"
else
currentValue = sprintf1(numberFormat, simStats[ii][var])
end
else
currentValue = "{-}"
end
currentLine *= " & $(currentValue)"
end
currentLine *= "\\\\"
push!(allLines, currentLine)
end
# Finish the table
push!(allLines, "\\bottomrule")
push!(allLines, "\\end{tabular}")
push!(allLines, "\\end{table}")
display(allLines)
# Write the table to a file
open("$(outputFolder)/$(filename).tex", "w") do f
for line in allLines
println(f, line)
end
end
end
"""
plotResponseDecomposition(res, modelB, modelA, outputFolder)
Plots the response decomposition.
"""
function plotResponseDecomposition(res, modelB, modelA, outputFolder; shortLabelA = "HANK", shortLabelB = "ZLB-HANK",
prodTypes = [:all, :average, :only1, :only2, :only3], saveOnlyCombinedPlots = false, skipAdditionalFigure = true,
outputFolderAdditional = outputFolder, plotType = :comparison)
for prodType = prodTypes
# Settings
periods = 1:1 # Range of periods used for computations
refIRF = :IRFs3 # Precomputed IRFs that are used for computations
decompType = :percentile # Categories for which decomposition is shown: :borrowersSavers, :percentile, :percentileNoAgg
#prodType = 1 # Productivity type used for :percentile and :percentileNoAgg
percList = [10, 99] # Percentile list used for :percentile and :percentileNoAgg
plotAvsB = false # true: switch model A with model B in the final plot
useCumulativeResponse = false # true: sums the percentage response for all periods defined above
# Labels of the components
labels = Dict()
labels[:interestIncome] = L"Interest$\;$" # Space at the end to improve legend spacing
labels[:laborIncome] = L"Labor Income$\;$"
labels[:transferIncome] = L"Taxes$\;$"
# Initalize dict with results
results = Dict()
# Compute the income response decompositions for each model
for model in [modelA, modelB]
# Extract the settings, IRFs and SSS from the results for easier access
P = res[model][:P]
IRFs = res[model][refIRF]
SSS = res[model][:SSS]
# Define the wealth levels that need to be evaluated
if decompType == :borrowersSavers
bSet = P.bDenseGrid
elseif decompType == :percentileNoAgg
bSet = [HANKWageRigidities.computePercentile(vec(sum(SSS[:bCross], dims = 2)), P.bDenseGrid, perc / 100) for perc in percList]
elseif decompType == :percentile
bSet = [HANKWageRigidities.computePercentile(vec(sum(SSS[:bCross], dims = 2)), P.bDenseGrid, perc / 100) for perc in percList]
bSet = [bSet; P.bDenseGrid]
else
error("Unknown decompType")
end
# Compute the income components at each point in time
incomeComponents = HANKWageRigidities.computeIncomeComponentsGrid(P, periods, bSet, IRFs, SSS)
# Compute the income components in the SSS
incomeComponentsSSS = HANKWageRigidities.computeIncomeComponentsGridSSS(P, bSet, SSS)
# Aggregate income components (e.g. to get borrowers and savers)
incomeComponents, incomeComponentsSSS = HANKWageRigidities.aggregateIncomeComponentsGrid(P, decompType, periods, percList, prodType, bSet, IRFs, SSS, incomeComponents, incomeComponentsSSS)
# Compute contributions of income components (analogous to computing "growth contributions")
for incomeType in keys(incomeComponents)
rate = incomeComponents[incomeType] ./ incomeComponentsSSS[incomeType] .- 1
weights = incomeComponentsSSS[incomeType] ./ incomeComponentsSSS[:totalIncome]
incomeComponents[incomeType] = rate .* weights * 100
end
# Check whether there are issues in the previous step (usually this is due to a component being zero in levels)
for incomeType in keys(incomeComponents)
if any(isnan.(incomeComponents[incomeType]))