Guest User

Untitled

a guest
Oct 19th, 2018
113
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.53 KB | None | 0 0
  1. #Setup
  2. rm(list = ls(all = TRUE))
  3. setwd('path.to/cv.ts')
  4.  
  5. #Load Packages
  6. require(forecast)
  7. require(doParallel)
  8. source('R/cv.ts.R')
  9. source('R/forecast functions.R')
  10.  
  11. #Download S&P 500 data and adjust from splits/dividends
  12. library(quantmod)
  13. getSymbols('^GSPC', from='1990-01-01')
  14. GSPC <- adjustOHLC(GSPC, symbol.name='^GSPC')
  15.  
  16. #Calculate monthly returns
  17. GSPC <- to.monthly(GSPC, indexAt='lastof')
  18. GSPC <- Cl(GSPC)
  19.  
  20. #Convert from xts to ts
  21. GSPC <- ts(GSPC, start=c(1990,1), frequency=12)
  22.  
  23. #Start a cluster to speed up cross validaiton
  24. cl <- makeCluster(4, type='SOCK')
  25. registerDoParallel(cl)
  26.  
  27. #Define cross validation parameters
  28. myControl <- tseriescontrol(
  29. minObs=60,
  30. stepSize=1,
  31. maxHorizon=12,
  32. fixedWindow=TRUE,
  33. preProcess=FALSE,
  34. ppMethod='guerrero',
  35. summaryFunc=tsSummary
  36. )
  37.  
  38. #Forecast using several models
  39. result_naive <- cv.ts(GSPC, naiveForecast, myControl)
  40. myControl$preProcess <- TRUE
  41. result_autoarima <- cv.ts(GSPC, auto.arimaForecast, myControl, ic='bic')
  42. result_ets <- cv.ts(GSPC, etsForecast, myControl, ic='bic')
  43.  
  44. #Stop cluster
  45. stopCluster(cl)
  46.  
  47. #Plot error
  48. require(reshape2)
  49. require(ggplot2)
  50. plotData <- data.frame(
  51. horizon=1:12
  52. ,naive =result_naive$results$MAPE[1:12]
  53. ,arima=result_autoarima$results$MAPE[1:12]
  54. ,ets=result_ets$results$MAPE[1:12]
  55. )
  56. plotData <- melt(plotData, id.vars='horizon', value.name='MAPE', variable.name='model')
  57. ggplot(plotData, aes(horizon, MAPE, color=model)) + geom_line()
Add Comment
Please, Sign In to add comment