-
Notifications
You must be signed in to change notification settings - Fork 16
/
get_functions.jl
3128 lines (2398 loc) · 129 KB
/
get_functions.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
"""
$(SIGNATURES)
Return the shock decomposition in absolute deviations from the non stochastic steady state based on the Kalman smoother or filter (depending on the `smooth` keyword argument) using the provided data and first order solution of the model. Data is by default assumed to be in levels unless `data_in_levels` is set to `false`.
# Arguments
- $MODEL
- $DATA
# Keyword Arguments
- $PARAMETERS
- $DATA_IN_LEVELS
- $SMOOTH
- $VERBOSE
# Examples
```jldoctest
using MacroModelling
@model RBC begin
1 / c[0] = (β / c[1]) * (α * exp(z[1]) * k[0]^(α - 1) + (1 - δ))
c[0] + k[0] = (1 - δ) * k[-1] + q[0]
q[0] = exp(z[0]) * k[-1]^α
z[0] = ρ * z[-1] + std_z * eps_z[x]
end
@parameters RBC begin
std_z = 0.01
ρ = 0.2
δ = 0.02
α = 0.5
β = 0.95
end
simulation = simulate(RBC)
get_shock_decomposition(RBC,simulation([:c],:,:simulate))
# output
3-dimensional KeyedArray(NamedDimsArray(...)) with keys:
↓ Variables ∈ 4-element Vector{Symbol}
→ Shocks ∈ 2-element Vector{Symbol}
◪ Periods ∈ 40-element UnitRange{Int64}
And data, 4×2×40 Array{Float64, 3}:
[showing 3 of 40 slices]
[:, :, 1] ~ (:, :, 1):
(:eps_z₍ₓ₎) (:Initial_values)
(:c) 0.000407252 -0.00104779
(:k) 0.00374808 -0.0104645
(:q) 0.00415533 -0.000807161
(:z) 0.000603617 -1.99957e-6
[:, :, 21] ~ (:, :, 21):
(:eps_z₍ₓ₎) (:Initial_values)
(:c) 0.026511 -0.000433619
(:k) 0.25684 -0.00433108
(:q) 0.115858 -0.000328764
(:z) 0.0150266 0.0
[:, :, 40] ~ (:, :, 40):
(:eps_z₍ₓ₎) (:Initial_values)
(:c) 0.0437976 -0.000187505
(:k) 0.4394 -0.00187284
(:q) 0.00985518 -0.000142164
(:z) -0.00366442 8.67362e-19
```
"""
function get_shock_decomposition(𝓂::ℳ,
data::KeyedArray{Float64};
parameters::ParameterType = nothing,
data_in_levels::Bool = true,
smooth::Bool = true,
verbose::Bool = false)
solve!(𝓂, parameters = parameters, verbose = verbose, dynamics = true)
reference_steady_state, (solution_error, iters) = 𝓂.solution.outdated_NSSS ? 𝓂.SS_solve_func(𝓂.parameter_values, 𝓂, verbose, false, 𝓂.solver_parameters) : (copy(𝓂.solution.non_stochastic_steady_state), (eps(), 0))
data = data(sort(axiskeys(data,1)))
obs_axis = collect(axiskeys(data,1))
obs_symbols = obs_axis isa String_input ? obs_axis .|> Meta.parse .|> replace_indices : obs_axis
obs_idx = parse_variables_input_to_index(obs_symbols, 𝓂.timings)
if data_in_levels
data_in_deviations = data .- reference_steady_state[obs_idx]
else
data_in_deviations = data
end
filtered_and_smoothed = filter_and_smooth(𝓂, data_in_deviations, obs_symbols; verbose = verbose)
axis1 = 𝓂.timings.var
if any(x -> contains(string(x), "◖"), axis1)
axis1_decomposed = decompose_name.(axis1)
axis1 = [length(a) > 1 ? string(a[1]) * "{" * join(a[2],"}{") * "}" * (a[end] isa Symbol ? string(a[end]) : "") : string(a[1]) for a in axis1_decomposed]
end
axis2 = vcat(𝓂.timings.exo, :Initial_values)
if any(x -> contains(string(x), "◖"), axis2)
axis2_decomposed = decompose_name.(axis2)
axis2 = [length(a) > 1 ? string(a[1]) * "{" * join(a[2],"}{") * "}" * (a[end] isa Symbol ? string(a[end]) : "") : string(a[1]) for a in axis2_decomposed]
axis2[1:length(𝓂.timings.exo)] = axis2[1:length(𝓂.timings.exo)] .* "₍ₓ₎"
else
axis2 = vcat(map(x->Symbol(string(x) * "₍ₓ₎"), 𝓂.timings.exo), :Initial_values)
end
return KeyedArray(filtered_and_smoothed[smooth ? 4 : 8][:,1:end-1,:]; Variables = axis1, Shocks = axis2, Periods = 1:size(data,2))
end
"""
$(SIGNATURES)
Return the estimated shocks based on the inversion filter (depending on the `filter` keyword argument), or Kalman filter or smoother (depending on the `smooth` keyword argument) using the provided data and (non-)linear solution of the model. Data is by default assumed to be in levels unless `data_in_levels` is set to `false`.
# Arguments
- $MODEL
- $DATA
# Keyword Arguments
- $PARAMETERS
- $ALGORITHM
- $FILTER
- `warmup_iterations` [Default: `0`, Type: `Int`]: periods added before the first observation for which shocks are computed such that the first observation is matched. A larger value alleviates the problem that the initial value is the relevant steady state.
- $DATA_IN_LEVELS
- $SMOOTH
- $VERBOSE
# Examples
```jldoctest
using MacroModelling
@model RBC begin
1 / c[0] = (β / c[1]) * (α * exp(z[1]) * k[0]^(α - 1) + (1 - δ))
c[0] + k[0] = (1 - δ) * k[-1] + q[0]
q[0] = exp(z[0]) * k[-1]^α
z[0] = ρ * z[-1] + std_z * eps_z[x]
end
@parameters RBC begin
std_z = 0.01
ρ = 0.2
δ = 0.02
α = 0.5
β = 0.95
end
simulation = simulate(RBC)
get_estimated_shocks(RBC,simulation([:c],:,:simulate))
# output
2-dimensional KeyedArray(NamedDimsArray(...)) with keys:
↓ Shocks ∈ 1-element Vector{Symbol}
→ Periods ∈ 40-element UnitRange{Int64}
And data, 1×40 Matrix{Float64}:
(1) (2) (3) (4) … (37) (38) (39) (40)
(:eps_z₍ₓ₎) 0.0603617 0.614652 -0.519048 0.711454 -0.873774 1.27918 -0.929701 -0.2255
```
"""
function get_estimated_shocks(𝓂::ℳ,
data::KeyedArray{Float64};
parameters::ParameterType = nothing,
algorithm::Symbol = :first_order,
filter::Symbol = :kalman,
warmup_iterations::Int = 0,
data_in_levels::Bool = true,
smooth::Bool = true,
verbose::Bool = false)
@assert filter ∈ [:kalman, :inversion] "Currently only the kalman filter (:kalman) for linear models and the inversion filter (:inversion) for linear and nonlinear models are supported."
if algorithm ∈ [:second_order,:pruned_second_order,:third_order,:pruned_third_order]
filter = :inversion
end
solve!(𝓂, parameters = parameters, algorithm = algorithm, verbose = verbose, dynamics = true)
reference_steady_state, (solution_error, iters) = 𝓂.solution.outdated_NSSS ? 𝓂.SS_solve_func(𝓂.parameter_values, 𝓂, verbose, false, 𝓂.solver_parameters) : (copy(𝓂.solution.non_stochastic_steady_state), (eps(), 0))
data = data(sort(axiskeys(data,1)))
obs_axis = collect(axiskeys(data,1))
obs_symbols = obs_axis isa String_input ? obs_axis .|> Meta.parse .|> replace_indices : obs_axis
obs_idx = parse_variables_input_to_index(obs_symbols, 𝓂.timings)
if data_in_levels
data_in_deviations = data .- reference_steady_state[obs_idx]
else
data_in_deviations = data
end
if filter == :kalman
filtered_and_smoothed = filter_and_smooth(𝓂, data_in_deviations, obs_symbols; verbose = verbose)
shocks = filtered_and_smoothed[smooth ? 3 : 7]
elseif filter == :inversion
states, shocks = inversion_filter(𝓂, data_in_deviations, algorithm, warmup_iterations = warmup_iterations)
end
axis1 = 𝓂.timings.exo
if any(x -> contains(string(x), "◖"), axis1)
axis1_decomposed = decompose_name.(axis1)
axis1 = [length(a) > 1 ? string(a[1]) * "{" * join(a[2],"}{") * "}" * (a[end] isa Symbol ? string(a[end]) : "") : string(a[1]) for a in axis1_decomposed]
axis1 = axis1 .* "₍ₓ₎"
else
axis1 = map(x->Symbol(string(x) * "₍ₓ₎"),𝓂.timings.exo)
end
return KeyedArray(shocks; Shocks = axis1, Periods = 1:size(data,2))
end
"""
$(SIGNATURES)
Return the estimated variables (in levels by default, see `levels` keyword argument) based on the inversion filter (depending on the `filter` keyword argument), or Kalman filter or smoother (depending on the `smooth` keyword argument) using the provided data and (non-)linear solution of the model. Data is by default assumed to be in levels unless `data_in_levels` is set to `false`.
# Arguments
- $MODEL
- $DATA
# Keyword Arguments
- $PARAMETERS
- $ALGORITHM
- $FILTER
- `warmup_iterations` [Default: `0`, Type: `Int`]: periods added before the first observation for which shocks are computed such that the first observation is matched. A larger value alleviates the problem that the initial value is the relevant steady state.
- $DATA_IN_LEVELS
- $LEVELS
- $SMOOTH
- $VERBOSE
# Examples
```jldoctest
using MacroModelling
@model RBC begin
1 / c[0] = (β / c[1]) * (α * exp(z[1]) * k[0]^(α - 1) + (1 - δ))
c[0] + k[0] = (1 - δ) * k[-1] + q[0]
q[0] = exp(z[0]) * k[-1]^α
z[0] = ρ * z[-1] + std_z * eps_z[x]
end
@parameters RBC begin
std_z = 0.01
ρ = 0.2
δ = 0.02
α = 0.5
β = 0.95
end
simulation = simulate(RBC)
get_estimated_variables(RBC,simulation([:c],:,:simulate))
# output
2-dimensional KeyedArray(NamedDimsArray(...)) with keys:
↓ Variables ∈ 4-element Vector{Symbol}
→ Periods ∈ 40-element UnitRange{Int64}
And data, 4×40 Matrix{Float64}:
(1) (2) (3) (4) … (37) (38) (39) (40)
(:c) 5.92901 5.92797 5.92847 5.92048 5.95845 5.95697 5.95686 5.96173
(:k) 47.3185 47.3087 47.3125 47.2392 47.6034 47.5969 47.5954 47.6402
(:q) 6.87159 6.86452 6.87844 6.79352 7.00476 6.9026 6.90727 6.95841
(:z) -0.00109471 -0.00208056 4.43613e-5 -0.0123318 0.0162992 0.000445065 0.00119089 0.00863586
```
"""
function get_estimated_variables(𝓂::ℳ,
data::KeyedArray{Float64};
parameters::ParameterType = nothing,
algorithm::Symbol = :first_order,
filter::Symbol = :kalman,
warmup_iterations::Int = 0,
data_in_levels::Bool = true,
levels::Bool = true,
smooth::Bool = true,
verbose::Bool = false)
@assert filter ∈ [:kalman, :inversion] "Currently only the kalman filter (:kalman) for linear models and the inversion filter (:inversion) for linear and nonlinear models are supported."
if algorithm ∈ [:second_order,:pruned_second_order,:third_order,:pruned_third_order]
filter = :inversion
end
solve!(𝓂, parameters = parameters, algorithm = algorithm, verbose = verbose, dynamics = true)
reference_steady_state, (solution_error, iters) = 𝓂.solution.outdated_NSSS ? 𝓂.SS_solve_func(𝓂.parameter_values, 𝓂, verbose, false, 𝓂.solver_parameters) : (copy(𝓂.solution.non_stochastic_steady_state), (eps(), 0))
data = data(sort(axiskeys(data,1)))
obs_axis = collect(axiskeys(data,1))
obs_symbols = obs_axis isa String_input ? obs_axis .|> Meta.parse .|> replace_indices : obs_axis
obs_idx = parse_variables_input_to_index(obs_symbols, 𝓂.timings)
if data_in_levels
data_in_deviations = data .- reference_steady_state[obs_idx]
else
data_in_deviations = data
end
if filter == :kalman
filtered_and_smoothed = filter_and_smooth(𝓂, data_in_deviations, obs_symbols; verbose = verbose)
states = filtered_and_smoothed[smooth ? 1 : 5]
elseif filter == :inversion
states, shocks = inversion_filter(𝓂, data_in_deviations, algorithm, warmup_iterations = warmup_iterations)
end
axis1 = 𝓂.timings.var
if any(x -> contains(string(x), "◖"), axis1)
axis1_decomposed = decompose_name.(axis1)
axis1 = [length(a) > 1 ? string(a[1]) * "{" * join(a[2],"}{") * "}" * (a[end] isa Symbol ? string(a[end]) : "") : string(a[1]) for a in axis1_decomposed]
end
return KeyedArray(levels ? states .+ reference_steady_state[1:length(𝓂.var)] : states; Variables = axis1, Periods = 1:size(data,2))
end
"""
$(SIGNATURES)
Return the standard deviations of the Kalman smoother or filter (depending on the `smooth` keyword argument) estimates of the model variables based on the provided data and first order solution of the model. Data is by default assumed to be in levels unless `data_in_levels` is set to `false`.
# Arguments
- $MODEL
- $DATA
# Keyword Arguments
- $PARAMETERS
- $DATA_IN_LEVELS
- $SMOOTH
- $VERBOSE
# Examples
```jldoctest
using MacroModelling
@model RBC begin
1 / c[0] = (β / c[1]) * (α * exp(z[1]) * k[0]^(α - 1) + (1 - δ))
c[0] + k[0] = (1 - δ) * k[-1] + q[0]
q[0] = exp(z[0]) * k[-1]^α
z[0] = ρ * z[-1] + std_z * eps_z[x]
end
@parameters RBC begin
std_z = 0.01
ρ = 0.2
δ = 0.02
α = 0.5
β = 0.95
end
simulation = simulate(RBC)
get_estimated_variable_standard_deviations(RBC,simulation([:c],:,:simulate))
# output
2-dimensional KeyedArray(NamedDimsArray(...)) with keys:
↓ Standard_deviations ∈ 4-element Vector{Symbol}
→ Periods ∈ 40-element UnitRange{Int64}
And data, 4×40 Matrix{Float64}:
(1) (2) (3) (4) … (38) (39) (40)
(:c) 1.23202e-9 1.84069e-10 8.23181e-11 8.23181e-11 8.23181e-11 8.23181e-11 0.0
(:k) 0.00509299 0.000382934 2.87922e-5 2.16484e-6 1.6131e-9 9.31323e-10 1.47255e-9
(:q) 0.0612887 0.0046082 0.000346483 2.60515e-5 1.31709e-9 1.31709e-9 9.31323e-10
(:z) 0.00961766 0.000723136 5.43714e-5 4.0881e-6 3.08006e-10 3.29272e-10 2.32831e-10
```
"""
function get_estimated_variable_standard_deviations(𝓂::ℳ,
data::KeyedArray{Float64};
parameters::ParameterType = nothing,
data_in_levels::Bool = true,
smooth::Bool = true,
verbose::Bool = false)
solve!(𝓂, parameters = parameters, verbose = verbose, dynamics = true)
reference_steady_state, (solution_error, iters) = 𝓂.solution.outdated_NSSS ? 𝓂.SS_solve_func(𝓂.parameter_values, 𝓂, verbose, false, 𝓂.solver_parameters) : (copy(𝓂.solution.non_stochastic_steady_state), (eps(), 0))
data = data(sort(axiskeys(data,1)))
obs_axis = collect(axiskeys(data,1))
obs_symbols = obs_axis isa String_input ? obs_axis .|> Meta.parse .|> replace_indices : obs_axis
obs_idx = parse_variables_input_to_index(obs_symbols, 𝓂.timings)
if data_in_levels
data_in_deviations = data .- reference_steady_state[obs_idx]
else
data_in_deviations = data
end
filtered_and_smoothed = filter_and_smooth(𝓂, data_in_deviations, obs_symbols; verbose = verbose)
axis1 = 𝓂.timings.var
if any(x -> contains(string(x), "◖"), axis1)
axis1_decomposed = decompose_name.(axis1)
axis1 = [length(a) > 1 ? string(a[1]) * "{" * join(a[2],"}{") * "}" * (a[end] isa Symbol ? string(a[end]) : "") : string(a[1]) for a in axis1_decomposed]
end
return KeyedArray(filtered_and_smoothed[smooth ? 2 : 6]; Standard_deviations = axis1, Periods = 1:size(data,2))
end
"""
$(SIGNATURES)
Return the conditional forecast given restrictions on endogenous variables and shocks (optional) in a 2-dimensional array. By default (see `levels`), the values represent absolute deviations from the relevant steady state (e.g. higher order perturbation algorithms are relative to the stochastic steady state). A constrained minimisation problem is solved to find the combinations of shocks with the smallest magnitude to match the conditions.
# Arguments
- $MODEL
- $CONDITIONS
# Keyword Arguments
- $SHOCK_CONDITIONS
- `initial_state` [Default: `[0.0]`, Type: `Union{Vector{Vector{Float64}},Vector{Float64}}`]: The initial state defines the starting point for the model and is relevant for normal IRFs. In the case of pruned solution algorithms the initial state can be given as multiple state vectors (`Vector{Vector{Float64}}`). In this case the initial state must be given in devations from the non-stochastic steady state. In all other cases the initial state must be given in levels. If a pruned solution algorithm is selected and initial state is a `Vector{Float64}` then it impacts the first order initial state vector only. The state includes all variables as well as exogenous variables in leads or lags if present.
- `periods` [Default: `40`, Type: `Int`]: the total number of periods is the sum of the argument provided here and the maximum of periods of the shocks or conditions argument.
- $PARAMETERS
- $VARIABLES
- `conditions_in_levels` [Default: `true`, Type: `Bool`]: indicator whether the conditions are provided in levels. If `true` the input to the conditions argument will have the non stochastic steady state substracted.
- $ALGORITHM
- $LEVELS
- $VERBOSE
# Examples
```jldoctest
using MacroModelling
using SparseArrays, AxisKeys
@model RBC_CME begin
y[0]=A[0]*k[-1]^alpha
1/c[0]=beta*1/c[1]*(alpha*A[1]*k[0]^(alpha-1)+(1-delta))
1/c[0]=beta*1/c[1]*(R[0]/Pi[+1])
R[0] * beta =(Pi[0]/Pibar)^phi_pi
A[0]*k[-1]^alpha=c[0]+k[0]-(1-delta*z_delta[0])*k[-1]
z_delta[0] = 1 - rho_z_delta + rho_z_delta * z_delta[-1] + std_z_delta * delta_eps[x]
A[0] = 1 - rhoz + rhoz * A[-1] + std_eps * eps_z[x]
end
@parameters RBC_CME begin
alpha = .157
beta = .999
delta = .0226
Pibar = 1.0008
phi_pi = 1.5
rhoz = .9
std_eps = .0068
rho_z_delta = .9
std_z_delta = .005
end
# c is conditioned to deviate by 0.01 in period 1 and y is conditioned to deviate by 0.02 in period 3
conditions = KeyedArray(Matrix{Union{Nothing,Float64}}(undef,2,2),Variables = [:c,:y], Periods = 1:2)
conditions[1,1] = .01
conditions[2,2] = .02
# in period 2 second shock (eps_z) is conditioned to take a value of 0.05
shocks = Matrix{Union{Nothing,Float64}}(undef,2,1)
shocks[1,1] = .05
get_conditional_forecast(RBC_CME, conditions, shocks = shocks, conditions_in_levels = false)
# output
2-dimensional KeyedArray(NamedDimsArray(...)) with keys:
↓ Variables_and_shocks ∈ 9-element Vector{Symbol}
→ Periods ∈ 42-element UnitRange{Int64}
And data, 9×42 Matrix{Float64}:
(1) (2) … (41) (42)
(:A) 0.0313639 0.0134792 0.000221372 0.000199235
(:Pi) 0.000780257 0.00020929 -0.000146071 -0.000140137
(:R) 0.00117156 0.00031425 -0.000219325 -0.000210417
(:c) 0.01 0.00600605 0.00213278 0.00203751
(:k) 0.034584 0.0477482 … 0.0397631 0.0380482
(:y) 0.0446375 0.02 0.00129544 0.001222
(:z_delta) 0.00025 0.000225 3.69522e-6 3.3257e-6
(:delta_eps) 0.05 0.0 0.0 0.0
(:eps_z) 4.61234 -2.16887 0.0 0.0
# The same can be achieved with the other input formats:
# conditions = Matrix{Union{Nothing,Float64}}(undef,7,2)
# conditions[4,1] = .01
# conditions[6,2] = .02
# using SparseArrays
# conditions = spzeros(7,2)
# conditions[4,1] = .01
# conditions[6,2] = .02
# shocks = KeyedArray(Matrix{Union{Nothing,Float64}}(undef,1,1),Variables = [:delta_eps], Periods = [1])
# shocks[1,1] = .05
# using SparseArrays
# shocks = spzeros(2,1)
# shocks[1,1] = .05
```
"""
function get_conditional_forecast(𝓂::ℳ,
conditions::Union{Matrix{Union{Nothing,Float64}}, SparseMatrixCSC{Float64}, KeyedArray{Union{Nothing,Float64}}, KeyedArray{Float64}};
shocks::Union{Matrix{Union{Nothing,Float64}}, SparseMatrixCSC{Float64}, KeyedArray{Union{Nothing,Float64}}, KeyedArray{Float64}, Nothing} = nothing,
initial_state::Union{Vector{Vector{Float64}},Vector{Float64}} = [0.0],
periods::Int = 40,
parameters::ParameterType = nothing,
variables::Union{Symbol_input,String_input} = :all_excluding_obc,
conditions_in_levels::Bool = true,
algorithm::Symbol = :first_order,
levels::Bool = false,
verbose::Bool = false)
periods += max(size(conditions,2), shocks isa Nothing ? 1 : size(shocks,2)) # isa Nothing needed otherwise JET tests fail
if conditions isa SparseMatrixCSC{Float64}
@assert length(𝓂.var) == size(conditions,1) "Number of rows of condition argument and number of model variables must match. Input to conditions has " * repr(size(conditions,1)) * " rows but the model has " * repr(length(𝓂.var)) * " variables (including auxilliary variables): " * repr(𝓂.var)
cond_tmp = Matrix{Union{Nothing,Float64}}(undef,length(𝓂.var),periods)
nzs = findnz(conditions)
for i in 1:length(nzs[1])
cond_tmp[nzs[1][i],nzs[2][i]] = nzs[3][i]
end
conditions = cond_tmp
elseif conditions isa Matrix{Union{Nothing,Float64}}
@assert length(𝓂.var) == size(conditions,1) "Number of rows of condition argument and number of model variables must match. Input to conditions has " * repr(size(conditions,1)) * " rows but the model has " * repr(length(𝓂.var)) * " variables (including auxilliary variables): " * repr(𝓂.var)
cond_tmp = Matrix{Union{Nothing,Float64}}(undef,length(𝓂.var),periods)
cond_tmp[:,axes(conditions,2)] = conditions
conditions = cond_tmp
elseif conditions isa KeyedArray{Union{Nothing,Float64}} || conditions isa KeyedArray{Float64}
conditions_axis = collect(axiskeys(conditions,1))
conditions_symbols = conditions_axis isa String_input ? conditions_axis .|> Meta.parse .|> replace_indices : conditions_axis
@assert length(setdiff(conditions_symbols, 𝓂.var)) == 0 "The following symbols in the first axis of the conditions matrix are not part of the model: " * repr(setdiff(conditions_symbols,𝓂.var))
cond_tmp = Matrix{Union{Nothing,Float64}}(undef,length(𝓂.var),periods)
cond_tmp[indexin(sort(conditions_symbols),𝓂.var),axes(conditions,2)] .= conditions(sort(axiskeys(conditions,1)))
conditions = cond_tmp
end
if shocks isa SparseMatrixCSC{Float64}
@assert length(𝓂.exo) == size(shocks,1) "Number of rows of shocks argument and number of model variables must match. Input to shocks has " * repr(size(shocks,1)) * " rows but the model has " * repr(length(𝓂.exo)) * " shocks: " * repr(𝓂.exo)
shocks_tmp = Matrix{Union{Nothing,Number}}(nothing,length(𝓂.exo),periods)
nzs = findnz(shocks)
for i in 1:length(nzs[1])
shocks_tmp[nzs[1][i],nzs[2][i]] = nzs[3][i]
end
shocks = shocks_tmp
elseif shocks isa Matrix{Union{Nothing,Float64}}
@assert length(𝓂.exo) == size(shocks,1) "Number of rows of shocks argument and number of model variables must match. Input to shocks has " * repr(size(shocks,1)) * " rows but the model has " * repr(length(𝓂.exo)) * " shocks: " * repr(𝓂.exo)
shocks_tmp = Matrix{Union{Nothing,Number}}(nothing,length(𝓂.exo),periods)
shocks_tmp[:,axes(shocks,2)] = shocks
shocks = shocks_tmp
elseif shocks isa KeyedArray{Union{Nothing,Float64}} || shocks isa KeyedArray{Float64}
shocks_axis = collect(axiskeys(shocks,1))
shocks_symbols = shocks_axis isa String_input ? shocks_axis .|> Meta.parse .|> replace_indices : shocks_axis
@assert length(setdiff(shocks_symbols,𝓂.exo)) == 0 "The following symbols in the first axis of the shocks matrix are not part of the model: " * repr(setdiff(shocks_symbols, 𝓂.exo))
shocks_tmp = Matrix{Union{Nothing,Number}}(nothing,length(𝓂.exo),periods)
shocks_tmp[indexin(sort(shocks_symbols), 𝓂.exo), axes(shocks,2)] .= shocks(sort(axiskeys(shocks,1)))
shocks = shocks_tmp
elseif isnothing(shocks)
shocks = Matrix{Union{Nothing,Number}}(nothing,length(𝓂.exo),periods)
end
solve!(𝓂, parameters = parameters, verbose = verbose, dynamics = true, algorithm = algorithm)
state_update, pruning = parse_algorithm_to_state_update(algorithm, 𝓂, false)
reference_steady_state, NSSS, SSS_delta = get_relevant_steady_states(𝓂, algorithm)
unspecified_initial_state = initial_state == [0.0]
if unspecified_initial_state
if algorithm == :pruned_second_order
initial_state = [zeros(𝓂.timings.nVars), zeros(𝓂.timings.nVars) - SSS_delta]
elseif algorithm == :pruned_third_order
initial_state = [zeros(𝓂.timings.nVars), zeros(𝓂.timings.nVars) - SSS_delta, zeros(𝓂.timings.nVars)]
else
initial_state = zeros(𝓂.timings.nVars) - SSS_delta
end
else
if initial_state isa Vector{Float64}
if algorithm == :pruned_second_order
initial_state = [initial_state - reference_steady_state[1:𝓂.timings.nVars], zeros(𝓂.timings.nVars) - SSS_delta]
elseif algorithm == :pruned_third_order
initial_state = [initial_state - reference_steady_state[1:𝓂.timings.nVars], zeros(𝓂.timings.nVars) - SSS_delta, zeros(𝓂.timings.nVars)]
else
initial_state = initial_state - NSSS
end
else
if algorithm ∉ [:pruned_second_order, :pruned_third_order]
@assert initial_state isa Vector{Float64} "The solution algorithm has one state vector: initial_state must be a Vector{Float64}."
end
end
end
var_idx = parse_variables_input_to_index(variables, 𝓂.timings)
Y = zeros(size(𝓂.solution.perturbation.first_order.solution_matrix,1),periods)
cond_var_idx = findall(conditions[:,1] .!= nothing)
free_shock_idx = findall(shocks[:,1] .== nothing)
shocks[free_shock_idx,1] .= 0
if conditions_in_levels
conditions[cond_var_idx,1] .-= reference_steady_state[cond_var_idx] + SSS_delta[cond_var_idx]
else
conditions[cond_var_idx,1] .-= SSS_delta[cond_var_idx]
end
@assert length(free_shock_idx) >= length(cond_var_idx) "Exact matching only possible with at least as many free shocks than conditioned variables. Period 1 has " * repr(length(free_shock_idx)) * " free shock(s) and " * repr(length(cond_var_idx)) * " conditioned variable(s)."
if algorithm ∈ [:second_order, :third_order, :pruned_second_order, :pruned_third_order]
precision_factor = 1.0
p = (conditions[:,1], state_update, shocks[:,1], cond_var_idx, free_shock_idx, initial_state, pruning, 𝒷, precision_factor)
res = @suppress begin Optim.optimize(x -> minimize_distance_to_conditions(x, p),
zeros(length(free_shock_idx)),
Optim.LBFGS(linesearch = LineSearches.BackTracking(order = 3)),
Optim.Options(f_abstol = eps(), g_tol= 1e-30);
autodiff = :forward) end
matched = Optim.minimum(res) < 1e-12
if !matched
res = @suppress begin Optim.optimize(x -> minimize_distance_to_conditions(x, p),
zeros(length(free_shock_idx)),
Optim.LBFGS(),
Optim.Options(f_abstol = eps(), g_tol= 1e-30);
autodiff = :forward) end
matched = Optim.minimum(res) < 1e-12
end
@assert matched "Numerical stabiltiy issues for restrictions in period 1."
x = Optim.minimizer(res)
shocks[free_shock_idx,1] .= x
initial_state = state_update(initial_state, Float64[shocks[:,1]...])
Y[:,1] = pruning ? sum(initial_state) : initial_state
for i in 2:size(conditions,2)
cond_var_idx = findall(conditions[:,i] .!= nothing)
if conditions_in_levels
conditions[cond_var_idx,i] .-= reference_steady_state[cond_var_idx] + SSS_delta[cond_var_idx]
else
conditions[cond_var_idx,i] .-= SSS_delta[cond_var_idx]
end
free_shock_idx = findall(shocks[:,i] .== nothing)
shocks[free_shock_idx,i] .= 0
@assert length(free_shock_idx) >= length(cond_var_idx) "Exact matching only possible with at least as many free shocks than conditioned variables. Period " * repr(i) * " has " * repr(length(free_shock_idx)) * " free shock(s) and " * repr(length(cond_var_idx)) * " conditioned variable(s)."
p = (conditions[:,i], state_update, shocks[:,i], cond_var_idx, free_shock_idx, pruning ? initial_state : Y[:,i-1], pruning, 𝒷, precision_factor)
res = @suppress begin Optim.optimize(x -> minimize_distance_to_conditions(x, p),
zeros(length(free_shock_idx)),
Optim.LBFGS(linesearch = LineSearches.BackTracking(order = 3)),
Optim.Options(f_abstol = eps(), g_tol= 1e-30);
autodiff = :forward) end
matched = Optim.minimum(res) < 1e-12
if !matched
res = @suppress begin Optim.optimize(x -> minimize_distance_to_conditions(x, p),
zeros(length(free_shock_idx)),
Optim.LBFGS(),
Optim.Options(f_abstol = eps(), g_tol= 1e-30);
autodiff = :forward) end
matched = Optim.minimum(res) < 1e-12
end
@assert matched "Numerical stabiltiy issues for restrictions in period $i."
x = Optim.minimizer(res)
shocks[free_shock_idx,i] .= x
initial_state = state_update(initial_state, Float64[shocks[:,i]...])
Y[:,i] = pruning ? sum(initial_state) : initial_state
end
elseif algorithm ∈ [:first_order, :riccati, :quadratic_iteration, :linear_time_iteration]
C = @views 𝓂.solution.perturbation.first_order.solution_matrix[:,𝓂.timings.nPast_not_future_and_mixed+1:end]
CC = C[cond_var_idx,free_shock_idx]
if length(cond_var_idx) == 1
@assert any(CC .!= 0) "Free shocks have no impact on conditioned variable in period 1."
elseif length(free_shock_idx) == length(cond_var_idx)
CC = RF.lu(CC, check = false)
@assert ℒ.issuccess(CC) "Numerical stabiltiy issues for restrictions in period 1."
end
shocks[free_shock_idx,1] .= 0
shocks[free_shock_idx,1] = CC \ (conditions[cond_var_idx,1] - state_update(initial_state, Float64[shocks[:,1]...])[cond_var_idx])
Y[:,1] = state_update(initial_state, Float64[shocks[:,1]...])
for i in 2:size(conditions,2)
cond_var_idx = findall(conditions[:,i] .!= nothing)
if conditions_in_levels
conditions[cond_var_idx,i] .-= reference_steady_state[cond_var_idx]
end
free_shock_idx = findall(shocks[:,i] .== nothing)
shocks[free_shock_idx,i] .= 0
@assert length(free_shock_idx) >= length(cond_var_idx) "Exact matching only possible with more free shocks than conditioned variables. Period " * repr(i) * " has " * repr(length(free_shock_idx)) * " free shock(s) and " * repr(length(cond_var_idx)) * " conditioned variable(s)."
CC = C[cond_var_idx,free_shock_idx]
if length(cond_var_idx) == 1
@assert any(CC .!= 0) "Free shocks have no impact on conditioned variable in period " * repr(i) * "."
elseif length(free_shock_idx) == length(cond_var_idx)
CC = RF.lu(CC, check = false)
@assert ℒ.issuccess(CC) "Numerical stabiltiy issues for restrictions in period " * repr(i) * "."
end
shocks[free_shock_idx,i] = CC \ (conditions[cond_var_idx,i] - state_update(Y[:,i-1], Float64[shocks[:,i]...])[cond_var_idx])
Y[:,i] = state_update(Y[:,i-1], Float64[shocks[:,i]...])
end
end
axis1 = [𝓂.timings.var[var_idx]; 𝓂.timings.exo]
if any(x -> contains(string(x), "◖"), axis1)
axis1_decomposed = decompose_name.(axis1)
axis1 = [length(a) > 1 ? string(a[1]) * "{" * join(a[2],"}{") * "}" * (a[end] isa Symbol ? string(a[end]) : "") : string(a[1]) for a in axis1_decomposed]
axis1[end-length(𝓂.timings.exo)+1:end] = axis1[end-length(𝓂.timings.exo)+1:end] .* "₍ₓ₎"
else
axis1 = [𝓂.timings.var[var_idx]; map(x->Symbol(string(x) * "₍ₓ₎"), 𝓂.timings.exo)]
end
return KeyedArray([Y[var_idx,:] .+ (levels ? reference_steady_state + SSS_delta : SSS_delta)[var_idx]; convert(Matrix{Float64}, shocks)]; Variables_and_shocks = axis1, Periods = 1:periods)
end
"""
$(SIGNATURES)
Return impulse response functions (IRFs) of the model in a 3-dimensional array.
Function to use when differentiating IRFs with repect to parameters.
# Arguments
- $MODEL
- $PARAMETER_VALUES
# Keyword Arguments
- $PERIODS
- $VARIABLES
- $SHOCKS
- $NEGATIVE_SHOCK
- $INITIAL_STATE
- $LEVELS
- $VERBOSE
# Examples
```jldoctest
using MacroModelling
@model RBC begin
1 / c[0] = (β / c[1]) * (α * exp(z[1]) * k[0]^(α - 1) + (1 - δ))
c[0] + k[0] = (1 - δ) * k[-1] + q[0]
q[0] = exp(z[0]) * k[-1]^α
z[0] = ρ * z[-1] + std_z * eps_z[x]
end
@parameters RBC begin
std_z = 0.01
ρ = 0.2
δ = 0.02
α = 0.5
β = 0.95
end
get_irf(RBC, RBC.parameter_values)
# output
4×40×1 Array{Float64, 3}:
[:, :, 1] =
0.00674687 0.00729773 0.00715114 0.00687615 … 0.00146962 0.00140619
0.0620937 0.0718322 0.0712153 0.0686381 0.0146789 0.0140453
0.0688406 0.0182781 0.00797091 0.0057232 0.00111425 0.00106615
0.01 0.002 0.0004 8.0e-5 2.74878e-29 5.49756e-30
```
"""
function get_irf(𝓂::ℳ,
parameters::Vector;
periods::Int = 40,
variables::Union{Symbol_input,String_input} = :all_excluding_obc,
shocks::Union{Symbol_input,String_input,Matrix{Float64},KeyedArray{Float64}} = :all,
negative_shock::Bool = false,
initial_state::Vector{Float64} = [0.0],
levels::Bool = false,
verbose::Bool = false)
solve!(𝓂, verbose = verbose)
shocks = 𝓂.timings.nExo == 0 ? :none : shocks
@assert shocks != :simulate "Use parameters as a known argument to simulate the model."
shocks = shocks isa KeyedArray ? axiskeys(shocks,1) isa Vector{String} ? rekey(shocks, 1 => axiskeys(shocks,1) .|> Meta.parse .|> replace_indices) : shocks : shocks
shocks = shocks isa String_input ? shocks .|> Meta.parse .|> replace_indices : shocks
if shocks isa Matrix{Float64}
@assert size(shocks)[1] == 𝓂.timings.nExo "Number of rows of provided shock matrix does not correspond to number of shocks. Please provide matrix with as many rows as there are shocks in the model."
periods += size(shocks)[2]
shock_history = zeros(𝓂.timings.nExo, periods)
shock_history[:,1:size(shocks)[2]] = shocks
shock_idx = 1
elseif shocks isa KeyedArray{Float64}
shocks_axis = collect(axiskeys(shocks,1))
shocks_symbols = shocks_axis isa String_input ? shocks_axis .|> Meta.parse .|> replace_indices : shocks_axis
shock_input = map(x->Symbol(replace(string(x), "₍ₓ₎" => "")), shocks_symbols)
periods += size(shocks)[2]
@assert length(setdiff(shock_input, 𝓂.timings.exo)) == 0 "Provided shocks which are not part of the model."
shock_history = zeros(𝓂.timings.nExo, periods)
shock_history[indexin(shock_input,𝓂.timings.exo),1:size(shocks)[2]] = shocks
shock_idx = 1
else
shock_idx = parse_shocks_input_to_index(shocks,𝓂.timings)
end
reference_steady_state, (solution_error, iters) = 𝓂.SS_solve_func(parameters, 𝓂, verbose, false, 𝓂.solver_parameters)
∇₁ = calculate_jacobian(parameters, reference_steady_state, 𝓂) |> Matrix
sol_mat, solved = calculate_first_order_solution(∇₁; T = 𝓂.timings)
state_update = function(state::Vector, shock::Vector) sol_mat * [state[𝓂.timings.past_not_future_and_mixed_idx]; shock] end
var_idx = parse_variables_input_to_index(variables, 𝓂.timings)
initial_state = initial_state == [0.0] ? zeros(𝓂.timings.nVars) : initial_state - reference_steady_state[1:length(𝓂.var)]
# Y = zeros(𝓂.timings.nVars,periods,𝓂.timings.nExo)
Ŷ = []
for ii in shock_idx
Y = []
if shocks != :simulate && shocks isa Union{Symbol_input,String_input}
shock_history = zeros(𝓂.timings.nExo,periods)
shock_history[ii,1] = negative_shock ? -1 : 1
end
if shocks == :none
shock_history = zeros(𝓂.timings.nExo,periods)
end
push!(Y, state_update(initial_state,shock_history[:,1]))
for t in 1:periods-1
push!(Y, state_update(Y[end],shock_history[:,t+1]))
end
push!(Ŷ, reduce(hcat,Y))
end
deviations = reshape(reduce(hcat,Ŷ),𝓂.timings.nVars,periods,length(shock_idx))[var_idx,:,:]
if levels
return deviations .+ reference_steady_state[var_idx]
else
return deviations
end
end
"""
$(SIGNATURES)
Return impulse response functions (IRFs) of the model in a 3-dimensional KeyedArray. By default (see `levels`), the values represent absolute deviations from the relevant steady state (e.g. higher order perturbation algorithms are relative to the stochastic steady state).
# Arguments
- $MODEL
# Keyword Arguments
- $PERIODS
- $ALGORITHM
- $PARAMETERS
- $VARIABLES
- $SHOCKS
- $NEGATIVE_SHOCK
- $GENERALISED_IRF
- `initial_state` [Default: `[0.0]`, Type: `Union{Vector{Vector{Float64}},Vector{Float64}}`]: The initial state defines the starting point for the model and is relevant for normal IRFs. In the case of pruned solution algorithms the initial state can be given as multiple state vectors (`Vector{Vector{Float64}}`). In this case the initial state must be given in devations from the non-stochastic steady state. In all other cases the initial state must be given in levels. If a pruned solution algorithm is selected and initial state is a `Vector{Float64}` then it impacts the first order initial state vector only. The state includes all variables as well as exogenous variables in leads or lags if present.
- $LEVELS
- `ignore_obc` [Default: `false`, Type: `Bool`]: solve the model ignoring the occasionally binding constraints.
- $VERBOSE
# Examples
```jldoctest
using MacroModelling
@model RBC begin
1 / c[0] = (β / c[1]) * (α * exp(z[1]) * k[0]^(α - 1) + (1 - δ))
c[0] + k[0] = (1 - δ) * k[-1] + q[0]
q[0] = exp(z[0]) * k[-1]^α
z[0] = ρ * z[-1] + std_z * eps_z[x]
end
@parameters RBC begin
std_z = 0.01
ρ = 0.2
δ = 0.02
α = 0.5
β = 0.95
end
get_irf(RBC)
# output
3-dimensional KeyedArray(NamedDimsArray(...)) with keys:
↓ Variables ∈ 4-element Vector{Symbol}
→ Periods ∈ 40-element UnitRange{Int64}
◪ Shocks ∈ 1-element Vector{Symbol}
And data, 4×40×1 Array{Float64, 3}:
[:, :, 1] ~ (:, :, :eps_z):
(1) (2) … (39) (40)
(:c) 0.00674687 0.00729773 0.00146962 0.00140619
(:k) 0.0620937 0.0718322 0.0146789 0.0140453
(:q) 0.0688406 0.0182781 0.00111425 0.00106615
(:z) 0.01 0.002 2.74878e-29 5.49756e-30
```
"""
function get_irf(𝓂::ℳ;
periods::Int = 40,
algorithm::Symbol = :first_order,
parameters::ParameterType = nothing,
variables::Union{Symbol_input,String_input} = :all_excluding_obc,
shocks::Union{Symbol_input,String_input,Matrix{Float64},KeyedArray{Float64}} = :all_excluding_obc,
negative_shock::Bool = false,
generalised_irf::Bool = false,
initial_state::Union{Vector{Vector{Float64}},Vector{Float64}} = [0.0],
levels::Bool = false,
ignore_obc::Bool = false,
verbose::Bool = false)
shocks = shocks isa KeyedArray ? axiskeys(shocks,1) isa Vector{String} ? rekey(shocks, 1 => axiskeys(shocks,1) .|> Meta.parse .|> replace_indices) : shocks : shocks
shocks = shocks isa String_input ? shocks .|> Meta.parse .|> replace_indices : shocks
shocks = 𝓂.timings.nExo == 0 ? :none : shocks
@assert !(shocks == :none && generalised_irf) "Cannot compute generalised IRFs for model without shocks."
stochastic_model = length(𝓂.timings.exo) > 0
obc_model = length(𝓂.obc_violation_equations) > 0
if shocks isa Matrix{Float64}
@assert size(shocks)[1] == 𝓂.timings.nExo "Number of rows of provided shock matrix does not correspond to number of shocks. Please provide matrix with as many rows as there are shocks in the model."
periods += size(shocks)[2]
shock_history = zeros(𝓂.timings.nExo, periods)
shock_history[:,1:size(shocks)[2]] = shocks
shock_idx = 1
obc_shocks_included = stochastic_model && obc_model && sum(abs2,shocks[contains.(string.(𝓂.timings.exo),"ᵒᵇᶜ"),:]) > 1e-10
elseif shocks isa KeyedArray{Float64}
shock_input = map(x->Symbol(replace(string(x),"₍ₓ₎" => "")),axiskeys(shocks)[1])