1

I face the following simple trading strategy:

Buy: when the price of a stock is above the upper Bollinger band.

Sell: when the price of a stock is below the lower Bollinger band.

Hold: A buy signal has appeared, so we hold the stock until one re-allocation day a sell signal appears.

We only consider weekly re-allocation Dates using GSee's startpoints function.

require(quantmod)

# load stock data 
tickers <- c("IBM")
myEnv <- new.env()
getSymbols(tickers, from ="2012-01-03", to="2014-12-01", env=myEnv)

close.prices <- do.call(merge, eapply(myEnv, Cl))
close.prices <- close.prices[,pmatch(tickers,colnames(close.prices))]
colnames(close.prices) <- c("IBM")

# now apply the simple trading strategy
m <- merge(close.prices, BBands(close.prices, n=20, maType="SMA"))
m$sig[with(m, IBM > up) & index(m) %in% index(m)[startpoints(m, on="weeks")]] <- 1
m$sig[with(m, IBM < dn) & index(m) %in% index(m)[startpoints(m, on="weeks")]] <- 0
m$sig[1] <- 0
m <- na.locf(m)
sig <- m$sig

So far so good! Now, I there are more Price series I want to extract signals from:

tickers <- c("IBM","AAPL")
getSymbols(tickers, from="2012-01-01", to="2013-12-01")

close.prices <- do.call(merge, lapply(tickers, function(x) Cl(get(x))))
colnames(close.prices) <- c("IBM","APPLE")ยด

I want to apply the above trading strategy to this portfolio of assets without defining a matrix (here 'm') for each individual asset. I am used to think in loops but there surely is a much more elegant method that avoids looping.

The result should look something like this:

> sig[100:110]
           IBM APPLE
2012-05-24   1     0
2012-05-25   1     0 
2012-05-29   1     0 
2012-05-30   1     0 
2012-05-31   1     0 
2012-06-01   1     0 
2012-06-04   0     0 
2012-06-05   0     0 
2012-06-06   0     0 
Pat
  • 1,299
  • 4
  • 17
  • 40

0 Answers0