Introduction

The first part of this report is a forecast of milk production in Belgium. The data Milk is a record of the monthly production of milk from January 1997 to July 2023. Numerical Values are measured in millions of liters. The data is obtained from Statbel, Belgium’s national statistics agency. To forecast the data, naive, STL, ETS, and ARIMA will be used, analysed and compared. Thereafter a forecast up to December 2025 will be generated.

The second part of this report is a forecast of the number of nights (in millions) spent on tourists accommodation establishments in Spain. The data Nights is obtained from the European Union’s Eurostat agency. To forecast the data, we will make use of, analyse and compare complex seasonality model and Neural Network models. The dataset contains values from January 1990 to September 2023. The values between March 2020 and December 2021 will be excluded for the forecast analysis. During that period, the COVID pandemic occurred. To avoid anomalies for the forecast model, it will be omitted. Thereafter, we will forecast the data up to December 2025.

The first step is to define the working directory and install all necessary packages for this analysis. This project’s working directory is in my iCloud folders as shown below.

getwd()

For this project we require the package readxl to read the dataset, fpp2 for the time series forecasting and ggplot2 for the graphs. Please make sure you have the following installed beforehand.

library("readxl")
library("fpp2")
## Registered S3 method overwritten by 'quantmod':
##   method            from
##   as.zoo.data.frame zoo
## ── Attaching packages ────────────────────────────────────────────── fpp2 2.5 ──
## ✔ ggplot2   3.4.4      ✔ fma       2.5   
## ✔ forecast  8.21.1     ✔ expsmooth 2.3
## 
library("gt")

Case 1

We first import the data using the readxl package. Then we inspect the class type of the values in the columns. As we can see below, the values are already in the correct format, hence there is no need for any further manipulation. The dates are in the proper POSIXct form and the Milk production values are in numerical form. Therefore, we can move on to visualising the graph on a simple time series plot.

rawdatamilk <- read_excel("DataSets2023.xlsx", sheet="Milk")
str(rawdatamilk)
## tibble [319 × 2] (S3: tbl_df/tbl/data.frame)
##  $ Date: POSIXct[1:319], format: "1997-01-01" "1997-02-01" ...
##  $ Milk: num [1:319] 222 209 239 276 294 ...

The data shows a time series of milk production in Belgium since 1997. There is some sort of seasonality that can be seen in the data. From visually analysing the time series plot, variance seem to be more on earlier years and less in later years with an uptick in 2015. Hence, transformation may be necessary when modelling the time series. On the time series display plot, the ACF plot shows significant autocorrelation between values, with an observed repeating pattern between every twelfth spike.

This seasonality occurence is further confirmed with the seasonal plot and monthly plot.Summer seems to be the peak season for milk production and there is an increasing trend as the later years are clustered above previous/earlier years. Monthly wise, production usually peak mid month and is the lowest towards month-end.

milk <- ts(rawdatamilk[,2], frequency = 12, start = c(1997,1))
plot(milk, main="Milk Production", xlab="months", 
     ylab="Qty (in Millions)", type="l")

tsdisplay(milk)

seasonplot(milk,year.labels=TRUE, year.labels.left=TRUE,
           main="Seasonal plot",
           ylab="milk",col=rainbow(20), pch=19)

monthplot(milk,ylab="milk",xlab="month", type="l",
          main="Monthplot: Milk Production")

Partioning

As requested, the data is partitioned into two seperate parts to train and test the models. The training set is up till July 2020 whereas the testing set is from August 2020 till July 2023.

milk1 <- window(milk, end=c(2020,7))
milk2 <- window(milk, start=c(2020,8), end=c(2023,7))

h1 <- length(milk2)

Transformation

As mentioned previously, there seems to be more variance in earlier years than later years with an uptick in the year 2015. To address this issue, a Box-Cox test can be applied. Using the BoxCox.lamba function is used to obtain the optimal lambda value for transformation. The optimal lambda is 1.334866.

lambda1 <- BoxCox.lambda(milk)
lambda1
## [1] 1.334866
plot(BoxCox(milk, lambda = 1.334866))

tsdisplay(BoxCox(milk, lambda = 1.334866))

Naive model

A naive model is built as a benchmark for more complex models. The transformation mentioned above will be applied to the model. From visually analysing the data, the model predicted the most recent years with a relatively big amount of error but did relatively decent in predicting the earlier years of the test set. The accuracy table for the naive test set shows a Mean Absolute Percentage Error (MAPE) of 2.65 and a Mean Absolute Squared Error (MASE) of 0.814.

There seems to be an underfit in the peak period values of the test set and over fit i the off-peak values of the test set. From a business and microeconomic perspective, suppose milk producers followed this forecast,this might be favourable as the supply is higher than the demand, possibly driving up prices and consequently profit given that actual demand corresponds to that of the solid black line.

models_naive <- c("Seasonal Naive")
n_naive <- length(models_naive)
m13 <- snaive(milk1,lambda = lambda1, h=h1)


plot(milk, main="Milk Production", 
     ylab="", xlab="years", xlim=c(1997,2023))
lines(m13$mean, col=4, lwd=2)
legend("topleft",lty=1,col=c(4),legend=c("Seasonal naive"))

m13accuracy <- data.frame(accuracy(m13, milk2))[2,c(2,3,5,6)]
rownames(m13accuracy) <- c("naive")
gt(m13accuracy, rownames_to_stub = T, caption= "naive test set")
naive test set
RMSE MAE MAPE MASE
naive 12.87775 9.807791 2.651062 0.8148861

Analysing the residuals of the seasonal naive model shows that the residuals are autocorrelated from the Ljung-Box test and does not show a white noise pattern as the null hypotheses that the residuals are independent i rejected and the alternate hypotheses that the residuals are correlated is accepted.

res_m13 <- checkresiduals(m13)

