I am having trouble backtesting a Bollinger Band strategy in R. The logic is that I want to take a short position if the Close is greater than the Upper Band and then close the position out when it crosses the Average. I also want to take a Long position if the Close is lower than the Lower Band, and Close the position when it crosses the Average. So far this is what I have:
bbands <- BBands(stock$Close, n=20,sd=2)
sig1 <- Lag(ifelse((stock$Close >bbands$up),-1,0))
sig2 <- Lag(ifelse((stock$Close <bbands$dn),1,0))
sig3 <- Lag(ifelse((stock$Close > bbands$mavg),1,-1))
sig <- sig1 + sig2
... This is where i am stuck, how do i use sig3
to get the desired results?
Now,
sig
is your position. If you have your position, you can calculate other things like number of trades, PnL, etc.