setwd("~/Maestria/3er semestre/Series de tiempo/Examen")
library(tidyverse)
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ dplyr 1.1.1 ✔ readr 2.1.4
## ✔ forcats 1.0.0 ✔ stringr 1.5.0
## ✔ ggplot2 3.4.2 ✔ tibble 3.2.1
## ✔ lubridate 1.9.2 ✔ tidyr 1.3.0
## ✔ purrr 1.0.1
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag() masks stats::lag()
## ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
library(readr)
library(magrittr)
##
## Attaching package: 'magrittr'
##
## The following object is masked from 'package:purrr':
##
## set_names
##
## The following object is masked from 'package:tidyr':
##
## extract
library(forecast)# Contiene el modelo ARIMA
## Registered S3 method overwritten by 'quantmod':
## method from
## as.zoo.data.frame zoo
library(tseries) #Para series de tiempo
library(TSA) #Para series de tiempo
## Registered S3 methods overwritten by 'TSA':
## method from
## fitted.Arima forecast
## plot.Arima forecast
##
## Attaching package: 'TSA'
##
## The following object is masked from 'package:readr':
##
## spec
##
## The following objects are masked from 'package:stats':
##
## acf, arima
##
## The following object is masked from 'package:utils':
##
## tar
library(urca) #Para hacer el Test de Raiz Unitaria (detectar hay o no estacionariedad)
library(ggplot2) #Para hacer gráficos
library(dplyr) #Para la manipulación de datos (filtrar, seleccionar, agregar, transformar)
library(stats) #Se usa para diversas pruebas estadísticas (medias,varianza, arima,etc)
library(seasonal)
##
## Attaching package: 'seasonal'
##
## The following object is masked from 'package:tibble':
##
## view
library(strucchange) # library implementing breakpoint analysis
## Loading required package: zoo
##
## Attaching package: 'zoo'
##
## The following objects are masked from 'package:base':
##
## as.Date, as.Date.numeric
##
## Loading required package: sandwich
##
## Attaching package: 'strucchange'
##
## The following object is masked from 'package:stringr':
##
## boundary
library(ggfortify) # extension for ggplot time series graphing
## Registered S3 methods overwritten by 'ggfortify':
## method from
## autoplot.Arima forecast
## autoplot.acf forecast
## autoplot.ar forecast
## autoplot.bats forecast
## autoplot.decomposed.ts forecast
## autoplot.ets forecast
## autoplot.forecast forecast
## autoplot.stl forecast
## autoplot.ts forecast
## fitted.ar forecast
## fortify.ts forecast
## residuals.ar forecast
train_nomodif = read_csv("./Datasets/train.csv")
## Rows: 3000888 Columns: 6
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## chr (1): family
## dbl (4): id, store_nbr, sales, onpromotion
## date (1): date
##
## ℹ Use `spec()` to retrieve the full column specification for this data.
## ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
train = filter(train_nomodif, family %in% c('LIQUOR,WINE,BEER', 'MEATS'))
head(train)
train_M = filter(train_nomodif, family == 'MEATS' & store_nbr == 11)
train_SF = filter(train_nomodif, family =='SEAFOOD' & store_nbr == 9)
#View(train)
test_nomodif = read_csv("./Datasets/test.csv")
## Rows: 28512 Columns: 5
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## chr (1): family
## dbl (3): id, store_nbr, onpromotion
## date (1): date
##
## ℹ Use `spec()` to retrieve the full column specification for this data.
## ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
test = filter(test_nomodif, family %in% c('LIQUOR,WINE,BEER', 'MEATS'))
head(test)
test_M = filter(test_nomodif, family == 'MEATS' & store_nbr == 11)
test_SF = filter(test_nomodif, family =='LIQUOR,WINE,BEER' & store_nbr == 9)
#View(test)
rm(test_nomodif)
seafood_stores_agrpd <- train_nomodif %>% filter(family == 'SEAFOOD') %>% select(date, sales) %>%
group_by(date) %>%
summarise(sales_sum = sum(sales)) %>% select(sales_sum)
ts_seafood_stores_agrpd = ts(seafood_stores_agrpd, frequency = 365, start=c(2013,1, 1))
autoplot(ts_seafood_stores_agrpd, main='Fig 1. Seafood sales, all stores')
rm(train_nomodif)
Stationary test
print("ADF TEST IN SEAFOOD STORES")
## [1] "ADF TEST IN SEAFOOD STORES"
adf.test(ts_seafood_stores_agrpd)
## Warning in adf.test(ts_seafood_stores_agrpd): p-value smaller than printed
## p-value
##
## Augmented Dickey-Fuller Test
##
## data: ts_seafood_stores_agrpd
## Dickey-Fuller = -7.3172, Lag order = 11, p-value = 0.01
## alternative hypothesis: stationary
# Reagrupa y suma los valores mensualmente
train_SF_monthly <- train_SF %>%
group_by(Mes = format(date, "%Y-%m")) %>%
summarise(Suma_sales = sum(sales))
train_SF_monthly
Pasando a datos mensuales la serie de Meat
# Reagrupa y suma los valores mensualmente
train_M_monthly <- train_M %>%
group_by(Mes = format(date, "%Y-%m")) %>%
summarise(Suma_sales = sum(sales))
train_M_monthly
ts_sf<-ts(train_SF_monthly$Suma_sales, frequency=12, start=c(2013,1))
autoplot(ts_sf,xlab="Year",ylab="Sales",main="Fig 2. Monthly Seafood Sales by Store #9")
print("ADF TEST IN SEAFOOD STORES")
## [1] "ADF TEST IN SEAFOOD STORES"
adf.test(ts_sf)
## Warning in adf.test(ts_sf): p-value smaller than printed p-value
##
## Augmented Dickey-Fuller Test
##
## data: ts_sf
## Dickey-Fuller = -4.5337, Lag order = 3, p-value = 0.01
## alternative hypothesis: stationary
ts_meat<-ts(train_M_monthly$Suma_sales, frequency=12, start=c(2013,1))
autoplot(ts_meat,xlab="Year",ylab="Sales",main="Fig 1. Meat Sales by Store #11")
print("ADF TEST IN ENTIRE TRAIN")
## [1] "ADF TEST IN ENTIRE TRAIN"
adf.test(train$sales)
## Warning in adf.test(train$sales): p-value smaller than printed p-value
##
## Augmented Dickey-Fuller Test
##
## data: train$sales
## Dickey-Fuller = -59.85, Lag order = 56, p-value = 0.01
## alternative hypothesis: stationary
print("ADF TEST IN TRAIN FOR MEAT STORES")
## [1] "ADF TEST IN TRAIN FOR MEAT STORES"
adf.test(ts_sf)
## Warning in adf.test(ts_sf): p-value smaller than printed p-value
##
## Augmented Dickey-Fuller Test
##
## data: ts_sf
## Dickey-Fuller = -4.5337, Lag order = 3, p-value = 0.01
## alternative hypothesis: stationary
print("ADF TEST IN TRAIN FOR LWR STORES")
## [1] "ADF TEST IN TRAIN FOR LWR STORES"
adf.test(ts_meat)
##
## Augmented Dickey-Fuller Test
##
## data: ts_meat
## Dickey-Fuller = -4.0972, Lag order = 3, p-value = 0.01181
## alternative hypothesis: stationary
Any of the previous series are stationary
arima_model_meat<-auto.arima(ts_meat, seasonal=FALSE, trace = TRUE);arima_model_meat
##
## ARIMA(2,0,2) with non-zero mean : Inf
## ARIMA(0,0,0) with non-zero mean : 1001.627
## ARIMA(1,0,0) with non-zero mean : 1001.425
## ARIMA(0,0,1) with non-zero mean : 1002.3
## ARIMA(0,0,0) with zero mean : 1262.941
## ARIMA(2,0,0) with non-zero mean : 1001.831
## ARIMA(1,0,1) with non-zero mean : 1003.306
## ARIMA(2,0,1) with non-zero mean : 1002.802
## ARIMA(1,0,0) with zero mean : Inf
##
## Best model: ARIMA(1,0,0) with non-zero mean
## Series: ts_meat
## ARIMA(1,0,0) with non-zero mean
##
## Coefficients:
## ar1 mean
## 0.2526 18615.3956
## s.e. 0.1597 312.4679
##
## sigma^2 = 3155040: log likelihood = -497.48
## AIC=1000.96 AICc=1001.42 BIC=1007.04
summary(arima_model_meat)
## Series: ts_meat
## ARIMA(1,0,0) with non-zero mean
##
## Coefficients:
## ar1 mean
## 0.2526 18615.3956
## s.e. 0.1597 312.4679
##
## sigma^2 = 3155040: log likelihood = -497.48
## AIC=1000.96 AICc=1001.42 BIC=1007.04
##
## Training set error measures:
## ME RMSE MAE MPE MAPE MASE
## Training set -0.1553562 1744.236 1187.169 -1.134558 6.984175 0.8080669
## ACF1
## Training set -0.03077421
arima_model_sf<-auto.arima(ts_sf, seasonal=FALSE, trace = TRUE);arima_model_sf
##
## ARIMA(2,0,2) with non-zero mean : 693.7419
## ARIMA(0,0,0) with non-zero mean : 707.9498
## ARIMA(1,0,0) with non-zero mean : 691.4349
## ARIMA(0,0,1) with non-zero mean : 693.2585
## ARIMA(0,0,0) with zero mean : 862.2849
## ARIMA(2,0,0) with non-zero mean : 689.9566
## ARIMA(3,0,0) with non-zero mean : 687.9348
## ARIMA(4,0,0) with non-zero mean : 689.8434
## ARIMA(3,0,1) with non-zero mean : 686.6628
## ARIMA(2,0,1) with non-zero mean : 684.6066
## ARIMA(1,0,1) with non-zero mean : 691.8809
## ARIMA(1,0,2) with non-zero mean : 691.5758
## ARIMA(3,0,2) with non-zero mean : Inf
## ARIMA(2,0,1) with zero mean : Inf
##
## Best model: ARIMA(2,0,1) with non-zero mean
## Series: ts_sf
## ARIMA(2,0,1) with non-zero mean
##
## Coefficients:
## ar1 ar2 ma1 mean
## 1.3685 -0.6598 -0.8163 503.5647
## s.e. 0.1237 0.1009 0.1310 8.9952
##
## sigma^2 = 10316: log likelihood = -336.7
## AIC=683.41 AICc=684.61 BIC=693.53
summary(arima_model_sf)
## Series: ts_sf
## ARIMA(2,0,1) with non-zero mean
##
## Coefficients:
## ar1 ar2 ma1 mean
## 1.3685 -0.6598 -0.8163 503.5647
## s.e. 0.1237 0.1009 0.1310 8.9952
##
## sigma^2 = 10316: log likelihood = -336.7
## AIC=683.41 AICc=684.61 BIC=693.53
##
## Training set error measures:
## ME RMSE MAE MPE MAPE MASE
## Training set 1.970454 97.87104 72.86849 -6.401792 18.66432 0.5745236
## ACF1
## Training set -0.02468026
Para ambos modelos se sugiere un modelo Autoregresivo de 1 y 2 lags con 0 diferenciaciones (dado que las series por si mismas son estacionarias) y con 1 y 0 retrasos en la media movil.
# Calculo de la Autocorrelación y Autocorrelación Parcial
acf(train_M_monthly$Suma_sales, lag.max = 50, plot = TRUE, main = "Serie Meat sales on store # 11 | Autocorrelation plot")
# Calculo de la Autocorrelación y Autocorrelación Parcial
pacf(train_M_monthly$Suma_sales, lag.max = 50, plot = TRUE, main = "Serie Meat sales on store # 11 | Partial autocorrelation plot")
Se puede interpretar de los anteriores plots, teníendo mayor peso el
PACF, que podemos emplear cuantos retrasos queramos, pero al querer
buscar un modelo no tan complejo podemos tomar uno o dos.
# Calculo de la Autocorrelación y Autocorrelación Parcial
acf(train_SF_monthly$Suma_sales, lag.max = 50, plot = TRUE, main = "Serie Seafood sales on store # 11 | Autocorrelation plot")
# Calculo de la Autocorrelación y Autocorrelación Parcial
pacf(train_SF_monthly$Suma_sales, lag.max = 50, plot = TRUE, main = "Serie Seafood sales on store # 11 | Partial autocorrelation plot")
Se puede interpretar de los anteriores plots, teníendo mayor peso el
PACF, que basta con uno o dos retrasos para explicar los valores
futuros.
# Calculo de la Autocorrelación y Autocorrelación Parcial
acf_values = acf(arima_model_meat$residuals, lag.max = 50, plot = TRUE, main = "Serie Meat sales on store # 11 | Autocorrelation plot")
acf_values
##
## Autocorrelations of series 'arima_model_meat$residuals', by lag
##
## 0.0833 0.1667 0.2500 0.3333 0.4167 0.5000 0.5833 0.6667 0.7500 0.8333 0.9167
## -0.031 0.181 -0.112 -0.118 -0.213 -0.110 -0.061 -0.109 0.057 0.053 0.105
## 1.0000 1.0833 1.1667 1.2500 1.3333 1.4167 1.5000 1.5833 1.6667 1.7500 1.8333
## 0.151 -0.004 0.039 -0.096 -0.177 -0.093 -0.107 -0.014 0.017 0.135 0.070
## 1.9167 2.0000 2.0833 2.1667 2.2500 2.3333 2.4167 2.5000 2.5833 2.6667 2.7500
## -0.023 0.046 -0.125 0.013 -0.018 -0.054 0.010 -0.038 0.139 0.004 0.252
## 2.8333 2.9167 3.0000 3.0833 3.1667 3.2500 3.3333 3.4167 3.5000 3.5833 3.6667
## -0.052 -0.077 -0.014 -0.126 -0.041 -0.011 0.125 -0.028 0.138 0.029 0.079
## 3.7500 3.8333 3.9167 4.0000 4.0833 4.1667
## -0.029 -0.060 -0.057 -0.049 -0.108 0.064
# Calculo de la Autocorrelación y Autocorrelación Parcial
pacf(arima_model_meat$residuals, lag.max = 50, plot = TRUE, main = "Serie Meat sales on store # 11 | Partial autocorrelation plot")
Se puede interpretar de los anteriores plots, teníendo mayor peso el
PACF, que no resulta ser significativo el incluir retrasos en MA.
# Calculo de la Autocorrelación y Autocorrelación Parcial
acf(arima_model_sf$residuals, lag.max = 50, plot = TRUE, main = "Serie Seafood sales on store # 9 | Autocorrelation plot")
# Calculo de la Autocorrelación y Autocorrelación Parcial
pacf(arima_model_sf$residuals, lag.max = 50, plot = TRUE, main = "Serie Seafood sales on store # 9 | Partial autocorrelation plot")
Se puede interpretar de los anteriores plots, teníendo mayor peso el
PACF, que podría ser significativo el incluir 5 retrasos en MA.
CUSUM_meat = cumsum(ts_meat - mean(ts_meat))
ts_CUSUM_meat = ts(CUSUM_meat, frequency=12, start=c(2013,1))
autoplot(ts_CUSUM_meat, xlab="Year",ylab="Sales (cumsum)",main="Fig 4. Cumulative sales, Meat products by Store #11")
CUSUM_sf = cumsum(ts_sf - mean(ts_sf))
ts_CUSUM_sf = ts(CUSUM_sf, frequency=12, start=c(2013,1))
autoplot(ts_CUSUM_sf, xlab="Year",ylab="Sales (cumsum)",main="Fig 4. Cumulative sales, Seafood products by Store #9")
autoplot(ts_CUSUM_sf) + geom_hline(yintercept = 0,color="blue") + labs(title="Cumulative Sum", x="year", y="percent in decimal")
# plot moving sum
MOSUM = rollapply(ts(ts_CUSUM_sf) - mean(ts_CUSUM_sf), 15, sum)
autoplot(MOSUM)+ geom_hline(yintercept = 0,color="blue")+labs(title="Moving Sum from 15 observations", x="year", y="percent in decimal")
# plot rec-cumsum (mean of all observations prior to given time)
rec_cusum <- numeric(length(ts_CUSUM_sf))
for (i in 1:length(ts_CUSUM_sf)){
rec_cusum[i] = mean(ts_CUSUM_sf[1:(i-1)])
}
rec_cusum2 = ts(rec_cusum, frequency=12, start=c(2013,1))
autoplot(rec_cusum2)+labs(title="Recursive Cumulative Sum", x="year", y="percent in decimal")
# calculate residual sum of squares
rss = sapply(5:(length(ts_CUSUM_sf)-5), function(i) {
before <- 1:i
after <- (i+1):length(ts_CUSUM_sf)
res <- c(Nile[before] - mean(Nile[before]), Nile[after] - mean(Nile[after]))
sum(res^2)
})
rss = ts(rss, frequency=12, start=c(2013,1))
autoplot(rss) + labs(title = "Fig3. Residual Sum of Squares",x="Year",y="RSS")
# find suspected breakpoint
breakpoint <- time(rss)[which.min(rss)]
plot(ts_CUSUM_sf, main='Fig 4. Cumsums Sales Seafood #9')
abline(v=breakpoint, col="red",lty=2)
#abline(v=1981, col="red",lty=2)
start_year = 2013
lines(ts(predict(lm((ts_CUSUM_sf[1:(breakpoint-start_year+1)]) ~ 1)),start=start_year,freq=1),col='darkgreen',lwd=2)
lines(ts(predict(lm((ts_CUSUM_sf[(breakpoint-start_year+1):length(ts_CUSUM_sf)]) ~ 1)),start=breakpoint,freq=1),col='darkgreen',lwd=2)
library(vars)
## Loading required package: MASS
##
## Attaching package: 'MASS'
## The following object is masked from 'package:dplyr':
##
## select
## Loading required package: lmtest
# Combina las series en un dataframe
data <- data.frame(ts_sf, ts_meat)
# Ajusta un modelo VAR
var_model <- VAR(data, p = 2)
# Resumen del modelo
summary(var_model)
##
## VAR Estimation Results:
## =========================
## Endogenous variables: ts_sf, ts_meat
## Deterministic variables: const
## Sample size: 54
## Log Likelihood: -803.213
## Roots of the characteristic polynomial:
## 0.5744 0.5744 0.4579 0.3272
## Call:
## VAR(y = data, p = 2)
##
##
## Estimation results for equation ts_sf:
## ======================================
## ts_sf = ts_sf.l1 + ts_meat.l1 + ts_sf.l2 + ts_meat.l2 + const
##
## Estimate Std. Error t value Pr(>|t|)
## ts_sf.l1 0.71692 0.14073 5.094 5.59e-06 ***
## ts_meat.l1 -0.01541 0.01185 -1.300 0.1998
## ts_sf.l2 -0.31902 0.14923 -2.138 0.0376 *
## ts_meat.l2 0.01630 0.01129 1.444 0.1551
## const 287.23357 265.98935 1.080 0.2855
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
##
## Residual standard error: 109.4 on 49 degrees of freedom
## Multiple R-Squared: 0.3733, Adjusted R-squared: 0.3222
## F-statistic: 7.298 on 4 and 49 DF, p-value: 0.0001081
##
##
## Estimation results for equation ts_meat:
## ========================================
## ts_meat = ts_sf.l1 + ts_meat.l1 + ts_sf.l2 + ts_meat.l2 + const
##
## Estimate Std. Error t value Pr(>|t|)
## ts_sf.l1 -2.747e+00 2.237e+00 -1.228 0.225320
## ts_meat.l1 6.458e-02 1.884e-01 0.343 0.733245
## ts_sf.l2 -2.096e+00 2.372e+00 -0.884 0.381082
## ts_meat.l2 2.621e-01 1.794e-01 1.461 0.150501
## const 1.502e+04 4.227e+03 3.554 0.000852 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
##
## Residual standard error: 1739 on 49 degrees of freedom
## Multiple R-Squared: 0.1635, Adjusted R-squared: 0.0952
## F-statistic: 2.394 on 4 and 49 DF, p-value: 0.0631
##
##
##
## Covariance matrix of residuals:
## ts_sf ts_meat
## ts_sf 11970 39821
## ts_meat 39821 3023423
##
## Correlation matrix of residuals:
## ts_sf ts_meat
## ts_sf 1.0000 0.2093
## ts_meat 0.2093 1.0000
# Impresión de la función de impulso-respuesta
irf <- irf(var_model, impulse = "ts_sf", response = c("ts_sf", "ts_meat"), boot = FALSE)
plot(irf)
# Impresión de la función de descomposición de la varianza
fevd <- fevd(var_model, n.ahead = 10)
plot(fevd)
Intepretaciones.
Se observa una relación positiva significativa entre las observaciones actuales de ts_sf y sus valores pasados, mientras que las observaciones pasadas de ts_meat no demuestran ser predictores significativos de ts_sf. Además, no se encuentran relaciones significativas entre las observaciones pasadas de ambas variables y las observaciones actuales de ts_meat. Aunque el modelo explica aproximadamente el 37.33% de la variabilidad en ts_sf y ts_meat, es crucial considerar la interpretación económica de estos resultados y la validez de las suposiciones del modelo VAR. La inclusión de términos determinísticos mejora la explicación de la variabilidad en las variables endógenas, y las matrices de covarianza y correlación de residuos proporcionan información sobre la relación lineal entre ts_sf y ts_meat. En resumen, estas conclusiones resaltan las relaciones estadísticamente significativas y no significativas entre las variables, subrayando la importancia de una evaluación completa y la consideración de modelos alternativos.
library(lmtest)
# Supongamos que tienes dos series de tiempo llamadas ts1 y ts2
# Realiza el test de Granger
result <- grangertest( ts_meat ~ ts_sf, order = 1)
print(result)
## Granger causality test
##
## Model 1: ts_meat ~ Lags(ts_meat, 1:1) + Lags(ts_sf, 1:1)
## Model 2: ts_meat ~ Lags(ts_meat, 1:1)
## Res.Df Df F Pr(>F)
## 1 52
## 2 53 -1 4.3022 0.04303 *
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
sarima_ts_sf = auto.arima(ts_sf, seasonal=TRUE, ic ="aic", trace=TRUE)
##
## ARIMA(2,0,2)(1,0,1)[12] with non-zero mean : 681.5956
## ARIMA(0,0,0) with non-zero mean : 707.7234
## ARIMA(1,0,0)(1,0,0)[12] with non-zero mean : 690.5295
## ARIMA(0,0,1)(0,0,1)[12] with non-zero mean : 689.4193
## ARIMA(0,0,0) with zero mean : 862.2108
## ARIMA(2,0,2)(0,0,1)[12] with non-zero mean : 680.4168
## ARIMA(2,0,2) with non-zero mean : 692.0276
## ARIMA(2,0,2)(1,0,0)[12] with non-zero mean : 683.4745
## ARIMA(1,0,2)(0,0,1)[12] with non-zero mean : 686.0802
## ARIMA(2,0,1)(0,0,1)[12] with non-zero mean : 678.4743
## ARIMA(2,0,1) with non-zero mean : 683.4066
## ARIMA(2,0,1)(1,0,1)[12] with non-zero mean : 679.8928
## ARIMA(2,0,1)(1,0,0)[12] with non-zero mean : 681.4801
## ARIMA(1,0,1)(0,0,1)[12] with non-zero mean : 686.6776
## ARIMA(2,0,0)(0,0,1)[12] with non-zero mean : 682.65
## ARIMA(3,0,1)(0,0,1)[12] with non-zero mean : 680.4204
## ARIMA(1,0,0)(0,0,1)[12] with non-zero mean : 688.6179
## ARIMA(3,0,0)(0,0,1)[12] with non-zero mean : 680.5057
## ARIMA(3,0,2)(0,0,1)[12] with non-zero mean : Inf
## ARIMA(2,0,1)(0,0,1)[12] with zero mean : 703.1701
##
## Best model: ARIMA(2,0,1)(0,0,1)[12] with non-zero mean
sarima_ts_sf
## Series: ts_sf
## ARIMA(2,0,1)(0,0,1)[12] with non-zero mean
##
## Coefficients:
## ar1 ar2 ma1 sma1 mean
## 1.3472 -0.6924 -0.7035 0.4859 498.9235
## s.e. 0.1365 0.0946 0.2048 0.1758 15.2166
##
## sigma^2 = 8761: log likelihood = -333.24
## AIC=678.47 AICc=680.19 BIC=690.63
Comparamos ambos modelos mediante el estadístico AIC, donde el modelo ARIMA(2,0,1) presenta un estadístico AIC 683.41, resultando ser mayor que el modelo SARIMA (2,0,1)(0,0,1)[12] con un AIC de 678.47.
forecast_values_arima <- forecast(arima_model_sf, h = 12)
plot(forecast_values_arima$x, main = "Fig 5. Observados vs. Predicciones | ARIMA", ylab = "Seafood sales", xlab=NA)
# Agregar las predicciones al gráfico
lines(forecast_values_arima$mean, col = "blue", lty = 2)
forecast_values_sarima <- forecast(sarima_ts_sf, h = 6)
plot(forecast_values_sarima$x, main = "Fig 6. Observados vs. Predicciones | SARIMA", ylab = "Seafood sales", xlab=NA)
# Agregar las predicciones al gráfico
lines(forecast_values_sarima$mean, col = "blue", lty = 2)
# 9 y 10) Multivario e Impacto de promociones
# Combina las series en un dataframe
train_promotions_monthly <- train_SF %>%
group_by(Mes = format(date, "%Y-%m")) %>%
summarise(Suma_promotions = sum(onpromotion))
ts_promotion<-ts(train_promotions_monthly$Suma_promotions, frequency=12, start=c(2013,1))
data <- data.frame(ts_promotion, ts_sf)
# Ajusta un modelo VAR
var_model_2 <- VAR(data, p = 2)
# Resumen del modelo
summary(var_model_2)
##
## VAR Estimation Results:
## =========================
## Endogenous variables: ts_promotion, ts_sf
## Deterministic variables: const
## Sample size: 54
## Log Likelihood: -495.929
## Roots of the characteristic polynomial:
## 0.8956 0.6065 0.4972 0.4972
## Call:
## VAR(y = data, p = 2)
##
##
## Estimation results for equation ts_promotion:
## =============================================
## ts_promotion = ts_promotion.l1 + ts_sf.l1 + ts_promotion.l2 + ts_sf.l2 + const
##
## Estimate Std. Error t value Pr(>|t|)
## ts_promotion.l1 0.259855 0.142531 1.823 0.07438 .
## ts_sf.l1 0.012688 0.007243 1.752 0.08606 .
## ts_promotion.l2 0.571859 0.147302 3.882 0.00031 ***
## ts_sf.l2 -0.006841 0.007288 -0.939 0.35252
## const -0.359878 3.650059 -0.099 0.92186
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
##
## Residual standard error: 5.661 on 49 degrees of freedom
## Multiple R-Squared: 0.6365, Adjusted R-squared: 0.6068
## F-statistic: 21.45 on 4 and 49 DF, p-value: 2.83e-10
##
##
## Estimation results for equation ts_sf:
## ======================================
## ts_sf = ts_promotion.l1 + ts_sf.l1 + ts_promotion.l2 + ts_sf.l2 + const
##
## Estimate Std. Error t value Pr(>|t|)
## ts_promotion.l1 -2.3963 2.8095 -0.853 0.397835
## ts_sf.l1 0.7095 0.1428 4.970 8.58e-06 ***
## ts_promotion.l2 1.9184 2.9035 0.661 0.511890
## ts_sf.l2 -0.2578 0.1437 -1.794 0.078916 .
## const 283.2009 71.9470 3.936 0.000261 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
##
## Residual standard error: 111.6 on 49 degrees of freedom
## Multiple R-Squared: 0.348, Adjusted R-squared: 0.2948
## F-statistic: 6.539 on 4 and 49 DF, p-value: 0.0002678
##
##
##
## Covariance matrix of residuals:
## ts_promotion ts_sf
## ts_promotion 32.05 65.32
## ts_sf 65.32 12453.09
##
## Correlation matrix of residuals:
## ts_promotion ts_sf
## ts_promotion 1.0000 0.1034
## ts_sf 0.1034 1.0000
# Impresión de la función de impulso-respuesta
irf <- irf(var_model_2, impulse = "ts_promotion", response = c("ts_promotion", "ts_sf"), boot = FALSE)
plot(irf)
# Impresión de la función de descomposición de la varianza
fevd <- fevd(var_model, n.ahead = 10)
plot(fevd)
Interpretación:
Efecto de las promociones (ts_promotion) en las ventas de Mariscos(ts_sf): - Coeficiente de ts_promotion.l1 = -2.3963 - Coeficiente de ts_promotion.l2 = 1.9184
Estos coeficientes indican cómo un cambio en ts_promotion en periodos anteriores afecta a ts_sf en periodos actuales y pasados. En este caso:
ts_promotion.l1 tiene un coeficiente negativo significativo (-2.3963), lo que sugiere que un aumento en ts_promotion en el periodo anterior está asociado con una disminución en ts_sf en el periodo actual. Este efecto es significativo al nivel de confianza seleccionado.
ts_promotion.l2 tiene un coeficiente positivo significativo (1.9184), indicando que un aumento en ts_promotion dos periodos atrás está asociado con un aumento en ts_sf en el periodo actual. Este efecto también es significativo al nivel de confianza seleccionado.
En resumen, según este modelo VAR, ts_promotion tiene una influencia significativa en ts_sf. Sin embargo, la dirección específica de la influencia (positiva o negativa) depende del periodo de tiempo considerado.
library(lmtest)
# Supongamos que tienes dos series de tiempo llamadas ts1 y ts2
# Realiza el test de Granger
result <- grangertest( ts_sf ~ ts_promotion, order = 2)
print(result)
## Granger causality test
##
## Model 1: ts_sf ~ Lags(ts_sf, 1:2) + Lags(ts_promotion, 1:2)
## Model 2: ts_sf ~ Lags(ts_sf, 1:2)
## Res.Df Df F Pr(>F)
## 1 49
## 2 51 -2 0.3642 0.6966