## 
##  Ljung-Box test
## 
## data:  Residuals from Seasonal naive method
## Q* = 593.18, df = 24, p-value < 2.2e-16
## 
## Model df: 0.   Total lags used: 24
res_table13 <- data.frame(matrix(ncol = 3,))
names(res_table13) <- c("Q*", "df", "p-value")
res_table13[1,] <- c(res_m13$statistic, res_m13$parameter, res_m13$p.value)
rownames(res_table13) <- c("seasonal naive")
gt(data=res_table13, rownames_to_stub = T, caption = "residual diagnostics seasonal naive")
residual diagnostics seasonal naive
Q* df p-value
seasonal naive 593.1806 24 0

STL Decomposition

For STL Decomposition methods, there are five different method parameters to be tested namely naive, random walk with drift, ETS, Arima and Arima LOG. A for loop is then created to generate the accuracy tables for the train and test set respectively. Out of the five models it is deduced that STL Arima and STL Arima LOG had the lowest MAPE and MASE.

models_stl <- c("stl naive", "stl rwdrift", "stl ets", "stl arima", "stl arima log")

n14 <- length(models_stl)

m141<- stlf(milk1, method="naive",lambda = lambda1, h=h1, robust = TRUE)
m142<- stlf(milk1, method="rwdrift",lambda = lambda1, h=h1, robust = TRUE)
m143<- stlf(milk1, method="ets", h=h1, lambda = lambda1, robust = TRUE)
m144 <- stlf(milk1, method="arima", lambda = lambda1, h=h1, robust = TRUE)
m145<- stlf(milk1, method="arima", lambda = 0 ,h=h1, biasadj = TRUE, robust = TRUE)

testset <- milk2
s_train1 <- data.frame(matrix(nrow = 0, ncol = 4))
s_test1 <- data.frame(matrix(nrow = 0, ncol = 4))

for (i in 141:145) {
  assign(paste0("s_m", i), accuracy(get(paste0("m", i)), testset)[,c(2,3,5,6)])
  s_train1 <- rbind(s_train1, get(paste0("s_m", i))[1,])
  s_test1 <- rbind(s_test1, get(paste0("s_m", i))[2,])
}


stlmodels <- c("s_train1", "s_test1")

for (i in stlmodels){
  x=get(i)
  names(x) <- c("RMSE", "MAE", "MAPE", "MASE")
  rownames(x) <- c(models_stl)
  assign(i,x)
}

stl_train1<- gt(data = s_train1 , rownames_to_stub = T, caption ="stl_train1")
stl_test1<- gt(data = s_test1 , rownames_to_stub = T, caption ="stl_test1")

stl_train1;stl_test1
stl_train1
RMSE MAE MAPE MASE
stl naive 7.126557 5.149231 1.890950 0.4278269
stl rwdrift 7.108796 5.169358 1.902132 0.4294992
stl ets 6.999438 5.069659 1.862685 0.4212156
stl arima 6.880790 5.115872 1.878486 0.4250552
stl arima log 7.023860 5.148984 1.888003 0.4278064
stl_test1
RMSE MAE MAPE MASE
stl naive 10.410226 8.927976 2.465543 0.7417862
stl rwdrift 11.884405 10.174346 2.870051 0.8453415
stl ets 10.366899 8.698491 2.391132 0.7227193
stl arima 8.262732 6.670269 1.867203 0.5542032
stl arima log 8.194037 6.668505 1.867918 0.5540567

However, further analysis of the residuals show that only the STL Arima model has residuals that resembles white noise and is independent because of the high p-value of over 0.2. Thus far, this model is considered as the best one.

res_m141 <- checkresiduals(m141)

## 
##  Ljung-Box test
## 
## data:  Residuals from STL +  Random walk
## Q* = 36.805, df = 24, p-value = 0.04576
## 
## Model df: 0.   Total lags used: 24
res_m142 <- checkresiduals(m142)

## 
##  Ljung-Box test
## 
## data:  Residuals from STL +  Random walk with drift
## Q* = 36.805, df = 24, p-value = 0.04576
## 
## Model df: 0.   Total lags used: 24
res_m143 <- checkresiduals(m143)

## 
##  Ljung-Box test
## 
## data:  Residuals from STL +  ETS(A,N,N)
## Q* = 29.665, df = 24, p-value = 0.1961
## 
## Model df: 0.   Total lags used: 24
res_m144 <- checkresiduals(m144)

## 
##  Ljung-Box test
## 
## data:  Residuals from STL +  ARIMA(1,1,1) with drift
## Q* = 25.214, df = 22, p-value = 0.2869
## 
## Model df: 2.   Total lags used: 24
res_m145 <- checkresiduals(m145)

## 
##  Ljung-Box test
## 
## data:  Residuals from STL +  ARIMA(2,1,1) with drift
## Q* = 33.244, df = 21, p-value = 0.04358
## 
## Model df: 3.   Total lags used: 24
res_table14 <- data.frame(matrix(ncol = 3,))
names(res_table14) <- c("Q*", "df", "p-value")

res_table14[1,] <- c(res_m141$statistic, res_m141$parameter, res_m141$p.value)
res_table14[2,] <- c(res_m142$statistic, res_m142$parameter, res_m142$p.value)
res_table14[3,] <- c(res_m143$statistic, res_m143$parameter, res_m143$p.value)
res_table14[4,] <- c(res_m144$statistic, res_m144$parameter, res_m144$p.value)
res_table14[5,] <- c(res_m145$statistic, res_m145$parameter, res_m145$p.value)


rownames(res_table14) <- c(models_stl)
gt(data=res_table14, rownames_to_stub = T)
Q* df p-value
stl naive 36.80478 24 0.04576154
stl rwdrift 36.80478 24 0.04576154
stl ets 29.66501 24 0.19610380
stl arima 25.21407 22 0.28694755
stl arima log 33.24367 21 0.04358407

From there a plot can be generated to visually show the results of the STL Arima model. The model performed exceptionally well except for the middle years in the test set as there seems to be over fitting during off-peak periods. From a business and a microeconomic perspective, suppose milk producers followed this forecast,this might be unfavourable as the supply is higher than the demand, possibly driving down prices and may lead to wastage as milk is a perishable good given that actual demand corresponds to that of the solid black line.

