Skip to content

Instantly share code, notes, and snippets.

@evenv
Created July 2, 2012 22:26
Show Gist options
  • Save evenv/3036127 to your computer and use it in GitHub Desktop.
Save evenv/3036127 to your computer and use it in GitHub Desktop.
R seasonal forecasting service in Rook
app <- function(env){
req <- Rook::Request$new(env)
res <- Rook::Response$new()
inputData <- gsub("##","\n",req$POST()[['data']])
write(inputData, file = "inputData.txt")
d <- read.table( "inputData.txt", sep=",", header=TRUE, row.names=1 )
d.startY <- as.integer( substr( row.names(d)[1], 1, 4 ) )
d.startM <- as.integer( substr( row.names(d)[1], 6, 7 ) )
d.ts <- ts( d, start=c(d.startY,d.startM), frequency=12 )
library(forecast)
d.hw <- HoltWinters(d.ts, beta=TRUE, gamma=TRUE, seasonal="additive")
d.forecast <- forecast(d.hw)
lastval = window(d.ts,start=end(d.ts),end=end(d.ts))
combined = ts.union(lastval,d.forecast$mean)
combined[ is.na(combined) ] <- 0
combined <- combined[,1]+combined[,2]
output <- combined
names <- as.character(as.Date(time(output)),format="%Y-%m")
write.table(output,file="outputData.txt",row.names=names,
col.names=FALSE,eol="##",sep=",",quote=FALSE)
outputData <- scan("outputData.txt",what="character")
res$write(outputData)
res$finish()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment