-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathSSM.R
2617 lines (2032 loc) · 107 KB
/
SSM.R
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
# R code for
# ****************************************************************
# * An Introduction to State Space Time Series Analysis (2007). *
# * Jacques J.F. Commandeur and Siem Jan Koopman. *
# * Oxford: Oxford University Press. *
# ****************************************************************
#R LIBRARIES, FOLDERS and FUNCTIONS####
#Installing, if needed, packages and loading the installed pacakages from the library
if(!(require(normtest))){install.packages('normtest')}
library(normtest)
if(!(require(KFAS))){install.packages('KFAS')}
library(KFAS)
if(!(require(rstudioapi))){install.packages('rstudioapi')}
library(rstudioapi)
if(!(require(knitr))){install.packages('knitr')}
library(knitr)
if(!(require(eurostat))){install.packages('eurostat')}
library(eurostat)
if(!(require(dplyr))){install.packages('dplyr')}
library(dplyr)
if(!(require(forecast))){install.packages('forecast')}
library(forecast)
#Cleaning workspace
rm(list=ls())
#Setting directory for files with data; they should be in the same directory as the files of source code
current_path = rstudioapi::getActiveDocumentContext()$path
setwd(dirname(current_path))
print(getwd())
#Function for Q-statistic
#Q-statistic is a general omnibus test that can be used to check whether
#the combined first k autocorrelations significantly deviate from 0,
#meaning the null hypothesis of independence must be rejected
#We assume that the residuals are independent if the test statistic does not exceed the critical value.
qStatistic <- function(predResid, k, w) {
#Standardised residuals as predResid should be submitted into this function!
#k - first k autocorrelations to be used in test; w - number of the disturbance variances
#(see Commandeur and Koopman, p.90-96)
value <- Box.test(predResid, lag = k, type = "Ljung")$statistic #Q-statistic based on the statistic calulated in the Ljung-Box test for lags from 1 to k
criticalValue <- qchisq(0.95, k-w+1) #Critical value corresponding to the upper 5% in the chi-square-distribution with k-w+1 degrees of freedom
list(#List of values provided by the function
k = k, #First k autocorrelations
value = unname(value), #Value of the test statistic
criticalValue = criticalValue #Critical value
)
}
#Function for r-statistic
#r-statistic checks independence of one-step-ahead prediction residuals
#It provides values of the autocorrelations at lags 1 and l, together with the 95% confidence limits.
#We assume that the residuals are independent if the values of the autocorrelations
#do not exceed the critical values for the 95% confidence limits
#(see Commandeur and Koopman, p.90-96)
rStatistic <- function(predResid, d, l) {
#Standardised residuals as predResid should be submitted into this function!
#d - diffuse initial value of the state, l - autocorrelation at lag l to be provided by the function
n <- (length(predResid)-d) #Length of the series after subtracting d, the number of diffuse initial elements of the state
acfValues <- acf(predResid[-(1:d)], plot = FALSE)$acf[-1]# List of the values of the autocorrelations for the series without the first d values
criticalValue <- 2 / sqrt(n) # +/- critical value for the 95% confidence limits
list( #List of values provided by the function
l = c(1,l), #lags 1 and l
value1 = acfValues[1], #Value of the autocorrelation at lag 1
value2 = acfValues[l], #Value of the autocorrelation at lag l
criticalValue = criticalValue # +/- critical value for 95% confidence limits
)
}
#Function for H-statistic
#H-statistic checks homoscedasticity of one-step-ahead prediction residuals
#This is done by testing the null hypothesis of the equal variances of the residuals
#in the first third part of the series and the last third part of the series.
#The ratio between these two variances is tested against an F-distribution with (h,h) degrees of freedom
#applying the usual 5% rule for rejection of the null hypothesis of equal variances, for a two-tailed test.
#We must find critical values corresponding to the upper and lower 2.5% in the two tails of the F-distribution;
#If, however, the tested statistic is larger than or equal to 1, it is enough to check
#whether it is lower than the critical value #corresponding to the upper 2.5% in the F-distribution;
#On the other hand, if the statistic is lower than 1 we have to test
#if its reciprocal value (1/ratio) is lower than the above-mentioned critical value.
#We assume that the residuals are homoscedastic if the test statistic does not exceed the critical value.
#(see Commandeur and Koopman, p.90-96)
hStatistic <- function(predResid, d) {
#Standardised residuals as predResid should be submitted into this function!
#d - number of diffuse initial values in the state,
n <- length(predResid) # Number of observations/residuals
h <- round((n-d)/3, digits = 0) #One third of the series: nearest integer to (n-d)/3; also degrees of freedom for the test
ratio <- sum(predResid[(n-h+1):n]^2) / sum(predResid[(d+1):(d+h)]^2) #Ratio between the variance of the residuals in the last third part of the series and the variance of residuals in the first third part of the series
value <- ifelse(ratio >= 1, ratio, 1/ratio) # Value of the test statistic; if the ratio is smaller than 1 then the reciprocal value is used for testing (1/ratio)
criticalValue <- qf(0.975, h, h) # Critical value corresponding to the upper 2.5% in the F-distribution with (h,h) degrees of freedom
list( #List of values provided by the function
h = h, #Degrees of freedom
ratio = ratio, #Ratio between the two variances
value = value, #Value of the test statistic
criticalValue = criticalValue #Critical value
)
}
#Function for N-statistic
#H-statistic checks normality of one-step-ahead prediction residuals
#This is done by testing the null hypothesis of normality
#We assume that the residuals are normally distributed if the test statistic does not exceed the critical value at 5% level
#(see Commandeur and Koopman, p.90-96)
nStatistic <- function(predResid, d) {
#Standardised residuals as predResid should be submitted into this function!
#d - number of diffuse initial values in the state
value <- jb.norm.test(predResid[-(1:d)])$statistic #N-statistic based on the statistic calculated in the Jarque and Bera or Shenton and Bowman test;
criticalValue <- qchisq(0.95,2) #Critical value corresponding to the upper 5% in the chi-square-distribution with 2 degrees of freedom
list(#List of values provided by the function
value = unname(value), #Value of the test statistic
criticalValue = criticalValue #Critical value
)
}
#Function to create a table with statistics
dTable <- function(qStatistic, rStatistic, hStatistic, nStatistic, title){
cat(title)
cat("\n")
diagnosticTemplateTable <- c(
"-----------------------------------------------------------------------------",
" statistic value critical value asumption satisfied",
"-----------------------------------------------------------------------------",
"independence Q(%2d) %7.3f %5.2f %1s", # Q-statistic, 4 args
" r(%1d) %7.3f +-%4.2f %1s", # r-statistics, 4 args
" r(%2d) %7.3f +-%4.2f %1s", # r, 4 args
"homoscedasticity %-3s(%2d) %7.3f %5.2f %1s", # Homo, 5 args
"normality N %7.3f %5.2f %1s", # N, 3 args
"-----------------------------------------------------------------------------"
)
cat( sprintf( paste(diagnosticTemplateTable, collapse = "\n"),
# Q-statistic, 4 args
qStatistic$k,
qStatistic$value,
qStatistic$criticalValue,
ifelse(qStatistic$value < qStatistic$criticalValue, "+", "-"),
# r-statistic, 4 args
rStatistic$l[1],
rStatistic$value1,
rStatistic$criticalValue,
ifelse(abs(rStatistic$value1) < rStatistic$criticalValue, "+", "-"),
# r-statistic, 4 args
rStatistic$l[2],
rStatistic$value2,
rStatistic$criticalValue,
ifelse(abs(rStatistic$value2) < rStatistic$criticalValue, "+", "-"),
# H-statistic, 5 args
ifelse(hStatistic$ratio > 1, " H", "1/H"),
hStatistic$h,
hStatistic$value,
hStatistic$criticalValue,
ifelse(hStatistic$value < hStatistic$criticalValue, "+", "-"),
# N, 3 args
nStatistic$value,
nStatistic$criticalValue,
ifelse(nStatistic$value < nStatistic$criticalValue, "+", "-") ) )
}
#Function to find best initial values for optim ver. 1
initValOpt <- function(w_ = w , model_ = model, updatefn_ = ownupdatefn, method = "Nelder-Mead", maxLoop = 100){
results <- matrix(NA, maxLoop, 2) %>%
data.frame() %>%
`colnames<-`(c("Log.likelihood", "Initial.value"))
#set.seed(123)
cat("Loop: ")
for (j in 1:maxLoop){
cat(paste(j, " "))
x <- runif(1, min = 0.00001, max = 2) %>% round(3)
fit <- fitSSM(inits = log(rep(x, w_)), model = model_, updatefn = updatefn_, method = method)
maxLik <- (logLik(fit$model, method = method)/n) %>% round(7)
#results[j, ] <- c(round(maxLik, 7), x)
results[j, ] <- c(maxLik, x)
}
cat("\n")
results %>% arrange(desc(Log.likelihood), Initial.value) %>% print()
return(results[1,2])
}
#desc(Log.likelihood)
#Function to find best initial values for optim ver. 2
initValOpt2 <- function(formula = "log(rep(x, 3))", model_ = model, updatefn_ = ownupdatefn, method = "Nelder-Mead", maxLoop = 100){
results <- matrix(NA, maxLoop, 2) %>%
data.frame() %>%
`colnames<-`(c("Log.likelihood", "Initial.value"))
#set.seed(123)
cat("Loop: ")
for (j in 1:maxLoop){
cat(paste(j, ""))
x <- runif(1, min = 0.00001, max = 2) %>% round(3)
fit <- fitSSM(inits = eval(parse(text = formula)), model = model_, updatefn = updatefn_, method = method)
maxLik <- (logLik(fit$model, method = method)/n) %>% round(7)
results[j, ] <- c(maxLik, x)
}
cat("\n")
results %>% arrange(desc(Log.likelihood), Initial.value) %>% print()
return(results[1,2])
}
#CHAPTER 1: Introduction####
data <- log(read.table("UKdriversKSI.txt"))
colnames(data) <- "logUKdriversKSI"
time <- 1:nrow(data)
fit <- lm(data$logUKdriversKSI~time)
(coef <- fit$coefficients) # Coefficients of regrerssion
f.stat <- summary(fit)$fstatistic
(f.stat.val <- f.stat[1]) # F-test value
(f.stat.p <- pf(f.stat[1], f.stat[2], f.stat[3], lower.tail = F)) # p-value for F-test
(error.var <- summary(fit)$sigma^2) # Error variance
#Figure 1.1. Scatter plot of the log of the number of UK drivers KSI
#against time (in months), including regression line
plot(data$logUKdriversKSI, col = "darkgrey", xlab = "",ylab = "log UK drivers KSI",
pch = 3,cex = 0.5, cex.lab = 0.8,cex.axis = 0.9,xlim = c(0,200))
abline(coef, col = "blue", lwd = 2, lty = 2)
title(main = "Figure 1.1. Scatter plot of the log of the number of UK drivers KSI
against time (in months), including regression line", cex.main = 0.8)
legend("topright",leg = c("log UK drivers KSI against time (in months)",
"regression line"), cex = 0.5,lty = c(0, 2), col = c("darkgrey","blue"),
pch = c(3,NA), bty = "y",horiz = T)
#Figure 1.2. Log of the number of UK drivers KSI plotted as a time series
plot(ts(data$logUKdriversKSI),ylab = "",xlab = "",xlim = c(0,200), col = "darkgrey")
title(main = "Figure 1.2. Log of the number of UK drivers KSI plotted as a time series",
cex.main = 0.8)
legend("topright",leg = "log UK drivers KSI",cex = 0.5,lty = 1, col = "darkgrey",horiz = T)
#Figure1.4. Correlogram of random time series
random.series <- rnorm(nrow(data))
Acf(c(random.series), 15, main = "", ylab = "")
title(main = "Figure1.4. Correlogram of random time series",
cex.main = 0.8)
legend("topright",leg = "ACF - random residuals",cex = 0.5,lty = 1, col = "black",horiz = T)
#Figure 1.5. Correlogram of calssical regression residuals
residuals <- residuals(fit)
Acf(c(residuals), 15,main = "", ylab = "")
title(main="Figure 1.5. Correlogram of calssical regression residuals",
cex.main=0.8)
legend("topright",leg = "ACF - regression residuals",cex = 0.5,lty = 1, col = "black",horiz = T)
#CHAPTER 2: The local level model####
#2.1 Deterministic level####
#Removing all objects except functions
rm(list = setdiff(ls(), lsf.str()))
#Loading data
dataUKdriversKSI <- log(read.table("UKdriversKSI.txt")) %>% ts(start = 1969,frequency = 12)
#Defining model
model <- SSModel(dataUKdriversKSI ~ SSMtrend(degree = 1, Q = list(matrix(0))), H = matrix(NA))
ownupdatefn <- function(pars,model){
model$H[,,1] <- exp(pars[1])
model
}
d <- q <- 1 #Number of diffuse initial values in the state
w <- 1 #Number of estimated hyperparameters (i.e. disturbance variances)
l <- 12 #Autocorrelation at lag l to be provided by r-statistic / ACF function
k <- 15 #First k autocorrelations to be used in Q-statistic
n <- 192 #Number of observations
#Fitting model and getting output
fit <- fitSSM(model, inits = 0.001, updatefn = ownupdatefn, method = "BFGS")
outKFS <- KFS(fit$model, smoothing = c("state", "mean", "disturbance"))
#Maximum likelihood
(maxLik <- logLik(fit$model, method = "BFGS")/n)
#Akaike information criterion (AIC)
(AIC <- (-2*logLik(fit$model)+2*(w+q))/n)
#Maximum likelihood estimate of the irregular variance
(H <- fit$model$H)
#Maximum likelihood estimate of the state disturbance variance
(Q <- fit$model$Q)
#Smoothed estimates of states (level)
level <- coef(outKFS)
#Initial value of smoothed level
(coef(outKFS)[1])
#Figure 2.1. Deterministic level
plot(dataUKdriversKSI , xlab = "", ylab = "", lty = 1)
lines(level, lty = 3)
title(main = "Figure 2.1. Deterministic level", cex.main = 0.8)
legend("topright",leg = c("log UK drivers KSI", "deterministic level"),
cex = 0.5, lty = c(1, 3), horiz = T)
#Auxiliary irregular residuals (non-standardised)
irregResid <- residuals(outKFS, "pearson")
#Figure 2.2. Irregular component for deterministic level model
plot(irregResid , xlab = "", ylab = "", lty = 2)
abline(h = 0, lty = 1)
title(main = "Figure 2.2. Irregular component for deterministic level model", cex.main = 0.8)
legend("topright",leg = "irregular",cex = 0.5, lty = 2, horiz = T)
#Diagnostic for one-step-ahead prediction residuals (standardised)
predResid <- rstandard(outKFS)
qStat <- qStatistic(predResid, k, w)
rStat <- rStatistic(predResid, d, l)
hStat <- hStatistic(predResid, d)
nStat <- nStatistic(predResid, d)
#Table 2.1. Diagnostic tests for deterministic level model and log UK drivers KSI
title = "Table 2.1. Diagnostic tests for deterministic level model and log UK drivers \nKSI"
dTable(qStat, rStat, hStat, nStat, title)
#2.2 Stochastic level####
#Removing all objects except functions
rm(list = setdiff(ls(), lsf.str()))
#Loading data
dataUKdriversKSI <- log(read.table("UKdriversKSI.txt")) %>% ts(start = 1969,frequency = 12)
#Defining model
model <- SSModel(dataUKdriversKSI ~ SSMtrend(degree = 1, Q = list(matrix(NA))), H = matrix(NA))
ownupdatefn <- function(pars,model){
model$H[,, 1] <- exp(pars[1])
model$Q[,, 1] <- exp(pars[2])
model
}
d <- q <- 1 #Number of diffuse initial values in the state
w <- 2#Number of estimated hyperparameters (i.e. disturbance variances)
l <- 12 #Autocorrelation at lag l to be provided by r-statistic / ACF function
k <- 15#First k autocorrelations to be used in Q-statistic
n <- 192 #Number of observations
#Fitting model and getting ouput
fit <- fitSSM(model, inits = log(c(0.001, 0.001)), updatefn = ownupdatefn, method = "BFGS")
outKFS <- KFS(fit$model, smoothing = c("state", "mean", "disturbance"))
#Maximum likelihood
(maxLik <- logLik(fit$model, method = "BFGS")/n)
#Akaike information criterion (AIC)
(AIC <- (-2*logLik(fit$model)+2*(w+q))/n)
#Maximum likelihood estimate of the irregular variance
(H <- fit$model$H)
#Maximum likelihood estimate of the state disturbance variance
(Q <- fit$model$Q)
#Smoothed estimates of states (level)
level <- coef(outKFS)
#Initial value of level
(initLevel <- level[1])
#Figure 2.3. Stochastic level
plot(dataUKdriversKSI , xlab = "", ylab = "", lty = 1)
lines(level, lty = 3)
title(main = "Figure 2.3. Stochastic level", cex.main = 0.8)
legend("topright",leg = c("log UK drivers KSI", "stochastic level"),
cex = 0.5, lty = c(1, 3), horiz = T)
#Auxiliary irregular residuals (non-standardised)
irregResid <- residuals(outKFS, "pearson")
#Figure 2.4. Irregular component for local level model
plot(irregResid , xlab = "", ylab = "", lty = 2)
abline(h = 0, lty = 1)
title(main = "Figure 2.4. Irregular component for local level model", cex.main = 0.8)
legend("topright",leg = "irregular",cex = 0.5, lty = 2, horiz = T)
#Diagnostic for one-step-ahead prediction residuals (standardised)
predResid <- rstandard(outKFS)
qStat <- qStatistic(predResid, k, w)
rStat <- rStatistic(predResid, d, l)
hStat <- hStatistic(predResid, d)
nStat <- nStatistic(predResid, d)
#Table 2.2. Diagnostic tests for local level model and log UK drivers KSI
title = "Table 2.2. Diagnostic tests for local level model and log UK drivers KSI"
dTable(qStat, rStat, hStat, nStat, title)
#2.3 The local level model and Norwegian fatalities####
#Removing all objects except functions
rm(list = setdiff(ls(), lsf.str()))
#Loading data
dataNOfatalities <- log(read.table("NorwayFinland.txt")[,2]) %>% ts(start = 1970, frequency = 1)
#Defining model
model <- SSModel(dataNOfatalities ~ SSMtrend(degree = 1, Q = list(matrix(NA))), H = matrix(NA))
ownupdatefn <- function(pars,model){
model$H[,,1] <- exp(pars[1])
model$Q[,,1] <- exp(pars[2])
model
}
d <- q <- 1 #Number of diffuse initial values in the state
w <- 2#Number of estimated hyperparameters (i.e. disturbance variances)
l <- 4 #Autocorrelation at lag l to be provided by r-statistic / ACF function
k <- 10#First k autocorrelations to be used in Q-statistic
n <- 34 #Number of observations
#Fitting model and getting output
fit <- fitSSM(model, inits = log(c(0.001,0.001)), updatefn = ownupdatefn, method = "BFGS")
outKFS <- KFS(fit$model, smoothing = c("state", "mean", "disturbance"))
#Maximum likelihood
(maxLik <- logLik(fit$model, method = "BFGS")/n)
#Akaike information criterion (AIC)
(AIC <- (-2*logLik(fit$model)+2*(w+q))/n)
#Maximum likelihood estimate of the irregular variance
(H <- fit$model$H)
#Maximum likelihood estimate of the state disturbance variance
(Q <- fit$model$Q)
#Smoothed estimates of states (level)
level <- coef(outKFS)
#Initial value of level
(initLevel <- level[1])
#Figure 2.5. Stochastic level for Norwegian fatalities
plot(dataNOfatalities, xlab = "", ylab = "", lty = 1)
lines(level, lty = 3)
title(main = "Figure 2.5. Stochastic level for Norwegian fatalities", cex.main = 0.8)
legend("topright",leg = c("log fatalities in Norway", "stochastic level"),
cex = 0.5, lty = c(1, 3), horiz = T)
#Auxiliary irregular residuals (non-standardised)
irregResid <- residuals(outKFS, "pearson")
#Figure 2.6. Irregular component for Norwegian fatalities
plot(irregResid , xlab = "", ylab = "", lty = 2)
abline(h = 0, lty = 1)
title(main = "Figure 2.6. Irregular component for Norwegian fatalities", cex.main = 0.8)
legend("topleft",leg = "irregular",cex = 0.5, lty = 2, horiz = T)
#Diagnostic for one-step-ahead prediction residuals (standardised)
predResid <- rstandard(outKFS)
qStat <- qStatistic(predResid, k, w)
rStat <- rStatistic(predResid, d, l)
hStat <- hStatistic(predResid, d)
nStat <- nStatistic(predResid, d)
#Table 2.3. Diagnostic tests for local level model and log Norwegian fatalities
title = "Table 2.3. Diagnostic tests for local level model and log Norwegian \nfatalities"
dTable(qStat, rStat, hStat, nStat, title)
#Chapter 3: The local linear trend model####
#3.1 Deterministic level and slope####
#Removing all objects except functions
rm(list = setdiff(ls(), lsf.str()))
#Loading data
dataUKdriversKSI <- log(read.table("UKdriversKSI.txt")) %>% ts(start = 1969, frequency = 12)
#Defining model
model <- SSModel(dataUKdriversKSI ~ SSMtrend(degree = 2, Q = list(matrix(0), matrix(0))), H = matrix(NA))
d <- q <- 2 #Number of diffuse initial values in the state
w <- 1#Number of estimated hyperparameters (i.e. disturbance variances)
l <- 12 #Autocorrelation at lag l to be provided by r-statistic / ACF function
k <- 15#First k autocorrelations to be used in Q-statistic
n <- 192 #Number of observations
#Fitting model and getting output
fit <- fitSSM(model, inits = log(0.001), method = "BFGS")
outKFS <- KFS(fit$model, smoothing = c("state", "mean", "disturbance"))
outKFS$model$Q
#Maximum likelihood
(maxLik <- logLik(fit$model)/n)
#Akaike information criterion (AIC)
(AIC <- (-2*logLik(fit$model)+2*(w+q))/n)
#Maximum likelihood estimate of the irregular variance
(H <- fit$model$H)
#Maximum likelihood estimate of the state disturbance variance
(Q <- fit$model$Q)
#Smoothed estimates of states
smoothEstStat <- coef(outKFS)
#Initial values of the smoothed estimates of states
(initSmoothEstStat <- smoothEstStat[1,])
#Diagnostic for one-step-ahead prediction residuals (standardised)
predResid <- rstandard(outKFS)
qStat <- qStatistic(predResid, k, w)
rStat <- rStatistic(predResid, d, l)
hStat <- hStatistic(predResid, d)
nStat <- nStatistic(predResid, d)
#Table 3.1 Diagnostic tests for deterministic linear trend model and log UK drivers KSI
title = "Table 3.1 Diagnostic tests for deterministic linear trend model and log UK \ndrivers KSI"
dTable(qStat, rStat, hStat, nStat, title)
#3.2 Stochastic level and slope####
#Removing all objects except functions
rm(list = setdiff(ls(), lsf.str()))
#Loading data
dataUKdriversKSI <- log(read.table("UKdriversKSI.txt")) %>% ts(start = 1969, frequency = 12)
#Defining model
model <- SSModel(dataUKdriversKSI ~ SSMtrend(degree = 2, Q = list(matrix(NA), matrix(NA))), H = matrix(NA))
ownupdatefn <- function(pars, model){
model$H[,,1] <- exp(pars[1])
diag(model$Q[,,1]) <- exp(pars[2:3])
model
}
d <- q <- 2 #Number of diffuse initial values in the state
w <- 3#Number of estimated hyperparameters (i.e. disturbance variances)
l <- 12 #Autocorrelation at lag l to be provided by r-statistic / ACF function
k <- 15#First k autocorrelations to be used in Q-statistic
n <- 192 #Number of observations
#Fitting model
fit <- fitSSM(model, inits = log(c(0.001, 0001, 0001)) ,method = "BFGS")
outKFS <- KFS(fit$model, smoothing = c("state", "mean", "disturbance"))
#Maximum likelihood
(maxLik <- logLik(fit$model)/n)
#Akaike information criterion (AIC)
(AIC <- (-2*logLik(fit$model)+2*(w+q))/n)
#Maximum likelihood estimate of the irregular variance
(H <- fit$model$H)
#Maximum likelihood estimate of the state disturbance variance
(Q <- fit$model$Q)
#Smoothed estimates of states
smoothEstStat <- coef(outKFS)
#Initial values of the smoothed estimates of states
(initSmoothEstStat <- smoothEstStat[1,])
# Trend (stochastic level + slope)
trend <-signal(outKFS, states = "trend")$signal
#Figure 3.1. Trend of stochastic linear trend model
plot(dataUKdriversKSI , xlab = "", ylab = "", lty = 1)
lines(trend, lty = 3)
title(main = "Figure 3.1. Trend of stochastic linear trend model", cex.main = 0.8)
legend("topright",leg = c("log UK drivers KSI", "stochastic level and slope"),
cex = 0.5, lty = c(1, 3), horiz = T)
#Figure 3.2. Slope of stochastic linear trend model
plot(smoothEstStat[, "slope"], xlab = "", ylab = "", lty = 1)
title(main = "Figure 3.2. Slope of stochastic linear trend model", cex.main = 0.8)
legend("topleft",leg = "stochastic slope",
cex = 0.5, lty = 1, horiz = T)
#Auxiliary irregular residuals (non-standardised)
irregResid <- residuals(outKFS, "pearson")
#Figure 3.3. Irregular component of stochastic trend model
plot(irregResid , xlab = "", ylab = "", lty = 2)
abline(h = 0, lty = 1)
title(main = "Figure 3.3. Irregular component of stochastic trend model", cex.main = 0.8)
legend("topright",leg = "irregular",cex = 0.5, lty = 2, horiz = T)
#Diagnostic for one-step-ahead prediction residuals (standardised)
predResid <- rstandard(outKFS)
qStat <- qStatistic(predResid, k, w)
rStat <- rStatistic(predResid, d, l)
hStat <- hStatistic(predResid, d)
nStat <- nStatistic(predResid, d)
#Table 3.2 Diagnostic tests for the local linear trend model applied
#to the log of the UK drivers KSI
title = "Table 3.2 Diagnostic tests for the local linear trend model applied to \nthe log of the UK drivers KSI"
dTable(qStat, rStat, hStat, nStat, title)
#3.3 Stochastic level and deterministic slope####
#Removing all objects except functions
rm(list = setdiff(ls(), lsf.str()))
#Loading data
dataUKdriversKSI <- log(read.table("UKdriversKSI.txt")) %>% ts(start = 1969, frequency = 12)
#Defining model
model <- SSModel(dataUKdriversKSI ~ SSMtrend(degree = 2, Q = list(matrix(NA), matrix(0))), H = matrix(NA))
ownupdatefn <- function(pars, model){
model$H[,,1] <- exp(pars[1])
diag(model$Q[,,1]) <- c(exp(pars[2]), 0)
model
}
d <- q <- 2 #Number of diffuse initial values in the state
w <- 2#Number of estimated hyperparameters (i.e. disturbance variances)
l <- 12 #Autocorrelation at lag l to be provided by r-statistic / ACF function
k <- 15#First k autocorrelations to be used in Q-statistic
n <- 192 #Number of observations
#Fitting model and getting output
fit <- fitSSM(model, inits = log(c(0.001, 0.001)), updatefn = ownupdatefn, method = "BFGS")
outKFS <- KFS(fit$model, smoothing = c("state", "mean", "disturbance"))
#Maximum likelihood
(maxLik <- logLik(fit$model)/n)
#Akaike information criterion (AIC)
(AIC <- (-2*logLik(fit$model)+2*(w+q))/n)
#Maximum likelihood estimate of the irregular variance
(H <- fit$model$H)
#Maximum likelihood estimate of the state disturbance variance
(Q <- fit$model$Q)
#Smoothed estimates of states
smoothEstStat <- outKFS$alphahat
#Initial values of the smoothed estimates of states
(initSmoothEstStat <- smoothEstStat[1,])
# Trend (stochastic level + slope)
trend <-signal(outKFS, states = "trend")$signal
#Figure 3.4. Trend of stochastic level and deterministic slope model
plot(dataUKdriversKSI, xlab = "", ylab = "", lty = 1)
lines(trend, lty = 3)
title(main = "Figure 3.4. Trend of stochastic level and deterministic slope model", cex.main = 0.8)
legend("topright",leg = c("log UK drivers KSI", "stochastic level and deterministic slope"),
cex = 0.5, lty = c(1, 3), horiz = T)
#3.4 The local linear trend model and Finnish fatalities####
#A) Both the level and the slope component vary####
#Removing all objects except functions
rm(list = setdiff(ls(), lsf.str()))
#Loading data
dataFIfatalities <- log(read.table("NorwayFinland.txt")[,3]) %>% ts(start = 1970, frequency = 1)
#Defining model
model <- SSModel(dataFIfatalities ~ SSMtrend(degree = 2, Q = list(matrix(NA), matrix(NA))), H = matrix(NA))
ownupdatefn <- function(pars, model){
model$H[,,1] <- exp(pars[1])
diag(model$Q[,,1]) <- exp(pars[2:3])
model
}
d <- q <- 2 #Number of diffuse initial values in the state
w <- 3#Number of estimated hyperparameters (i.e. disturbance variances)
l <- 4 #Autocorrelation at lag l to be provided by r-statistic / ACF function
k <- 10#First k autocorrelations to be used in Q-statistic
n <- 34 #Number of observations
#Fitting model and getting output
#x <- initValOpt()
fit <- fitSSM(model, inits = log(c(0.021, 0.021, 0.021)), updatefn = ownupdatefn, method = "Nelder-Mead")
outKFS <- KFS(fit$model, smoothing = c("state", "mean", "disturbance"))
#Maximum likelihood
(maxLik <- logLik(fit$model)/n)
#Akaike information criterion (AIC)
(AIC <- (-2*logLik(fit$model)+2*(w+q))/n)
#Maximum likelihood estimate of the irregular variance
(H <- fit$model$H)
#Maximum likelihood estimate of the state disturbance variance
(Q <- fit$model$Q)
#Smoothed estimates of states
smoothEstStat <- outKFS$alphahat
#Initial values of the smoothed estimates of states
(initSmoothEstStat <- smoothEstStat[1,])
#B) Deterministic level and stochastic slope####
#Removing all objects except functions
rm(list = setdiff(ls(), lsf.str()))
#Loading data
dataFIfatalities <- log(read.table("NorwayFinland.txt")[,3]) %>% ts(start = 1970, frequency = 1)
#Defining model
model <- SSModel(dataFIfatalities ~ SSMtrend(degree = 2, Q = list(matrix(0), matrix(NA))), H = matrix(NA))
ownupdatefn <- function(pars, model){
model$H[,,1] <- exp(pars[1])
diag(model$Q[,,1]) <- c(0, exp(pars[2]))
model
}
d <- q <- 2 #Number of diffuse initial values in the state
w <- 2#Number of estimated hyperparameters (i.e. disturbance variances)
l <- 4 #Autocorrelation at lag l to be provided by r-statistic / ACF function
k <- 10#First k autocorrelations to be used in Q-statistic
n <- 34 #Number of observations
#Fitting model and getting output
#x <- initValOpt()
fit <- fitSSM(model, inits = log(c(0.059, 0.059)), updatefn = ownupdatefn, method = "L-BFGS-B")
outKFS <- KFS(fit$model, smoothing = c("state", "mean", "disturbance"))
#Maximum likelihood
(maxLik <- logLik(fit$model)/n)
#Akaike information criterion (AIC)
(AIC <- (-2*logLik(fit$model)+2*(w+q))/n)
#Maximum likelihood estimate of the irregular variance
(H <- fit$model$H)
#Maximum likelihood estimate of the state disturbance variance
(Q <- fit$model$Q)
#Smoothed estimates of states
smoothEstStat <- outKFS$alphahat
#Initial values of the smoothed estimates of states
(initSmoothEstStat <- smoothEstStat[1,])
# Trend (stochastic level + slope)
trend <-signal(outKFS, states = "trend")$signal
#Figure 3.5. Trend of deterministic level and stochastic slope model
# for Finnish fatalities (top) and stochastic slope component (bottom) linear trend model
par(mfrow = c(2, 1), mar = c(1.5, 4, 4, 4))
plot(dataFIfatalities, xlab = "", ylab = "", lty = 1)
lines(trend, lty = 3)
title(main = "Figure 3.5. Trend of deterministic level and stochastic slope model
for Finnish fatalities (top) and stochastic slope component (bottom) linear trend model",
cex.main = 0.8)
legend("topright",leg = c("log fatalities Finland", "deterministic level, stochastic slope"),
cex = 0.5, lty = c(1, 3), horiz = T)
par(mar = c(4, 4, 1.5, 4))
plot(smoothEstStat[, "slope"], xlab = "", ylab = "", lty = 3)
abline(h = 0, lty = 1)
legend("topright",leg = "stochastic slope", cex = 0.5, lty = 1, horiz = T)
par(mfrow=c(1, 1))
#Auxiliary irregular residuals (non-standardised)
irregResid <- residuals(outKFS, "pearson")
#Figure 3.6. Irregular component for Finish fatalities
par(mfrow = c(1, 1), mar = c(4, 4, 4, 4))
plot(irregResid , xlab = "", ylab = "", lty = 2)
abline(h = 0, lty = 1)
title(main = "Figure 3.6. Irregular component for Finish fatalities", cex.main = 0.8)
legend("topright",leg = "irregular",cex = 0.5, lty = 2, horiz = T)
#Diagnostic for one-step-ahead prediction residuals (standardised)
predResid <- rstandard(outKFS)
qStat <- qStatistic(predResid, k, w)
rStat <- rStatistic(predResid, d, l)
hStat <- hStatistic(predResid, d)
nStat <- nStatistic(predResid, d)
#Table 3.3. Diagnostic tests for deterministic level and stochastic slope
#model, and log Finnish fatalities
title = "Table 3.3. Diagnostic tests for deterministic level and stochastic slope \nmodel, and log Finnish fatalities"
dTable(qStat, rStat, hStat, nStat, title)
#CHAPTER 4: Local level model with seasonal####
#4.1 Deterministic level and seasonal####
#Removing all objects except functions
rm(list = setdiff(ls(), lsf.str()))
#Loading data
dataUKdriversKSI <- log(read.table("UKdriversKSI.txt")) %>% ts(start = 1969, frequency=12)
#Figure 4.1. Log of the number of UK drivers KSI with time lines for years
plot(dataUKdriversKSI, ylab = "",xlab = "")
abline(v=seq(1969, 1985, 1), lty = 3)
title(main = "Figure 4.1. Log of the number of UK drivers KSI with time lines for years",
cex.main = 0.8)
legend("topright", leg = "log UK drivers KSI",cex = 0.5, lty = 1, horiz = T)
#Defining model
model <- SSModel(dataUKdriversKSI ~ SSMtrend(1, Q=0) + SSMseasonal(12, sea.type='dummy', Q = 0), H=NA)
ownupdatefn <- function(pars, model){
model$H[,,1] <- exp(pars[1])
model
}
d <- q <- 12 #Number of diffuse initial values in the state
w <- 1 #Number of estimated hyperparameters (i.e. disturbance variances)
l <- 12 #Autocorrelation at lag l to be provided by r-statistic / ACF function
k <- 15#First k autocorrelations to be used in Q-statistic
n <- 192 #Number of observations
#Fitting model and getting output
#x <- initValOpt(method = "BFGS")
fit <- fitSSM(inits = log(0.006), model = model, updatefn = ownupdatefn, method = "BFGS")
outKFS <- KFS(fit$model, smoothing = c("state", "mean", "disturbance"))
outKFS$model$Q
#Maximum likelihood
(maxLik <- logLik(fit$model, method = "Nelder-Mead")/n)
#Akaike information criterion (AIC)
(AIC <- (-2*logLik(fit$model)+2*(w+q))/n)
#Maximum likelihood estimate of the irregular variance
(H <- fit$model$H)
#Maximum likelihood estimate of the state disturbance variance
(Q <- fit$model$Q)
#Smoothed estimates of states (level and seasonal components)
smoothEstStat <- coef(outKFS)
#Initial values of the smoothed estimates of states
(initSmoothEstStat <- smoothEstStat[1,])
# Combined level and seasonal
levSeas <-signal(outKFS, states = "all")$signal
#Level
level <- signal(outKFS, states = "level")$signal
#Seasonal
seasonal <- signal(outKFS, states = "seasonal")$signal
#Figure 4.2. Combined deterministic level and seasonal
plot(dataUKdriversKSI, xlab = "", ylab = "", lty = 1)
lines(levSeas, lty = 3)
title(main = "Figure 4.2. Combined deterministic level and seasonal", cex.main = 0.8)
legend("topright",leg = c("log UK drivers KSI", "deterministic level + seasonal"),
cex = 0.5, lty = c(1, 3), horiz = T)
#Figure 4.3. Deterministic level
plot(dataUKdriversKSI, xlab = "", ylab = "", lty = 1)
lines(level, lty = 3)
title(main = "Figure 4.3. Deterministic level", cex.main = 0.8)
legend("topright",leg = c("log UK drivers KSI", "deterministic level"),
cex = 0.5, lty = c(1, 3), horiz = T)
#Figure 4.4. Deterministic seasonal
plot(seasonal, xlab = "", ylab = "", lty = 1)
abline(h = 0, lty = 3)
title(main = "Figure 4.4. Deterministic seasonal", cex.main = 0.8)
legend("topleft",leg = "deterministic seasonal",
cex = 0.5, lty = 1, horiz = T)
#Auxiliary irregular residuals (non-standardised)
irregResid <- residuals(outKFS, "pearson")
#Figure 4.5. Irregular component for deterministic level and seasonal model
plot(irregResid , xlab = "", ylab = "", lty = 2)
abline(h = 0, lty = 1)
title(main = "Figure 4.5. Irregular component for deterministic level and seasonal model", cex.main = 0.8)
legend("topright",leg = "irregular",cex = 0.5, lty = 2, horiz = T)
#Diagnostic for one-step-ahead prediction residuals (standardised)
predResid <- rstandard(outKFS)
qStat <- qStatistic(predResid, k, w)
rStat <- rStatistic(predResid, d, l)
hStat <- hStatistic(predResid, d)
nStat <- nStatistic(predResid, d)
#Table 4.1. Diagnostic tests for deterministic level and seasonal
#model and log UK drivers KSI
title = "Table 4.1. Diagnostic tests for deterministic level and seasonal model \nand log UK drivers KSI"
dTable(qStat, rStat, hStat, nStat, title)
#4.2 Stochastic level and seasonal####
#Removing all objects except functions
rm(list = setdiff(ls(), lsf.str()))
#Loading data
dataUKdriversKSI <- log(read.table("UKdriversKSI.txt")) %>% ts(start = 1969, frequency = 12)
#Defining model
model <- SSModel(dataUKdriversKSI ~ SSMtrend(1, Q = NA) + SSMseasonal(12, sea.type = 'dummy', Q = NA), H = NA)
ownupdatefn <- function(pars,model){
model$H[,,1] <- exp(pars[1])
diag(model$Q[,,1]) <- exp(c(pars[2], pars[3]))
model
}
d <- q <- 12 #Number of diffuse initial values in the state
w <- 3 #Number of estimated hyperparameters (i.e. disturbance variances)
l <- 12 #Autocorrelation at lag l to be provided by r-statistic / ACF function
k <- 15#First k autocorrelations to be used in Q-statistic
n <- 192 #Number of observations
#Fitting model
#x <- initValOpt() #Finding best initial values for optim
fit <- fitSSM(inits = log(rep(0.011, w)), model = model, updatefn = ownupdatefn, method = "Nelder-Mead")
outKFS <- KFS(fit$model, smoothing = c("state", "mean", "disturbance"))
#Maximum likelihood
(maxLik <- logLik(fit$model, method = method)/n)
#Akaike information criterion (AIC)
(AIC <- (-2*logLik(fit$model)+2*(w+q))/n)
#Maximum likelihood estimate of the irregular variance
(H <- fit$model$H)
#Maximum likelihood estimate of the state disturbance variance
(Q <- fit$model$Q)
#Smoothed estimates of states (level and seasonal components)
smoothEstStat <- coef(outKFS)
#Initial values of the smoothed estimates of states
(initSmoothEstStat <- smoothEstStat[1,])
# Combined level and seasonal
levSeas <-signal(outKFS, states = "all")$signal
#Level
level <- signal(outKFS, states = "level")$signal
#Seasonal
seasonal <- signal(outKFS, states = "seasonal")$signal
#Figure 4.6. Stochastic level
plot(dataUKdriversKSI, xlab = "", ylab = "", lty = 1)
lines(level, lty = 3)
title(main = "Figure 4.6. Stochastic level", cex.main = 0.8)
legend("topright",leg = c("log UK drivers KSI", "stochastic level"),
cex = 0.5, lty = c(1, 3), horiz = T)
#Figure 4.7. Stochastic seasonal
plot(seasonal, xlab = "", ylab = "", lty = 1)
abline(h = 0, lty = 3)
title(main = "Figure 4.4. Stochastic seasonal", cex.main = 0.8)
legend("topleft",leg = "stochastic seasonal",
cex = 0.5, lty = 1, horiz = T)
#Figure 4.8. Stochastic seasonal for the year 1969
plot(window(seasonal, start = c( 1969, 1), end = c( 1969, 12)), xlab = "", ylab = "", lty = 1, xaxt = "n")
axis(1, seq(1969, 1970-1/12, length.out = 12), c("1969-Jan", "", "", "1969-Apr", "", "", "1969-July", "", "", "1969-Oct", "", ""))
abline(h = 0, lty = 3)
title(main = "Figure 4.8. Stochastic seasonal for the year 1969", cex.main = 0.8)
legend("topleft",leg = "stochastic seasonal",
cex = 0.5, lty = 1, horiz = T)
#Auxiliary irregular residuals (non-standardised)
irregResid <- residuals(outKFS, "pearson")
#Figure 4.9. Irregular component for stochastic level and seasonal model
plot(irregResid , xlab = "", ylab = "", lty = 2)
abline(h = 0, lty = 1)
title(main = "Figure 4.9. Irregular component for stochastic level and seasonal model",
cex.main = 0.8)
legend("topright",leg = "irregular",cex = 0.5, lty = 2, horiz = T)
#Diagnostic for one-step-ahead prediction residuals (standardised)
predResid <- rstandard(outKFS)
qStat <- qStatistic(predResid, k, w)
rStat <- rStatistic(predResid, d, l)
hStat <- hStatistic(predResid, d)
nStat <- nStatistic(predResid, d)
#Table 4.2. Diagnostic tests for stochastic level and seasonal
#model and log UK drivers KSI
title = "Table 4.2. Diagnostic tests for stochastic level and seasonal model \nand log UK drivers KSI"
dTable(qStat, rStat, hStat, nStat, title)