##################################################
### Preparation
##################################################
library(quantmod)
library(randomForest)
library(nnet) # for ANN model
library(DMwR)
library(e1071)
library(earth)
library(zoo)
library(TTR)
library(forecast)
##################################################
### Forecast based on SVM
##################################################
## download data set
getSymbols("^GDAXI",from="2009-01-01",to="2012-05-31")
GDAXI=as.data.frame(GDAXI)
colnames(GDAXI) = c("Open", "High", "Low", "Close","Volume","AdjClose")
attach(GDAXI)
## set daily Close as response variable
CLO=GDAXI$Close
## also set daily Close as regressor
VOL=GDAXI$Close
## loop for SVR modeling with sliding window
## for every window use 90 points as training set
## with following loop totally we construct 700 models using sliding method
list1=list(lm)
## NOTICE: THIS LOOP WILL COST 18 MINUTES BECAUSE OF GRID SEARCH OF SVM
for (i in 1:700)
{
list1[[i]]=best.svm(x=VOL[i:(i+89)],y=CLO[(i+1):(i+90)],gamma = 2^(-1:1), cost = 2^(2:4)
}
## perform 1-step ahead forecast
PRE=numeric(length=700)
for (i in 1:700)
{
PRE[i]=predict(list1[[i]],VOL[i+90])
}
mean(abs(PRE-CLO[92:791])) # MAE
mean((PRE-CLO[92:791])^2) # MSE
sqrt(mean((PRE-CLO[92:791])^2) ) # RMSFE
## time series plot: DAX Index vs SVR-Forecast
timematrix=cbind(PRE,CLO[92:791])
timedata=ts(timematrix)
Index=window(timedata[,1:2])
plot(Index,plot.type="single",lty=2:1,col=2:1,main="DAX Index and SVR-Forecast")
legend(0,7500,c("SVR-Forecast","DAX Index"),col=c(2,1),lty=2:1)
##################################################
### Forecast based on ARIMA
##################################################
## set daily Close as response variable for ARIMA model
CLO1=GDAXI$Close
##
list11=list(lm)
## loop for ARIMA modeling with the function auto.arima()
## in package "forecast" by Rob J. Hyndman
## using daily Close of 90 trading days as training set
## totally we construct 700 models with sliding window
for (i in 1:700)
{
list11[[i]]=auto.arima(CLO1[(i+1):(i+90)])
}
PRE1=numeric(700)
## loop for forecast with 1-step ahead method
for (i in 1:700)
{
PRE1[i]=forecast(list11[[i]],h=1)$mean
}
mean(abs(PRE1-CLO1[92:791])) # MAE
mean((PRE1-CLO1[92:791])^2) # MSE
sqrt(mean((PRE1-CLO1[92:791])^2) ) #RMSFE
## time series plot with 3 curves "SVR-Forecast","ARIMA-Forecast","DAX Index"
timematrix=cbind(PRE,PRE1,CLO1[92:791])
timedata=ts(timematrix)
Index1=window(timedata[,1:3])
plot(Index1,plot.type="single",lty=3:1,col=3:1,main="DAX Index, SVR-Forecast and ARIMA-Forecast")
legend(0,7500,c("SVR-Forecast","ARIMA-Forecast","DAX Index"),col=3:1,lty=3:1)
SVM in Forecasting
最新推荐文章于 2024-10-20 13:54:54 发布