Google Example

library(quantmod)
## Loading required package: xts
## Loading required package: zoo
## 
## Attaching package: 'zoo'
## 
## The following objects are masked from 'package:base':
## 
##     as.Date, as.Date.numeric
## 
## Loading required package: TTR
## Version 0.4-0 included new data defaults. See ?getSymbols.
library(forecast)
## Loading required package: timeDate
## This is forecast 6.1
from.dat <- as.Date("01/01/08", format="%m/%d/%y")
to.dat <- as.Date("12/31/13", format="%m/%d/%y")
getSymbols("IBM",src="google",from = from.dat, to=to.dat)
##     As of 0.4-0, 'getSymbols' uses env=parent.frame() and
##  auto.assign=TRUE by default.
## 
##  This  behavior  will be  phased out in 0.5-0  when the call  will
##  default to use auto.assign=FALSE. getOption("getSymbols.env") and 
##  getOptions("getSymbols.auto.assign") are now checked for alternate defaults
## 
##  This message is shown once per session and may be disabled by setting 
##  options("getSymbols.warning4.0"=FALSE). See ?getSymbols for more details.
## [1] "IBM"

Summarize monthly and store as time series

mIBM <- to.monthly(IBM)
IBMOpen<- Op(mIBM)
ts1<- ts(IBMOpen,frequency=12)
plot(ts1,xlab="Years+1",ylab="IBM")

#Decomplose a time series into parts

plot(decompose(ts1),xlab="Years+1")

#Trend - Consistently increasing pattern over time
#Seasonal - When there is a pattern over a fixed period of time that recurs.
#Cyclic - When data rises and falls over non fixed periods

Training and test sets

ts1Train<- window(ts1,start=1,end=5)##time point 1 and end in time point 5(1st year~5th year)
ts1Test<- window(ts1,start=5,end=(7-0.01))#Time point 5 and end in time point 6
## Warning in window.default(x, ...): 'end' value not changed
ts1Train
##      Jan    Feb    Mar    Apr    May    Jun    Jul    Aug    Sep    Oct
## 1 108.99 107.16 113.86 115.20 121.06 128.49 117.50 128.52 122.87 115.51
## 2  83.89  90.60  91.17  96.13 103.78 106.94 105.00 118.88 117.67 119.39
## 3 131.18 123.23 127.50 128.95 129.39 124.69 123.55 129.25 125.31 135.51
## 4 147.21 162.11 163.15 163.70 172.11 168.90 171.61 182.60 172.71 174.36
## 5 186.73                                                               
##      Nov    Dec
## 1  92.64  80.95
## 2 120.77 127.29
## 3 143.64 143.61
## 4 181.55 187.01
## 5

Simple moving average

library(forecast)
plot(ts1Train)
lines(ma(ts1Train,order=3),col="red")

#Exponential smoothing

ets1<- ets(ts1Train,model="MMM")
fcast<- forecast(ets1)
plot(fcast)
lines(ts1Test,col="red")

#Get the accuracy

accuracy(fcast,ts1Test)
##                       ME      RMSE       MAE         MPE      MAPE
## Training set   0.7778437  6.066221  4.657389   0.3968409  3.768888
## Test set     -23.1888494 29.852942 24.232307 -12.1282246 12.636419
##                   MASE      ACF1 Theil's U
## Training set 0.1668232 0.2550114        NA
## Test set     0.8679781 0.7842383  3.607814