quantmod - Bollinger Strategy in R with Entry and Exit Signals at Re-allocation Dates -


i have following simple trading strategy:

entry signal: when price of ibm above upper bollinger band.

close signal: when price of ibm below lower bollinger band.

here bollinger bands:

require(quantmod)  # load ibm 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")  # extract upper , lower bollinger band ttr's bbands function bb.up = bbands(close.prices, n=20, matype = sma)[,3]  bb.dn = bbands(close.prices, n=20, matype = sma)[,1] 

the tricky part close position only if price of ibm below lower bollinger band @ re-allocation date. otherwise roll signal of last period next period. accomplish weekly re-allocation:

# apply startpoints function pick week's first trading day  # re-allocating portfolio  startpoints = function (x, on = "weeks", k = 1) {   head(endpoints(x, on, k) + 1, -1) }  sig.bb.up = ifelse(close.prices > bb.up, 1, 0) sig.bb.up = sig.bb.up[startpoints(bb.up),]  sig.bb.dn = ifelse(close.prices < bb.dn, 1, 0) sig.bb.dn = sig.bb.dn[startpoints(bb.dn),] 

the whole question how define coded signal function sig.bb contains "1" price above upper bollinger band @ re-allocation date, then holds stock until price below lower bollinger band @ following re-allocation date.

what have tried catch frist observation , roll following observations based on first entry of sig.bb vector

sig.bb = ifelse(index(close.prices[1,1]) == "2012-01-03", sig.bb.up,                 ifelse(close.prices > bb.up, 1,                        ifelse(close.prices < bb.dn, 0, lag(sig.bb)))) 

which returns "na"...

how proceed (for interested in topic) after sig.bb obtained can found here: equally weighted reallocation of stock portfolio @ specific dates according signal

i'm not sure want output be, see if close

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 na.locf(m) 

Comments

Popular posts from this blog

java - Plugin org.apache.maven.plugins:maven-install-plugin:2.4 or one of its dependencies could not be resolved -

Round ImageView Android -

How can I utilize Yahoo Weather API in android -