Hi
I am trying to write some code to backtest some spread trading ideas.
I have got this far:
library(xts)
library(quantmod)
library(foreach)
getCombined <- function(sym1, sym2, dateFilter='::')
{
# Grab historical data for both symbols
one <- getSymbols(sym1, auto.assign=FALSE)
two <- getSymbols(sym2, auto.assign=FALSE)
# Give columns more usable names
colnames(one) <- c('Open', 'High', 'Low', 'Close', 'Volume', 'Adjusted')
colnames(two) <- c('Open', 'High', 'Low', 'Close', 'Volume', 'Adjusted')
# Build combined object
return(merge(one$Close, two$Close, all=FALSE)[dateFilter])
}
sym1 <- 'CBA.AX'
sym2 <- 'NAB.AX'
spread <- getCombined(sym1, sym2)
chartSeries(spread, type='line',theme=chartTheme('white'),TA=NULL)
price <- spread$Close - spread$Close.1
m <- rollapply(price, 20, mean)
sd.2 <- rollapply(price, 20, sd)
upper.boundary <- m + sd.2
lower.boundary <- m - sd.2
spread.data <- merge(price$Close, m$Close, upper.boundary$Close,
lower.boundary$Close, all=FALSE)
# Give columns more usable names
colnames(spread.data) <- c('Close', 'Mean', 'Upper.Boundary',
'Lower.Boundary')
so now I have my time series and I want to iterate over it with rules like:
1. If the price exceeds 2 x standard deviation and then returns below
sell the spread
2. If I'm short and the price becomes smaller than the average buy the
spread
3. and so on
In other programming languages (except prolog which favors recursion) I
guess I would write some type of loop and iterate over the data but some
of these R functions seem to achieve wonderful results so I thought I
would post this to see if a loop was the way to go or if there was
something more elegant.
Any help most welcome.