-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathREADME
More file actions
453 lines (386 loc) · 13.7 KB
/
Copy pathREADME
File metadata and controls
453 lines (386 loc) · 13.7 KB
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
library(zoo)
library(tseries)
library(lmtest)
library(forecast)
library(ggplot2)
library(patchwork)
# Correction Q1 à 3 disponible https://github.com/AQLT/TP_Ensae2A/wiki
##########################
####### Question 1 #######
##########################
data <-read.csv("Data/data_tp5.csv",sep = ";")
data$dates[1]
spread <- ts(data$spread, start = c(1986, 3), frequency = 12)
dspread <- diff(spread,1) # difference premiere
##########################
####### Question 2 #######
##########################
plot(cbind(spread,dspread))
# La série en niveau semble avoir une tendance déterministe (ou deux tendances)
# La série différenciée pourrait être stationnaire
##########################
####### Question 3 #######
##########################
# rmq : tester la présence d'une tendance par régression n'a pas de sens
# car si on a une racine unitaire on est dans le cas d'une spurious régression
y = cumsum(rnorm(n=100))
summary(lm(y ~ seq_along(y)))
library(urca)
library(fUnitRoots)
# Ici on teste la présence de racine unitaire
# adf invalid si on ne rajoute pas de variable explicative
# dans le doute c'est toujours mieux de rajouter la tendance et constante
adf <- adfTest(spread, type = "ct",lags = 0)
Qtests <- function(series, k = 24, fitdf=0) {
t(sapply(1:k,function(l){
if(l <= fitdf){
b <- list(statistic = NA, p.value = NA)
}else{
b <- Box.test(series,"Ljung-Box",lag = l,
fitdf = fitdf
)
}
data.frame(lag = l,
b$statistic,
b$p.value
)
}))
}
adfTest_valid <- function(series,kmax,type){
k <- 0
# On test ADF jusqu'à ce que les résidus ne soient pas autocorrélés
noautocorr <- 0
while (noautocorr==0){
cat(paste0("ADF with ",k, " lags: residuals OK? "))
adf <- adfTest(series,lags=k,type=type)
pvals <- Qtests(adf@test$lm$residuals,
24,
fitdf=length(adf@test$lm$coefficients))[,3]
if (sum(pvals<0.05,na.rm=T) == 0) {
noautocorr <- 1; cat("OK \n")
}else {
cat("nope \n")
}
k <- k + 1
}
return(adf)
}
# On ne fait que le test à l'ordre 24
adfTest_valid2 <- function(series,kmax,type){
k <- 0
# On test ADF jusqu'à ce que les résidus ne soient pas autocorrélés
noautocorr <- 0
while (noautocorr==0){
cat(paste0("ADF with ",k, " lags: residuals OK? "))
adf <- adfTest(series,lags=k,type=type)
pvals <- Qtests(adf@test$lm$residuals,
24,
fitdf=length(adf@test$lm$coefficients))[,3]
if (sum(pvals[24]<0.05,na.rm=T) == 0) {
noautocorr <- 1; cat("OK \n")
}else {
cat("nope \n")
}
k <- k + 1
}
return(adf)
}
df1 <- adfTest_valid(spread,24,"ct")
df2 <- adfTest_valid2(spread,24,"ct")
# On teste ici le modèle
# ∆y_t = a + bt + γ y_t-1 +e_t
# tau3 correspond au test γ = 0
# phi2 correspond au test a = b = γ = 0
# phi3 correspond au test b = γ = 0
# voir https://new.mmf.lnu.edu.ua/wp-content/uploads/2018/03/enders_applied_econometric_time_series.pdf
summary(
urca::ur.df(spread, type = "trend",lags = 12,
selectlags = "AIC")
) # 5 lags retenus par AIC
# Dans tous cas on ne rejette pas H0 (mais a priori pas de tendance linéaire)
# PP n'a pas besoin de beaucoup d'hypothèses parce que la stat calculée
# sur beta est construite de façon non paramétrique et qui corrige
# toute forme d'autocorrélation. Mais pas très bon quand peu de données
tseries::pp.test(spread) # on rejette pas hypothèse de présence de racine unitaire
tseries::kpss.test(spread, null = "Trend") # on rejette hypothèse de stationnarité
autoplot(dspread) /
(ggAcf(dspread) + labs(title = "ACF") +
ggPacf(dspread) + labs(title = "PACF") )
autoplot(spread) /
(ggAcf(spread) + labs(title = "ACF") +
ggPacf(spread) + labs(title = "PACF") )
tseries::pp.test(dspread) # on rejette pas hypothèse de présence de racine unitaire
tseries::kpss.test(dspread, null = "Level")
df1 <- adfTest_valid(dspread,24,"c")
df2 <- adfTest_valid2(dspread,24,"c")
summary(
urca::ur.df(dspread, type = "none",lags = 12,
selectlags = "AIC")
)
##########################
####### Question 4 #######
##########################
autoplot(dspread) /
(ggAcf(dspread) + labs(title = "ACF") +
ggPacf(dspread) + labs(title = "PACF") )
##########################
####### Question 5 #######
##########################
models_possibles <- expand.grid(p = c(0,1,2,3), d = 1, q = c(0, 1, 2, 3))
evaluation_model <- function(order, x = spread){
# ici on utilise Arima plutôt que arima pour la fonction accuracy
model <- forecast::Arima(x, order = order,include.constant = FALSE)
qualite <- c(AIC(model), BIC(model), accuracy(model))
names(qualite) <- c("AIC", "BIC", colnames(accuracy(model)))
qualite
}
all_models <- data.frame(t(apply(models_possibles,1,evaluation_model)))
rownames (all_models) <- sprintf("ARIMA(%i,%i,%i)", models_possibles[,"p"],
models_possibles[,"d"], models_possibles[,"q"])
all_models
rownames(all_models)[which.min(all_models$AIC)]
rownames(all_models)[which.min(all_models$BIC)]
rownames(all_models)[which.min(all_models$RMSE)]
apply(all_models,2,function(x) rownames(all_models)[which.min(x)])
##########################
####### Question 6 #######
##########################
# On peut retenir les deux modèles qui minimises AIC et BIC
# Rmq : le modèle retenu par auto.arima est un ARIMA(2,1,2) qui ne minimise pas l'AIC
auto.arima(spread,max.D = 0, max.P = 0, max.Q = 0)
arima310 <- arima(spread,c(3,1,0),include.mean=FALSE)
arima011 <- arima(spread,c(0,1,1),include.mean=FALSE)
lmtest::coeftest(
arima310
) # modèle bien ajusté coef AR(3) significatif
lmtest::coeftest(
arima011
) # modèle bien ajusté coef MA(1) significatif
##########################
####### Question 7 #######
##########################
Qtests(residuals(
arima310
),
fitdf = 3)
Qtests(residuals(
arima011
),
fitdf = 3)
##########################
####### Question 9 #######
##########################
(autoplot(residuals(arima310)) +
geom_vline(xintercept = 2001+11/12,linetype="dashed",
col = "red", alpha = 0.7) +
labs(title = "ARIMA(3,1,0)")) /
(autoplot(residuals(arima011)) +
geom_vline(xintercept = 2001+11/12,linetype="dashed",
col = "red", alpha = 0.7)+
labs(title = "ARIMA(0,1,1)"))
# Il y a vraisemblablement un point atypique
arima310_ind <- arima(spread,c(3,1,0),include.mean=FALSE,xreg = time(spread) == 2001+11/12)
arima011_ind <- arima(spread,c(0,1,1),include.mean=FALSE,xreg = time(spread) == 2001+11/12)
# L'indicatrice est significative
lmtest::coeftest(
arima310_ind
) # modèle bien ajusté coef AR(3) significatif
lmtest::coeftest(
arima011_ind
)
(autoplot(residuals(arima310_ind)) +
geom_vline(xintercept = 2001+11/12,linetype="dashed",
col = "red", alpha = 0.7) +
labs(title = "ARIMA(3,1,0)")) /
(autoplot(residuals(arima011_ind)) +
geom_vline(xintercept = 2001+11/12,linetype="dashed",
col = "red", alpha = 0.7)+
labs(title = "ARIMA(0,1,1)"))
##########################
####### Question 10 #######
##########################
# On peut faire un test de chow
# Voir https://cran.r-project.org/web/packages/strucchange/vignettes/strucchange-intro.pdf
# Voir également https://robjhyndman.com/hyndsight/structural-breaks/
# Code à vérifier
test_rupture <- function(order, date_break = 1995){
glob_mod = arima(spread,
order = order, include.mean = FALSE)
rss <- sum(residuals(glob_mod)^2)
sigma2 <- glob_mod$sigma2
k <- length(coef(glob_mod))
n <- length(spread) - order[2]
fit1 <- arima(window(spread, end = date_break),
order = order, include.mean = FALSE)
fit2 <- arima(window(spread, start = date_break+1/12),
order = order, include.mean = FALSE)
ess <- sum(c(residuals(fit1), residuals(fit2))^2)
stats <- (rss - ess)/(n-2*k)
stats <- stats/k
c(stats = stats,
qf = qf(0.05, df1 = k, df2 = n-2*k, lower.tail = FALSE),
pval = 1- pf(stats, df1 = k, df2 = n-2*k)
)
}
round(test_rupture(order = c(0,1,1),date_break = 2001+11/12), 3)
round(test_rupture(order = c(3,1,0),date_break = 2001+11/12), 3)
#############################
####### TP avec fable #######
#############################
library(fable)
library(lubridate)
library(dplyr)
library(feasts)
library(ggplot2)
fable_mod = lapply(sprintf("(value) ~ 0 + pdq(%i,%i,%i) + PDQ(0,0,0) ", models_possibles[,"p"],
models_possibles[,"d"], models_possibles[,"q"]), as.formula)
fable_mod = lapply(fable_mod, ARIMA)
names(fable_mod) <- rownames (all_models)
spread_ts = spread %>%
as_tsibble()
all_mod = do.call(function (...) model(spread_ts, ...), fable_mod)
all_mod %>%
report()
all_mod %>%
report() %>%
mutate(across(AIC:BIC, ~ .model[which.min(.x)])) %>%
distinct(AIC, AICc, BIC)
library(zoo)
library(tseries)
library(lmtest)
library(forecast)
library(ggplot2)
library(patchwork)
# Correction Q1 à 3 disponible https://github.com/AQLT/TP_Ensae2A/wiki
##########################
####### Question 1 #######
##########################
data <-read.csv("Data/data_tp5.csv",sep = ";")
data$dates[1]
spread <- ts(data$spread, start = c(1986, 3), frequency = 12)
dspread <- diff(spread,1) # difference premiere
##########################
####### Question 2 #######
##########################
plot(cbind(spread,dspread))
# La série en niveau semble avoir une tendance déterministe (ou deux tendances)
# La série différenciée pourrait être stationnaire
##########################
####### Question 3 #######
##########################
# rmq : tester la présence d'une tendance par régression n'a pas de sens
# car si on a une racine unitaire on est dans le cas d'une spurious régression
y = cumsum(rnorm(n=100))
summary(lm(y ~ seq_along(y)))
library(urca)
library(fUnitRoots)
# Ici on teste la présence de racine unitaire
# adf invalid si on ne rajoute pas de variable explicative
# dans le doute c'est toujours mieux de rajouter la tendance et constante
adf <- adfTest(spread, type = "ct",lags = 0)
Qtests <- function(series, k = 24, fitdf=0) {
t(sapply(1:k,function(l){
if(l <= fitdf){
b <- list(statistic = NA, p.value = NA)
}else{
b <- Box.test(series,"Ljung-Box",lag = l,
fitdf = fitdf
)
}
data.frame(lag = l,
b$statistic,
b$p.value
)
}))
}
adfTest_valid <- function(series,kmax,type){
k <- 0
# On test ADF jusqu'à ce que les résidus ne soient pas autocorrélés
noautocorr <- 0
while (noautocorr==0){
cat(paste0("ADF with ",k, " lags: residuals OK? "))
adf <- adfTest(series,lags=k,type=type)
pvals <- Qtests(adf@test$lm$residuals,
24,
fitdf=length(adf@test$lm$coefficients))[,3]
if (sum(pvals<0.05,na.rm=T) == 0) {
noautocorr <- 1; cat("OK \n")
}else {
cat("nope \n")
}
k <- k + 1
}
return(adf)
}
# On ne fait que le test à l'ordre 24
adfTest_valid2 <- function(series,kmax,type){
k <- 0
# On test ADF jusqu'à ce que les résidus ne soient pas autocorrélés
noautocorr <- 0
while (noautocorr==0){
cat(paste0("ADF with ",k, " lags: residuals OK? "))
adf <- adfTest(series,lags=k,type=type)
pvals <- Qtests(adf@test$lm$residuals,
24,
fitdf=length(adf@test$lm$coefficients))[,3]
if (sum(pvals[24]<0.05,na.rm=T) == 0) {
noautocorr <- 1; cat("OK \n")
}else {
cat("nope \n")
}
k <- k + 1
}
return(adf)
}
df1 <- adfTest_valid(spread,24,"ct")
df2 <- adfTest_valid2(spread,24,"ct")
# On teste ici le modèle
# ∆y_t = a + bt + γ y_t-1 +e_t
# tau3 correspond au test γ = 0
# phi2 correspond au test a = b = γ = 0
# phi3 correspond au test b = γ = 0
# voir https://new.mmf.lnu.edu.ua/wp-content/uploads/2018/03/enders_applied_econometric_time_series.pdf
summary(
urca::ur.df(spread, type = "trend",lags = 12,
selectlags = "AIC")
) # 5 lags retenus par AIC
# Dans tous cas on ne rejette pas H0 (mais a priori pas de tendance linéaire)
# PP n'a pas besoin de beaucoup d'hypothèses parce que la stat calculée
# sur beta est construite de façon non paramétrique et qui corrige
# toute forme d'autocorrélation. Mais pas très bon quand peu de données
tseries::pp.test(spread) # on rejette pas hypothèse de présence de racine unitaire
tseries::kpss.test(spread, null = "Trend") # on rejette hypothèse de stationnarité
autoplot(dspread) /
(ggAcf(dspread) + labs(title = "ACF") +
ggPacf(dspread) + labs(title = "PACF") )
autoplot(spread) /
(ggAcf(spread) + labs(title = "ACF") +
ggPacf(spread) + labs(title = "PACF") )
tseries::pp.test(dspread) # on rejette pas hypothèse de présence de racine unitaire
tseries::kpss.test(dspread, null = "Level")
df1 <- adfTest_valid(dspread,24,"c")
df2 <- adfTest_valid2(dspread,24,"c")
summary(
urca::ur.df(dspread, type = "none",lags = 12,
selectlags = "AIC")
)
##########################
####### Question 4 #######
##########################
autoplot(dspread) /
(ggAcf(dspread) + labs(title = "ACF") +
ggPacf(dspread) + labs(title = "PACF") )
##########################
####### Question 5 #######
##########################
models_possibles <- expand.grid(p = c(0,1,2,3), d = 1, q = c(0, 1, 2, 3))
evaluation_model <- function(order, x = spread){
# ici on utilise Arima plutôt que arima pour la fonction accuracy
model <- forecast::Arima(x, order = order,include.constant = FALSE)
qualite <- c(AIC(model), BIC(model), accuracy(model))
names(qualite) <- c("AIC", "BIC", colnames(accuracy(model)))
qualite
}
all_models <- data.frame(t(apply(models_possibles,1,evaluation_model)))
rownames (all_models) <- sprintf("ARIMA(%i,%i,%i)", models_possibles[,"p"],
models_possib