plot(milk, main="Milk Production", 
     ylab="", xlab="months", xlim=c(1997,2023))
lines(m144$mean, col=4, lwd=2)
legend("topleft",lty=1,col=c(4),legend=c("STL Arima"))

ETS models

Four forecasts using ETS Models is performed with varying parameters. Damping and Lambda values for Box-Cox transformation is varied and compared to the default ETS function which algorithmically performs a grid search to find the most optimal model. From there, the same for loop done on the STL models analysis is made to compute and compare the accuracy of all ETS models. The accuracy tables shows that ETS log had the lowest MAPE and MASE. The state space of the final ETS log model is ETS(A,Ad,A) with the smoothing parameter values shown below.

models_ets <- c("ETS", "ETS no damping", "ETS lambda", "ETS log")
n15 <- length(models_ets)

m151 <- forecast(ets(milk1), h=h1 )
m152 <- forecast(ets(milk1,damped = F), h=h1)
m153 <- forecast(ets(milk1, lambda = lambda1, biasadj = T), h=h1)
m154 <- forecast(ets(milk1,  lambda = 0, biasadj = T), h=h1)

testset <- milk2
e_train1 <- data.frame(matrix(nrow = 0, ncol = 4))
e_test1 <- data.frame(matrix(nrow = 0, ncol = 4))

for (i in 151:154) {
  assign(paste0("e_m", i), accuracy(get(paste0("m", i)), testset)[,c(2,3,5,6)])
  e_train1 <- rbind(e_train1, get(paste0("e_m", i))[1,])
  e_test1 <- rbind(e_test1, get(paste0("e_m", i))[2,])
}


etsmodels <- c("e_train1", "e_test1")

for (i in etsmodels){
  x=get(i)
  names(x) <- c("RMSE", "MAE", "MAPE", "MASE")
  rownames(x) <- c(models_ets)
  assign(i,x)
}

ets_train1<- gt(data = e_train1 , rownames_to_stub = T, caption ="ets_train1")
ets_test1<- gt(data = e_test1 , rownames_to_stub = T, caption ="ets_test1")

ets_train1;ets_test1
ets_train1
RMSE MAE MAPE MASE
ETS 7.782087 6.020243 2.202041 0.5001955
ETS no damping 7.904441 6.092256 2.226735 0.5061787
ETS lambda 7.816108 6.084651 2.224939 0.5055468
ETS log 7.836536 6.127634 2.224381 0.5091181
ets_test1
RMSE MAE MAPE MASE
ETS 10.17359 8.545781 2.337310 0.7100313
ETS no damping 10.22311 8.606203 2.352467 0.7150515
ETS lambda 10.60551 8.825295 2.417032 0.7332549
ETS log 10.17865 8.119512 2.224482 0.6746145
ets(milk1,  lambda = 0, biasadj = T)
## ETS(A,Ad,A) 
## 
## Call:
##  ets(y = milk1, lambda = 0, biasadj = T) 
## 
##   Box-Cox transformation: lambda= 0 
## 
##   Smoothing parameters:
##     alpha = 0.9371 
##     beta  = 0.0013 
##     gamma = 1e-04 
##     phi   = 0.9714 
## 
##   Initial states:
##     l = 5.3939 
##     b = 0.0126 
##     s = -0.0143 -0.087 -0.0512 -0.0713 -0.0195 0.0299
##            0.0434 0.1115 0.062 0.0431 -0.0568 0.0101
## 
##   sigma:  0.0294
## 
##       AIC      AICc       BIC 
## -380.3238 -377.7329 -314.7058

Next, a residual analysis is carried out anong all ETS models. As the table below shows, only the ETS log model has residuals that corresponds to a white noise series. Therefore double confirming it as our final model among other ETS models performed.

res_m151 <- checkresiduals(m151)

## 
##  Ljung-Box test
## 
## data:  Residuals from ETS(A,Ad,A)
## Q* = 44.531, df = 24, p-value = 0.006614
## 
## Model df: 0.   Total lags used: 24
res_m152 <- checkresiduals(m152)

## 
##  Ljung-Box test
## 
## data:  Residuals from ETS(A,N,A)
## Q* = 43.146, df = 24, p-value = 0.009573
## 
## Model df: 0.   Total lags used: 24
res_m153 <- checkresiduals(m153)

## 
##  Ljung-Box test
## 
## data:  Residuals from ETS(A,Ad,A)
## Q* = 45.506, df = 24, p-value = 0.005073
## 
## Model df: 0.   Total lags used: 24
res_m154 <- checkresiduals(m154)

## 
##  Ljung-Box test
## 
## data:  Residuals from ETS(A,Ad,A)
## Q* = 77.092, df = 24, p-value = 1.756e-07
## 
## Model df: 0.   Total lags used: 24
res_table15 <- data.frame(matrix(ncol = 3,))
names(res_table15) <- c("Q*", "df", "p-value")

res_table15[1,] <- c(res_m141$statistic, res_m151$parameter, res_m141$p.value)
res_table15[2,] <- c(res_m142$statistic, res_m152$parameter, res_m142$p.value)
res_table15[3,] <- c(res_m143$statistic, res_m153$parameter, res_m143$p.value)
res_table15[4,] <- c(res_m144$statistic, res_m154$parameter, res_m144$p.value)



rownames(res_table15) <- c(models_ets)
gt(data=res_table15, rownames_to_stub = T)
Q* df p-value
ETS 36.80478 24 0.04576154
ETS no damping 36.80478 24 0.04576154
ETS lambda 29.66501 24 0.19610380
ETS log 25.21407 24 0.28694755

A plot is then generated and from a visual analysis, it is apparent that there might be an overfit in peak periods as the model overestimated the peak and an underfit in the trough or off peak period values over the years in the test set. From a business and a microeconomic perspective, suppose milk producers followed this forecast,this might be unfavourable during as the supply is higher than the demand, possibly driving down prices and may lead to wastage as milk is a perishable good given that actual demand corresponds to that of the solid black line given that actual demand corresponds to that of the solid black line. However, it may be otherwise favourable during off-peak periods as milk producers produce less that the actual demand that correspond to the solid black line.

