#************************************************************ # Smoothing and Decompostion of Time Series R #------------------------------------------------------------ # Financial Market Forecasting model rm(list=ls()) library(quantmod) library("forecast") myForc <- function(x,f1) { x_m <- meanf(x, h=f1) # Naive x_naive = naive(x,level=c(90,95),h=f1) # Random Walk with Drift x_rd = rwf(x,drift=T,level=c(90,95),h=f1) # Holt Exponential Smooth Method x_h <- holt(x,h=f1, exponential = FALSE) # Holt-Winters Smooth Method x_hwest <- HoltWinters(x,gamma=FALSE) x_hw <- forecast(x_hwest,h=f1) # Neural Network Method x_nnest <- nnetar(x) x_nn <- forecast(x_nnest,h=f1) out_test <- rbind(accuracy(x_naive),accuracy(x_rd),accuracy(x_h),accuracy(x_hw),accuracy(x_nn)) row.names(out_test) <- c("Naive","Random Walk","Holt Exp","Holt_Winters","Neural Net") return(out_test) } # Here is the unemployment rate without seasonal adjustment getSymbols("UNRATENSA", src = "FRED") unemp = UNRATENSA chartSeries(unemp, theme="white") unempts <- ts( unemp, start=1948-1-1, frequency=12) unempcomp <- (decompose(unempts)) plot(unempcomp) forc_unemp <- myForc(unemp,20) forc_unemp # Random Number Cases x_random = rnorm(1000,1,1) x_train <- ts(x_random,start=1, end=990, frequency=1) x_test <- ts(x_random,start=991, end=1000, frequency=1) ts.plot(x_random) forc_x_in <- myForc(x_train,10) forc_x_in f1 = 10 # Holt Exponential Smooth Method x_h <- holt(x_train,h=f1, exponential = FALSE) x_hffit <- predict(x_h,x_test) e_hfe <- x_ts - x_hffit$mean[1:f1] all_error <- cbind(x_test,x_hffit$mean[1:f1],e_hfe) all_error ts.plot(x_test,e_hfe, col=c("blue","red")) # Holt-Winters Exponential Smooth Method x_hw <- HoltWinters(x_train,gamma=FALSE) x_hwffit <- predict(x_hw,x_test) e_hwfe <- x_test - x_hwffit$mean[1:f1] ts.plot(x_test,e_hfe,e_hwfe, col=c("blue","yellow","red"))