-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTemporal_hierarchies.Rmd
More file actions
101 lines (85 loc) · 1.8 KB
/
Temporal_hierarchies.Rmd
File metadata and controls
101 lines (85 loc) · 1.8 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
---
title: "Temporal hierarchies"
author: "Rizny Mubarak"
date: "2023-09-29"
output:
pdf_document:
toc: yes
toc_depth: 4
---
### 1. Data and packages
```{r}
pckg <- c("thief","MAPA","tsutils","abind")
for (i in 1:length(pckg)){
if(!(pckg[i] %in% rownames(installed.packages()))){
install.packages(pckg[i])
}
library(pckg[i],character.only = TRUE)
}
```
```{r}
y <- AirPassengers
```
### 2. Temporal hierarchies using the thief package
```{r}
frc1 <- thief(y)
plot(frc1)
```
```{r}
frc2 <- thief(y,usemodel="arima")
plot(frc2)
```
### 3. Manual implementation of THieF
```{r}
S <- tsutils::Sthief(y) # Get the S matrix
ff <- frequency(y) # Get sampling frequency of target series
AL <- ff/(1:ff) # Calculate frequencies of various aggregation levels
AL <- AL[AL %% 1 == 0] # And exclude those that would not be integer
k <- length(AL) # Find how many are left
```
```{r}
Y <- MAPA::tsaggr(y,AL)[[1]]
```
```{r}
hrz <- 16 # Target horizon
hAggr <- (ceiling(hrz/ff)*ff)/AL
hAggr
```
```{r}
frc <- mse <- list()
for (i in 1:k){
yTemp <- Y[[i]]
fit <- ets(yTemp)
mse[[i]] <- fit$mse
frcTemp <- forecast(fit,h=hAggr[i])$mean
# Re-structure forecasts
frc[[i]] <- matrix(frcTemp,ncol=hAggr[1]) # Organised as column per year
}
```
```{r}
frcAll <- abind(frc,along=1)
frcAll
```
```{r}
# Structural:
W <- diag(1/rowSums(S))
Gstr <- solve(t(S)%*%W%*%S)%*%t(S)%*%W
# Variance:
mse <- unlist(mse)
W <- diag(1/mse[rep((1:k),rev(AL))])
Gvar <- solve(t(S)%*%W%*%S)%*%t(S)%*%W
```
```{r}
# Create the bottom level forecasts
frcBRec <- Gstr %*% frcAll
frcFinal <- as.numeric(frcBRec)[1:hrz]
# We can also translate this into a time series object
frcFinal <- ts(frcFinal,frequency=frequency(y),start=end(y)[1] + deltat(y)*end(y)[2])
frcFinal
```
```{r}
ts.plot(y,frcFinal,col=c("black","red"))
```
```{r}
frcARec <- S %*% frcBRec
```