R Nos puede ser de gran ayuda para implementar el método Holt-Winter de filtrado y pronóstico. se usan las funcionalidades HoltWinter y predict.HoltWinter, para pronosticar cifras bajo demanda basadas en datos históricos. El uso de las funciones de HoltWinter en R es bastante sencillo.

Digamos que nuestro data set se ve de la siguiente manera:

demand <- ts(BJsales, start = c(2000, 1), frequency = 12)
plot(demand)

Ahora se pasa la serie temporal a HoltWinter y se trazan los datos ajustados.

hw <- HoltWinters(demand)
plot(hw)

A continuación, calculamos la previsión a 12 meses con un intervalo de confianza de 0,95 y trazamos el pronóstico junto con los valores reales y ajustados.

forecast <- predict(hw, n.ahead = 12, prediction.interval = T, level = 0.95)
plot(hw, forecast)

Como se observa en los ejemplos anteriores, la función es bastante fácil de utilizar. Para hacer un análisis más certero de las predicciones usando el método Holt-Winters, se puede usar el paquete ggplot2 que provee gráficas mucho más descriptivas visualmente hablando.

He aquí una pequeña función que extrae algunos datos de los objetos HoltWinter y predict.HoltWinter y los alimenta a ggplot2:

#HWplot3.R
 
library(ggplot2)
library(reshape)
 
 
HWplot3<-function(ts_object,  n.ahead=4,  CI=.95,  error.ribbon='green', line.size=1){
     
    hw_object<-HoltWinters(ts_object)
     
    forecast<-predict(hw_object,  n.ahead=n.ahead,  prediction.interval=T,  level=CI)
     
     
    for_values<-data.frame(time=round(time(forecast),  3),  value_forecast=as.data.frame(forecast)$fit,  dev=as.data.frame(forecast)$upr-as.data.frame(forecast)$fit)
     
    fitted_values<-data.frame(time=round(time(hw_object$fitted),  3),  value_fitted=as.data.frame(hw_object$fitted)$xhat)
     
    actual_values<-data.frame(time=round(time(hw_object$x),  3),  Actual=c(hw_object$x))
     
     
    graphset<-merge(actual_values,  fitted_values,  by='time',  all=TRUE)
    graphset<-merge(graphset,  for_values,  all=TRUE,  by='time')
    graphset[is.na(graphset$dev),  ]$dev<-0
     
    graphset$Fitted<-c(rep(NA,  NROW(graphset)-(NROW(for_values) + NROW(fitted_values))),  fitted_values$value_fitted,  for_values$value_forecast)
     
     
    graphset.melt<-melt(graphset[, c('time', 'Actual', 'Fitted')], id='time')
     
  p<-ggplot(graphset.melt,  aes(x=time,  y=value)) + geom_ribbon(data=graphset, aes(x=time, y=Fitted, ymin=Fitted-dev,  ymax=Fitted + dev),  alpha=.2,  fill=error.ribbon) + geom_line(aes(colour=variable), size=line.size) + geom_vline(xintercept=max(actual_values$time),  lty=2) + xlab('Time') + ylab('Value') + labs(legend.position='bottom') + scale_colour_hue('')
    return(p)
 
}

Antes de continuar, es importante guardar el script anterior en el directorio de trabajo (Working Directory). Ahora procedemos a llamarel Script que hemos llamado para este trabajo Hwplot3 y nos devolverá una gráfica mucho más clara:

source("HWplot3.R")
demand <- ts(BJsales, start = c(2000, 1), frequency = 12)
HWplot3 (demand, n.ahead = 12)
## Warning: Ignoring unknown aesthetics: y
## Warning: Removed 24 rows containing missing values (geom_path).

Ahora es muy fácil ajustar la gráfica a placer una vez que la tenemos creada:

graph <- HWplot3(demand, n.ahead = 12, error.ribbon = "red")
## Warning: Ignoring unknown aesthetics: y
# add a title
graph <- graph + labs(title = "Ejemplo de Predicciones Holt-Winters ggplot2")

# change the x scale a little
graph <- graph + scale_x_continuous(breaks = seq(1998, 2015))

# change the y-axis title
graph <- graph + ylab("Demanda ($)")

# change the x-axis title
graph <- graph + xlab("Tiempo")

# change the colour of the lines
graph <- graph + scale_colour_brewer("Valores", palette = "Set1")
## Scale for 'colour' is already present. Adding another scale for
## 'colour', which will replace the existing scale.
# the result:
graph
## Warning: Removed 24 rows containing missing values (geom_path).

Este trabajo está basado en “Holt-Winters forecast using ggplot2” el 16 de Julio de 2012 en r-bloggers.com.