**The Average Investor's Blog » R**, and kindly contributed to R-bloggers)

In the last post I showed how to pick the parameters for the ARMA model. The next step is to determine the position at the close. One way to do that is by a one day ahead prediction, if the prediction comes negative (remember the series we are operating on is the daily returns) then the desired position is short, otherwise it’s long.

library(quantmod) library(fArma) getSymbols("SPY", from="1900-01-01") SPY.rets = diff(log(Ad(SPY))) SPY.arma = armaFit(~arma(0, 2), data=as.ts(tail(SPY.rets,500))) predict(SPY.arma, n.ahead=1, doplot=F)

Now, to build an indicator for back testing, one can walk the daily return series and at each point perform the steps we covered so far. The main loop looks like (in pseudocode):

for(ii in history:length(dailyRetSeries)) { tt = as.ts(tail(head(dailyRetSeries, ii), history)) ttArma = findBestArma() predict(ttArma, n.ahead=1, doplot=F) }

Where *history* is the look-back period to consider at each point, I usually use 500, which is about two years of data. Although the above code is simply an illustration, I hope the main idea is pretty clear by now.

As mentioned earlier, *findBestArma* needs to be surrounded by a *tryCatch* block. Same goes for the *predict* – it may fail to converge. What I do is to have *predict* included in *findBestArma*, ignoring models for which the prediction fails.

Another improvement is to use ARMA together with GARCH. The latter is a powerful method to model the clustered volatility typically found in financial series. Sounds complex, but it turns out to be pretty straightforward in R. Just to give you an idea:

library(quantmod) library(fGarch) getSymbols("SPY", from="1900-01-01") SPY.rets = diff(log(Ad(SPY))) SPY.garch = garchFit(~arma(0, 2) + garch(1, 1), data=as.ts(tail(SPY.rets, 500))) predict(SPY.garch, n.ahead=1, doplot=F)

That’s all I have to say on the theoretical side. I will finish this series with more implementation details and some back testing results in the next post …

**leave a comment**for the author, please follow the link and comment on their blog:

**The Average Investor's Blog » R**.

R-bloggers.com offers

**daily e-mail updates**about R news and tutorials on topics such as: visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...