1
+ export backtest
2
+
3
+ struct Backtest
4
+ abs_errors:: Matrix{Float64}
5
+ crps_scores:: Matrix{Float64}
6
+ function Backtest (n:: Int , steps_ahead:: Int )
7
+ abs_errors = Matrix {Float64} (undef, n, steps_ahead)
8
+ crps_scores = Matrix {Float64} (undef, n, steps_ahead)
9
+ return new (abs_errors, crps_scores)
10
+ end
11
+ end
12
+
13
+ discrete_crps_indicator_function (val:: T , z:: T ) where {T} = val < z
14
+ function crps (val:: T , scenarios:: Vector{T} ) where {T}
15
+ sorted_scenarios = sort (scenarios)
16
+ m = length (scenarios)
17
+ crps_score = zero (T)
18
+ for i = 1 : m
19
+ crps_score +=
20
+ (sorted_scenarios[i] - val) *
21
+ (m * discrete_crps_indicator_function (val, sorted_scenarios[i]) - i + 0.5 )
22
+ end
23
+ return (2 / m^ 2 ) * crps_score
24
+ end
25
+ evaluate_abs_error (y:: Vector{T} , forecast:: Vector{T} ) where T = abs .(y - forecast)
26
+ function evaluate_crps (y:: Vector{T} , scenarios:: Matrix{T} ) where {T}
27
+ crps_scores = Vector {T} (undef, length (y))
28
+ for k = 1 : length (y)
29
+ crps_scores[k] = crps (y[k], scenarios[k, :])
30
+ end
31
+ return crps_scores
32
+ end
33
+
34
+ """
35
+ TODO
36
+ """
37
+ function backtest (gas:: Model{<:Distribution, T} , y:: Vector{T} , steps_ahead:: Int , start_idx:: Int ;
38
+ S:: Int = 1000 ,
39
+ initial_params:: Matrix{T} = stationary_initial_params (gas),
40
+ opt_method = NelderMead (gas, DEFAULT_NUM_SEEDS)) where T
41
+ num_mle = length (y) - start_idx - steps_ahead
42
+ backtest = Backtest (num_mle, steps_ahead)
43
+ for i in 1 : num_mle
44
+ println (" Backtest: step $i of $num_mle " )
45
+ gas_to_fit = deepcopy (gas)
46
+ y_to_fit = y[1 : start_idx - 1 + i]
47
+ y_to_verify = y[start_idx + i: start_idx - 1 + i + steps_ahead]
48
+ ScoreDrivenModels. fit! (gas_to_fit, y_to_fit; initial_params= initial_params, opt_method= opt_method)
49
+ forec = forecast (y_to_fit, gas_to_fit, steps_ahead; S= S, initial_params= initial_params)
50
+ abs_errors = evaluate_abs_error (y_to_verify, forec. observation_forecast)
51
+ crps_scores = evaluate_crps (y_to_verify, forec. observation_scenarios)
52
+ backtest. abs_errors[i, :] = abs_errors
53
+ backtest. crps_scores[i, :] = crps_scores
54
+ end
55
+ return backtest
56
+ end
0 commit comments