I'm constructing a trading strategy and am stuck at two key areas. When using Stoch and MACD in quantmod
, I am trying to create a signal when the slow stochastic crosses over the fast stochastic (1), and visa-versa(-1), and flat when in between (0). MACD the code is identical except with the column names MACD and Signal. Lastly, I am trying to merge the three signals to create a master signal when all three signals equal 1, -1, 0.
library(quantmod)
####################
## BOLINGER BANDS ##
####################
getSymbols("SPY", src="yahoo", from="2013-01-01", to="2015-05-01")
x <- na.omit(merge(SPY, BBands(Cl(SPY))))
x$sig <- NA
# Flat where Close crossed the mavg
x$sig[c(FALSE, diff(sign(Cl(x) - x$mavg), na.pad=FALSE) != 0)] <- 0
x$sig[Cl(x) > x$up] <- -1 # short when Close is above up
x$sig[Cl(x) < x$dn] <- 1 # long when Close is below dn
x$sig[1] <- 0 # flat on the first day
x$sig[nrow(x)] <- 0 # flat on the last day
# Fill in the signal for other times
x$sig <- na.locf(x$sig) # wherever sig is NA, copy previous value to next row
# Now Lag your signal to reflect that you can't trade on the same bar that
# your signal fires
x$sig <- Lag(x$sig)
x$sig[1] <- 0 # replace NA with zero position on first row
####################
### STOCHASTICS ####
####################
y <- na.omit(merge(SPY, stoch(Cl(SPY))))
y$sig <- NA
# Flat where between crosses. Not sure how to write
#y$sig[c(FALSE, diff(sign(y$slowD == y$fastD), na.pad=FALSE !=0)] <- 0
y$sig[y$fastD > y$slowD] <- -1 # short when Close is above up
y$sig[y$fastD < y$slowD] <- 1 # long when Close is below dn
y$sig[1] <- 0 # flat on the first day
y$sig[nrow(x)] <- 0 # flat on the last day
# Fill in the signal for other times
y$sig <- na.locf(y$sig) # wherever sig is NA, copy previous value to next row
# Now Lag your signal to reflect that you can't trade on the same bar that
# your signal fires
y$sig <- Lag(y$sig)
y$sig[1] <- 0
####################
###### MACD ########
####################
z <- na.omit(merge(SPY, MACD(Cl(SPY))))
z$sig <- NA
# Flat where between crosses. Not sure how to write
z$sig[c(FALSE, diff(sign(z$signal == z$macd), na.pad=FALSE) != 1)] <- 1
z$sig[z$signal > z$macd] <- -1 # short when Close is above up
z$sig[z$signal < z$macd] <- 1 # long when Close is below dn
z$sig[1] <- 0 # flat on the first day
z$sig[nrow(z)] <- 0 # flat on the last day
# Fill in the signal for other times
z$sig <- na.locf(z$sig) # wherever sig is NA, copy previous value to next row
# Now Lag your signal to reflect that you can't trade on the same bar that
# your signal fires
z$sig <- Lag(z$sig)
z$sig[1] <- 0
# Merge xyz by date and create new signal when all three conditions are met