plot(milk, main="Milk Production", 
     ylab="", xlab="months", xlim=c(1997,2023))
lines(m154$mean, col=4, lwd=2)

ARIMA

Two Arima models will be built and analysed. The first one will utilise the full and default algorithm of R’s auto arima function, whereas the second one will be based on visual analysis and intuition. Estimating the amount of differencing needed in non seasonal and seasonal part of the Arima models, we obtain the values of 1 for both.

models_arima <- c("auto.arima","arima estimation")
n_arima <- length(models_arima)
m161 <- forecast(auto.arima(milk1,lambda = lambda1), h=h1)

ndiffs(milk1)
## [1] 1
nsdiffs(milk1)
## [1] 1
tsdisplay(diff(milk1,lag=12))

tsdisplay(diff(diff(milk1,lag=12)))

Based intuition after analysing the ACF and PACF it can be deduced that an Arima(1,1,0)(1,1,1)[12] model will yield good results. The intuition is as follows: Since there is significant lag and quick decay on PACF at 1, an AR(1) model is plausible.The sharp cuttoff at PACF at 1 and a noticeable pattern after every 12 lags suggest the presence of seasonality.Since there is no sharp cutoff on ACF and that the decay is geometric, q could be 0. “d” and “D” values have been estimated to be 1. Hence the model is coded below:

m162 <- forecast(arima(milk1, order = c(1,1,0), seasonal=c(1,1,1)), h=h1)

Checking for Accuracy and Residuals, it is reported from the table below that the auto arima model generated by R is more accurate in terms of MAPE and MASE compared to the intuitive model. The generated model also performs better on the residuals compared to the intuitive model. A the 95% significance level, the residuals can be accepted as white noise.

tsdisplay(residuals(m161))

tsdisplay(residuals(m162))

a_test1 <- rbind(data.frame(accuracy(m161,milk2))[-1,c(2,3,5,6)],data.frame(accuracy(m162, milk2))[-1,c(2,3,5,6)] )
row.names(a_test1) <- c(models_arima)
gt(a_test1, rownames_to_stub = T, caption = "auto.arima test set accuracy")
auto.arima test set accuracy
RMSE MAE MAPE MASE
auto.arima 11.73997 10.15380 2.856677 0.8436345
arima estimation 16.38942 15.13347 4.216090 1.2573729
res_m161 <- checkresiduals(m161)

## 
##  Ljung-Box test
## 
## data:  Residuals from ARIMA(1,1,1)(1,1,1)[12]
## Q* = 30.491, df = 20, p-value = 0.06228
## 
## Model df: 4.   Total lags used: 24
res_m162 <- checkresiduals(m162)

## 
##  Ljung-Box test
## 
## data:  Residuals from ARIMA(1,1,0)(1,1,1)[12]
## Q* = 43.219, df = 21, p-value = 0.002947
## 
## Model df: 3.   Total lags used: 24
res_table16 <- data.frame(matrix(ncol = 3,))
names(res_table16) <- c("Q*", "df", "p-value")
res_table16[1,] <- c(res_m161$statistic, res_m161$parameter, res_m161$p.value)
res_table16[2,] <- c(res_m162$statistic, res_m162$parameter, res_m162$p.value)

rownames(res_table16) <- c("auto.arima(1,1,1)(1,1,1)[12]", "arima(1,1,0)(1,1,1)[12]")
gt(data=res_table16, rownames_to_stub = T)
Q* df p-value
auto.arima(1,1,1)(1,1,1)[12] 30.49114 20 0.062276708
arima(1,1,0)(1,1,1)[12] 43.21895 21 0.002947272

From there, a plot is generated for the auto.arima model. The model generated by R correspond to the following formula with a backshift notation:

(1−0.7749B)(1−0.0294B12)(1−B)(1−B12)yt =(1-0.9464B)(1-0.7464B^12)et

The model performed exceptionally well except for the middle years in the test set as there seems to be over fitting during peak and off-peak periods. From a business and a microeconomic perspective, suppose milk producers followed this forecast,this might be unfavourable as the supply is higher than the demand, possibly driving down prices and may lead to wastage and consequently, losses as milk is a perishable good given that actual demand corresponds to that of the solid black line.

plot(milk, main="milk", 
     ylab="", xlab="months", xlim=c(1997,2023))
lines(m161$mean, col=4, lwd=2)

m161$model
## Series: milk1 
## ARIMA(1,1,1)(1,1,1)[12] 
## Box Cox transformation: lambda= 1.334866 
## 
## Coefficients:
##          ar1      ma1    sar1     sma1
##       0.7749  -0.9464  0.0294  -0.7464
## s.e.  0.0577   0.0322  0.0901   0.0718
## 
## sigma^2 = 2586:  log likelihood = -1447.25
## AIC=2904.51   AICc=2904.73   BIC=2922.5

Model Comparison

Comparing all models, we have the STL Arima as the best performing model of this case study in terms of accuracy measures with MAPE and MASE. Residuals are also proven statitistically to be white noise.

