There are many techniques we could employ when trying to predict the future, such as moving average (MA), regression, auto-regression, and the like. First, let's start with the simplest one for a moving average:
movingAverageFunction<- function(data,n=10){ out= data for(i in n:length(data)){ out[i] = mean(data[(i-n+1):i]) } return(out)}
In the preceding program, the default value for the number of periods is 10. We could use the dataset called MSFT included in the R package called timeSeries (see the code that follows):
> library(timeSeries)> data(MSFT)> p<-MSFT$Close> #> ma<-movingAverageFunction(p,3)> head(p)[1] 60.6250 61.3125 60.3125 59.1250 56.5625 55.4375> head(ma)[1] 60.62500 61.31250 60.75000 60.25000 58.66667 ...