SVM in Forecasting

##################################################
###  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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值