finalcomparison1 <- rbind(m13accuracy,s_test1,e_test1,a_test1)
gt(finalcomparison1, rownames_to_stub = T, caption="model comparison case 1")
model comparison case 1
RMSE MAE MAPE MASE
naive 12.877750 9.807791 2.651062 0.8148861
stl naive 10.410226 8.927976 2.465543 0.7417862
stl rwdrift 11.884405 10.174346 2.870051 0.8453415
stl ets 10.366899 8.698491 2.391132 0.7227193
stl arima 8.262732 6.670269 1.867203 0.5542032
stl arima log 8.194037 6.668505 1.867918 0.5540567
ETS 10.173593 8.545781 2.337310 0.7100313
ETS no damping 10.223113 8.606203 2.352467 0.7150515
ETS lambda 10.605512 8.825295 2.417032 0.7332549
ETS log 10.178650 8.119512 2.224482 0.6746145
auto.arima 11.739968 10.153800 2.856677 0.8436345
arima estimation 16.389418 15.133465 4.216090 1.2573729
finalresidual <- rbind(res_table13,res_table14, res_table15, res_table16)
gt(finalresidual, rownames_to_stub = T, caption = "residual diagnostics all models")
residual diagnostics all models
Q* df p-value
seasonal naive 593.18065 24 0.000000000
stl naive 36.80478 24 0.045761539
stl rwdrift 36.80478 24 0.045761539
stl ets 29.66501 24 0.196103802
stl arima 25.21407 22 0.286947547
stl arima log 33.24367 21 0.043584069
ETS 36.80478 24 0.045761539
ETS no damping 36.80478 24 0.045761539
ETS lambda 29.66501 24 0.196103802
ETS log 25.21407 24 0.286947547
auto.arima(1,1,1)(1,1,1)[12] 30.49114 20 0.062276708
arima(1,1,0)(1,1,1)[12] 43.21895 21 0.002947272

Conclusion

Hence the STL Arima log models is generated again as the model of choice for this case study. A table of the exact values with confidence intervals is given. This data would be useful for companies and the relevant goverment authorities to coordinate and optimise milk production.

bestmode1 <- stlf(milk, method="arima", lambda = lambda1 ,h=29, biasadj = TRUE, robust = TRUE)
plot(bestmode1)
lines(milk)

summary18 <- data.frame(summary(bestmode1))
summary18$ID <- seq.int(nrow(summary18))
summary18 <- subset(summary18, ID>5)
summary18<- summary18[,-6]

                      
final18 <- gt(data=summary18, rownames_to_stub = T)

final18
Point.Forecast Lo.80 Hi.80 Lo.95 Hi.95
Jan 2024 387.5148 373.8654 401.1015 366.5458 408.2062
Feb 2024 361.0200 346.5500 375.4144 338.7761 382.9291
Mar 2024 399.2036 384.8066 413.5328 377.0836 421.0237
Apr 2024 393.3373 378.4982 408.1034 370.5331 415.8184
May 2024 407.3870 392.3880 422.3139 384.3398 430.1153
Jun 2024 387.1750 371.5972 402.6711 363.2276 410.7606
Jul 2024 389.3087 373.4592 405.0741 364.9420 413.3029
Aug 2024 380.4534 364.1899 396.6262 355.4435 405.0619
Sep 2024 365.2009 348.4268 381.8746 339.3949 390.5623
Oct 2024 374.3396 357.4329 391.1468 348.3322 399.9063
Nov 2024 362.8880 345.5336 380.1341 336.1825 389.1145
Dec 2024 380.6307 363.2970 397.8615 353.9652 406.8407
Jan 2025 391.8677 374.4536 409.1809 365.0825 418.2063
Feb 2025 365.6271 347.5467 383.5909 337.7983 392.9399
Mar 2025 403.7709 386.0496 421.3908 376.5152 430.5778
Apr 2025 398.0057 379.9608 415.9439 370.2469 425.2924
May 2025 412.0592 393.9946 430.0206 384.2756 439.3858
Jun 2025 391.9674 373.3623 410.4574 363.3386 420.0866
Jul 2025 394.1232 375.3245 412.8050 365.1957 422.5333
Aug 2025 385.3265 366.1562 404.3726 355.8189 414.2838
Sep 2025 370.1560 350.4947 389.6811 339.8790 399.8304
Oct 2025 379.2671 359.5447 398.8558 348.9005 409.0418
Nov 2025 367.8743 347.7236 387.8812 336.8365 398.2752
Dec 2025 385.5466 365.4979 405.4593 354.6777 415.8139

Case 2

Case two is a forecast for the number of nights spent in tourist accommodations in Spain. The data is obtained from the European Union’s Statistics Agency, Eurostat. Examining the structure of the raw data set, there is a column of dates from 1990 to 2023 and a range of observations of three different countries.

rawdatanights <- read_excel("DataSets2023.xlsx", sheet="Nights")
str(rawdatanights)
## tibble [405 × 4] (S3: tbl_df/tbl/data.frame)
##  $ Date   : POSIXct[1:405], format: "1990-01-01" "1990-02-01" ...
##  $ Spain  : num [1:405] 6.68 7 8.53 11.17 11.74 ...
##  $ Italy  : num [1:405] 9.1 10.1 12.3 15.6 16.1 ...
##  $ Belgium: num [1:405] 0.846 0.983 1.362 3.151 3.148 ...

Visualising the Data

Spain will be the focus for this case study hence, the values for Belgium and Italy will be dropped. The data of the amount of nights spent in Spanish tourist accommodation establishment is visualised in a plot. Visual analysis indicate a steep drop anomaly during the COVID period and a sudden increase in the year 2000. Variance seems to be increasing as time progresses. Seasonality is present in the data with August being the peak period.

nights <- ts(rawdatanights[,2], frequency = 12, start = c(1990,1))
plot(nights, main="Nights spent on tourists accommodation establishments in Spain", xlab="Years", ylab="nights", type="l")

tsdisplay(nights)

seasonplot(nights,year.labels=TRUE, year.labels.left=TRUE,
           main="Seasonal plot",
           ylab="nightse",col=rainbow(20), pch=19)

monthplot(nights,ylab="nightse",xlab="month", type="l",
          main="Monthplot: Nights spent")

Partitioning the data

As with the any time series forecast analysis, the data set needs to be partitioned. However in this particular case, COVID is the known cause of the sudden and steep drop anomaly and hence it is best to remove it. It is treated more or less like an outlier that needs to be removed from the training set and model. The training set is determined by values up to December 2017. In this analysis we will use the values up till 2017 to predict the best model by fitting it to values from 2018 January till 2020 January.

For R to be able to transform the data we must get rid of zeros. Upon closer inspection of the dataset, there is a zero value in one of the month during the COVID period. By altering the value to 0.000001, it means only one night that month was spent in total in Spanish tourist accommodation establishment. This zero value may not be reflective of the actual situtation back then and can be explained by the rounding off error excel may have made. A lambda value of 0.104 is needed to achieve a good Box-Cox transformation to stabilise variance. For this case study, STL models and ARIMA will be used.

