data-raw/script.R

library(fpp)
library(forecast)
library(plyr)
library(dplyr)
library(tidyr)
library(dygraphs)
library(ggplot2)

# VisualizaĆ§Ć£o

plots <- euretail %>%
  stl(4) %>%
  first() %>%
  alply(2, I) %>%
  lapply(function(x) {
    x %>%
      dygraph() %>%
      dySeries('V1', strokeWidth = 2)
  }) %>%
  setNames(c('seasonal', 'trend', 'error'))
plots$original <- euretail %>%
  dygraph() %>%
  dySeries('V1', strokeWidth = 2)

data.frame(Retail = as.numeric(euretail),
           Seasonal = stl(euretail, 4)[[1]][, 1],
           Trend = stl(euretail, 4)[[1]][, 2],
           Error = stl(euretail, 4)[[1]][, 3],
           Year = attributes(euretail)$tsp %>% {seq(.[1], .[2], 1 / .[3])}) %>%
  ggplot(aes(x = Year, y = Retail)) +
  geom_line() +
  scale_x_continuous(breaks = 1980:2015)

data.frame(Retail = as.numeric(euretail),
           Seasonal = stl(euretail, 4)[[1]][, 1],
           Trend = stl(euretail, 4)[[1]][, 2],
           Error = stl(euretail, 4)[[1]][, 3],
           Year = attributes(euretail)$tsp %>% {seq(.[1], .[2], 1 / .[3])}) %>%
  dplyr::select(-Retail) %>%
  gather(Parcial, val, -Year) %>%
  ggplot(aes(x = Year, y = val)) +
  geom_line() +
  facet_wrap(~Parcial, scales = 'free_y', ncol = 1) +
  scale_x_continuous(breaks = 1980:2015)

# Modelagem

###############################################################################

euretail
plot(stl(euretail, 4))

par(las = 1)

tsdisplay(diff(euretail, 4))
tsdisplay(diff(diff(euretail, 4)))

# fit <- Arima(euretail, order = c(1,1,0), seasonal = c(1,1,0))
fit <- Arima(euretail, order = c(0,1,1), seasonal = c(0,1,1))
tsdisplay(residuals(fit))

fit3 <- Arima(euretail, order = c(0,1,3), seasonal = c(0,1,1))
tsdisplay(residuals(fit3))

Box.test(res, lag = 16, fitdf = 4, type = "Ljung")
plot(forecast(fit3, h = 12))

fit4 <- auto.arima(euretail)
plot(forecast(fit4, h = 12))

###############################################################################
jtrecenti/gpim documentation built on May 20, 2019, 3:17 a.m.