nights1 <- window(nights, end=c(2017,12))
nights2 <- window(nights, start=c(2018,1), end=c(2020,1))
nights3 <- ifelse(rawdatanights$Spain==0, 0.000001,rawdatanights$Spain)
nights3 <- window(nights, end=c(2020,1))
h <- length(nights2)

lambda20 <- BoxCox.lambda(nights1)
lambda20
## [1] 0.1040385
plot(BoxCox(nights3, lambda=lambda20), main="Nights spent on tourists accommodation establishments in Spain", xlab="Years", 
     ylab="nights", type="l")

Building the STL model

For STL Decomposition methods, there are five different method parameters to be tested namely naive, random walk with drift, ETS, Arima and Arima LOG. A for loop is then created to generate the accuracy tables for the train and test set respectively. Out of the five models it is deduced that STL Arima and STL Arima LOG had the lowest MAPE and MASE.

models <- c("stl naive", "stl rwdrift", "stl ets", "stl arima", "stl arima log")

n2 <- length(models)

m2<- stlf(nights1, method="naive",lambda = lambda20, h=h, robust = TRUE)
m3 <- stlf(nights1, method="rwdrift",lambda = lambda20, h=h, robust = TRUE)
m4<- stlf(nights1, method="ets", h=h, lambda = lambda20, robust = TRUE)
m5 <- stlf(nights1, method="arima", lambda = lambda20, h=h, robust = TRUE)
m6<- stlf(nights1, method="arima", lambda = 0 ,h=h, biasadj = TRUE, robust = TRUE)

Accuracy Testing STL model

From the loop, it is determined that STL naive and STL ETS as the two top contenders for the final STL Model as they have the lowest MASE and MAPE among the others. To choose the final model, the model with the highest p values among the two will be chosen.

testset2 <- nights2
s_train2 <- data.frame(matrix(nrow = 0, ncol = 4))
s_test2 <- data.frame(matrix(nrow = 0, ncol = 4))

for (i in 2:6) {
  assign(paste0("s_m", i), accuracy(get(paste0("m", i)), testset2)[,c(2,3,5,6)])
  s_train2 <- rbind(s_train2, get(paste0("s_m", i))[1,])
  s_test2 <- rbind(s_test2, get(paste0("s_m", i))[2,])
}


stlmodels <- c("s_train2", "s_test2")

for (i in stlmodels){
  x=get(i)
  names(x) <- c("RMSE", "MAE", "MAPE", "MASE")
  rownames(x) <- c(models)
  assign(i,x)
}

stl_train2<- gt(data = s_train2 , rownames_to_stub = T, caption ="stl_train")
stl_test2<- gt(data = s_test2, rownames_to_stub = T, caption ="stl_test")

stl_train2;stl_test2
stl_train
RMSE MAE MAPE MASE
stl naive 1.354295 0.7701904 3.200784 0.4863607
stl rwdrift 1.354079 0.7672821 3.203690 0.4845242
stl ets 1.096399 0.6869093 2.981506 0.4337703
stl arima 1.091219 0.6783302 2.964780 0.4283527
stl arima log 1.125605 0.6960716 2.985940 0.4395561
stl_test
RMSE MAE MAPE MASE
stl naive 1.577534 1.149647 2.724479 0.7259806
stl rwdrift 3.029634 2.247477 5.398146 1.4192394
stl ets 1.784818 1.233723 2.824709 0.7790731
stl arima 2.822119 2.060646 4.914792 1.3012594
stl arima log 3.723880 2.670645 6.130380 1.6864620

Residual Diagnostics

From the residual test, the STL ETS(A,Ad,N) is chosen as the residuals are independent and not correlated. Using this model, a time series forecast plot is then produced. The results below shows an excellent fit.

res_m2 <- checkresiduals(m2)

## 
##  Ljung-Box test
## 
## data:  Residuals from STL +  Random walk
## Q* = 96.346, df = 24, p-value = 1.252e-10
## 
## Model df: 0.   Total lags used: 24
res_m4 <- checkresiduals(m4)

## 
##  Ljung-Box test
## 
## data:  Residuals from STL +  ETS(A,Ad,N)
## Q* = 34.12, df = 24, p-value = 0.08255
## 
## Model df: 0.   Total lags used: 24
res_table20 <- data.frame(matrix(ncol = 3,))
names(res_table20) <- c("Q*", "df", "p-value")
res_table20[1,] <- c(res_m2$statistic, res_m2$parameter, res_m2$p.value)
res_table20[2,] <- c(res_m4$statistic, res_m4$parameter, res_m4$p.value)
rownames(res_table20) <- c("STL naive", "STL ETS" )
gt(data=res_table20, rownames_to_stub = T)
Q* df p-value
STL naive 96.34635 24 1.252290e-10
STL ETS 34.12041 24 8.255167e-02
plot(nights, main="nights", ylab="", xlab="year")
lines(m4$mean, col=4, lwd=2)

Final STL Model: STL + ETS(A, Ad, N)

Hence It can then be concluded that the STL +ETS(A, Ad, N) is the best model among the decomposition methods. A table with the corresponding forecast values till 2025 December is generated with the plot. Visually analysing the data, the values post COVID period is predicted exceptionally well with this model.

final2 <- stlf(nights3, method="ets",lambda = lambda20, h=71, robust = TRUE)
plot(final2)
lines(nights)

summary1 <- data.frame(summary(final2))
summary1$ID <- seq.int(nrow(summary1))
summary1 <- subset(summary1, ID>47)
summary1 <- summary1[,-6]

                      
s_mfinal2 <- gt(data=summary1, rownames_to_stub = T)

s_mfinal2
Point.Forecast Lo.80 Hi.80 Lo.95 Hi.95
Jan 2024 21.79434 16.12756 29.18408 13.69764 33.94248
Feb 2024 23.23023 17.15315 31.16981 14.55130 36.28906
Mar 2024 28.87054 21.37873 38.63430 18.16464 44.91869
Apr 2024 35.49397 26.35109 47.38296 22.42145 55.02309
May 2024 41.60983 30.92712 55.48731 26.33188 64.39895
Jun 2024 49.98990 37.22990 66.53725 31.73329 77.15029
Jul 2024 65.85766 49.28818 87.25408 42.12558 100.93563
Aug 2024 75.52519 56.56217 99.99783 48.36090 115.63977
Sep 2024 51.90467 38.28316 69.71829 32.45589 81.21208
Oct 2024 40.18535 29.28579 54.58823 24.66282 63.95023
Nov 2024 24.31224 17.34801 33.68431 14.43852 39.85542
Dec 2024 23.28265 16.52460 32.41939 13.71208 38.45521
Jan 2025 21.80252 15.37855 30.53411 12.71693 36.32405
Feb 2025 23.23835 16.36854 32.58715 13.52504 38.79160
Mar 2025 28.87979 20.43096 40.33433 16.92294 47.91620
Apr 2025 35.50441 25.21754 49.40316 20.93413 58.58067
May 2025 41.62113 29.62963 57.79111 24.62823 68.45350
Jun 2025 50.00239 35.71047 69.22113 29.73588 81.86910
Jul 2025 65.87266 47.35012 90.64157 39.57093 106.87783
Aug 2025 75.54109 54.38769 103.78861 45.49329 122.28685
Sep 2025 51.91533 36.76431 72.43860 30.46894 86.01486
Oct 2025 40.19329 28.10156 56.75408 23.12333 67.79449
Nov 2025 24.31699 16.61406 35.07817 13.49497 42.35266
Dec 2025 23.28694 15.82770 33.75434 12.81862 40.85239

Stationarity Check

The data set needs to be checked for stationarity prior to building an ARIMA forecast model that can be used to compare with the STL model above. In this step, the auto.arima function will be called. There is no need for a visual or intuitive approach as with the previous case study as in this case R will be relied on to find the most optimal model.

models2 <- c("auto.arima", "auto.arima adjusted", "auto.arima d1 D1 log")
n3 <- length(models2)

Differencing process

R determined that the d and D of the ARIMA forecast is 1 as shown below to achieve stationarity.

ndiffs(nights1)
## [1] 1
nsdiffs(nights1)
## [1] 1
tsdisplay(diff(nights1,12))

nsdiffs(diff(nights1,12))
## [1] 0
checkresiduals(diff(nights1,12,1))

## 
##  Ljung-Box test
## 
## data:  Residuals
## Q* = 821.76, df = 24, p-value < 2.2e-16
## 
## Model df: 0.   Total lags used: 24

Building the ARIMA model

Three different ARIMA models with different parameters is built. The first two will be transformed according to the predetermined lambda values found earlier whereas the last one will be log transformed. The first model will not have any other parameters specified.

m7 <- forecast(auto.arima(nights1, lambda=lambda20))


m8 <- forecast(auto.arima(nights1, stepwise = FALSE, approximation = FALSE, 
                  lambda = lambda20, biasadj = TRUE))


m9 <- forecast(auto.arima(nights1, stepwise = FALSE, approximation = FALSE, 
                       lambda = 0, biasadj = TRUE, d=1, D=1))

Accuracy Testing ARIMA models

The three models are tested for accuracy through the same for loop used previously. The test set table shows that the automatic ARIMA model generated is the best performing among all as it should be.

testset2 <- nights2
a_train2 <- data.frame(matrix(nrow = 0, ncol = 4))
a_test2 <- data.frame(matrix(nrow = 0, ncol = 4))

for (i in 7:9) {
  assign(paste0("a_m", i), accuracy(get(paste0("m", i)), testset2)[,c(2,3,5,6)])
  a_train2 <- rbind(a_train2, get(paste0("a_m", i))[1,])
  a_test2 <- rbind(a_test2, get(paste0("a_m", i))[2,])
}


arimamodels <- c("a_train2", "a_test2")

for (i in arimamodels){
  x=get(i)
  names(x) <- c("RMSE", "MAE", "MAPE", "MASE")
  rownames(x) <- c(models2)
  assign(i,x)
}

arima_train2<- gt(data = a_train2 , rownames_to_stub = T, caption ="a_train")
arima_test2<- gt(data = a_test2, rownames_to_stub = T, caption ="a_test")

arima_train2;arima_test2
a_train
RMSE MAE MAPE MASE
auto.arima 1.164692 0.8089505 3.422244 0.5108370
auto.arima adjusted 1.181138 0.8126543 3.449996 0.5131759
auto.arima d1 D1 log 1.223774 0.8377004 3.490427 0.5289920
a_test
RMSE MAE MAPE MASE
auto.arima 3.258278 2.484792 5.980126 1.569099
auto.arima adjusted 3.264634 2.481279 6.039881 1.566881
auto.arima d1 D1 log 4.242759 3.258999 7.674021 2.057997

Residual Check

A residual check should be done to double check that there is no autocorrelation in the residuals and to choose between the first two models. Both yield the same results however the first one will be chosen as it has a smaller MAPE. The first model corresponds to an ARIMA (1,0,1)(2,1,2)[12] with drift model. There is unfortunately some correlation in the residuals if we use alpha value of 0.05.

res_m7 <- checkresiduals(m7)

## 
##  Ljung-Box test
## 
## data:  Residuals from ARIMA(1,0,1)(2,1,2)[12] with drift
## Q* = 38.359, df = 18, p-value = 0.003471
## 
## Model df: 6.   Total lags used: 24
res_m8 <- checkresiduals(m8)

## 
##  Ljung-Box test
## 
## data:  Residuals from ARIMA(1,0,1)(1,1,2)[12] with drift
## Q* = 39.461, df = 19, p-value = 0.003849
## 
## Model df: 5.   Total lags used: 24
res_table21 <- data.frame(matrix(ncol = 3,))
names(res_table21) <- c("Q*", "df", "p-value")
res_table21[1,] <- c(res_m7$statistic, res_m7$parameter, res_m7$p.value)
res_table21[2,] <- c(res_m8$statistic, res_m8$parameter, res_m8$p.value)
rownames(res_table21) <- c("auto.arima", "auto.arima log")
gt(data=res_table21, rownames_to_stub = T)
Q* df p-value
auto.arima 38.35874 18 0.003471320
auto.arima log 39.46068 19 0.003849159

Final ARIMA Model: ARIMA(2,1,3)(2,1,2)[12] with drift

Hence the final forecast is generated with a plot and a table containing specific values till December 2025.

final3 <- auto.arima(nights3, lambda = lambda20)
final3 <- forecast(final3, h=71) 
plot(final3) 
lines(nights)

summary2 <- data.frame(summary(final3))
summary2$ID <- seq.int(nrow(summary2))
summary2 <- subset(summary2, ID>47)
summary2 <- summary2[,-6]

                      
s_mfinal2 <- gt(data=summary2, rownames_to_stub = T)

s_mfinal2
Point.Forecast Lo.80 Hi.80 Lo.95 Hi.95
Jan 2024 23.44206 16.56938 32.76682 13.71760 38.94230
Feb 2024 24.80215 17.38893 34.93099 14.33076 41.67212
Mar 2024 31.86052 22.37389 44.80418 18.45580 53.41022
Apr 2024 38.49070 27.02966 54.12840 22.29615 64.52571
May 2024 45.26564 31.75102 63.72342 26.17395 76.00426
Jun 2024 54.20371 38.02922 76.28989 31.35340 90.98283
Jul 2024 70.39206 49.53866 98.79209 40.91267 117.65024
Aug 2024 80.02886 56.25056 112.44703 46.42349 133.98955
Sep 2024 55.93573 38.52981 80.08235 31.44018 96.32543
Oct 2024 43.73641 29.64680 63.55387 23.97407 77.01403
Nov 2024 26.78737 17.66267 39.92925 14.06169 49.00374
Dec 2024 25.66913 16.78569 38.55448 13.30094 47.49564
Jan 2025 23.90751 15.47900 36.23727 12.19651 44.84335
Feb 2025 25.31660 16.25785 38.66109 12.75083 48.02042
Mar 2025 32.42124 20.88950 49.36071 16.41429 61.21825
Apr 2025 39.35405 25.39103 59.84106 19.96692 74.17034
May 2025 46.11207 29.74125 70.13881 23.38335 86.94723
Jun 2025 55.28192 35.70240 83.98578 28.09110 104.05064
Jul 2025 71.69134 46.52403 108.43525 36.70616 134.04732
Aug 2025 81.53367 52.87467 123.40012 41.70027 152.59471
Sep 2025 56.98071 36.07896 88.14382 28.06981 110.18236
Oct 2025 44.58174 27.69867 70.16191 21.31820 88.45328
Nov 2025 27.32725 16.42788 44.30928 12.40703 56.68633
Dec 2025 26.20215 15.60485 42.84467 11.72220 55.03966

Model Comparisons and Conclusion

Comparing both STL and ARIMA methods, it is deduced from the table below that the arima models did not perform as well as the stl ets model that was chosen previously. Hence the STL + ETS model should be used. This analysis has shown that the numbers of nights spent in Spanish tourist accommodation establishments have recovered and is back on the same trend as previously. Using the forecasted data, local tourist offices can predict and coordinate with the accommodation establishments.

final_summary <- rbind(a_test2, s_test2)
gt(final_summary, rownames_to_stub = T, caption = "final summary")
final summary
RMSE MAE MAPE MASE
auto.arima 3.258278 2.484792 5.980126 1.5690992
auto.arima adjusted 3.264634 2.481279 6.039881 1.5668812
auto.arima d1 D1 log 4.242759 3.258999 7.674021 2.0579967
stl naive 1.577534 1.149647 2.724479 0.7259806
stl rwdrift 3.029634 2.247477 5.398146 1.4192394
stl ets 1.784818 1.233723 2.824709 0.7790731
stl arima 2.822119 2.060646 4.914792 1.3012594
stl arima log 3.723880 2.670645 6.130380 1.6864620
final_res <- rbind(res_table20,res_table21)
gt(final_res, rownames_to_stub = T, caption = "final res analysis comparison")
final res analysis comparison
Q* df p-value
STL naive 96.34635 24 1.252290e-10
STL ETS 34.12041 24 8.255167e-02
auto.arima 38.35874 18 3.471320e-03
auto.arima log 39.46068 19 3.849159e-03

COVID Impact

To measure the impact of COVID on the data, a linear regression is carried out with the auto arima function using the lmtest package. Binary variables is added into the data frame with an ifelse command. Only the period between March 2020 and December 2021 is coded as one whereas all else is zero. The results show that the impact of covid was significant and has affected the number of nights spent in tourist accommodation establishment negatively by a factor of 8.

library(lmtest)
## Loading required package: zoo
## 
## Attaching package: 'zoo'
## The following objects are masked from 'package:base':
## 
##     as.Date, as.Date.numeric
covid_impact <- data.frame(rawdatanights)
covid_impact$covid <- ifelse(covid_impact$Date >= "2020-03-01" & covid_impact$Date < "2022-01-01", 1, 0)

covid_ts <- ts(covid_impact[,5], frequency = 12, start = c(1990,1))
xmodel <- auto.arima(nights, xreg = covid_ts)
coeftest(xmodel)
## 
## z test of coefficients:
## 
##        Estimate Std. Error  z value  Pr(>|z|)    
## ar1    0.844674   0.034507  24.4785 < 2.2e-16 ***
## ma1    0.174105   0.055254   3.1510  0.001627 ** 
## ma2    0.279523   0.051997   5.3758 7.626e-08 ***
## sma1  -0.612155   0.040994 -14.9327 < 2.2e-16 ***
## drift  0.066569   0.034076   1.9536  0.050751 .  
## xreg  -8.564214   1.557057  -5.5003 3.792e-08 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1