I am using R moving average crossover backtest script from eickonomics. But I have a question about this section.
#Calculate the moving averages and lag them one day to prevent lookback bias
PreviousSMA_50 <- lag(SMA(Cl(data[['SPY']]),50))
PreviousSMA_200 <- lag(SMA(Cl(data[['SPY']]),200))
.
.
data$weight[] = ifelse(as.integer(PreviousSMA_50>PreviousSMA_200)==1,1,0) #If price of SPY is above the SMA then buy
Why does the author need to lag the SMA values? Why can't he simply use unlagged values?
PreviousSMA_50 <- SMA(Cl(data[['SPY']]),50)
PreviousSMA_200 <- SMA(Cl(data[['SPY']]),200)
.
.
data$weight[] = ifelse(as.integer(PreviousSMA_50>PreviousSMA_200)==1,1,0)
Why would we use previous SMA value instead of current SMA value? How does it cause lookahead bias?
If we need other indicators do we have to lag those values as well?
rsi<-RSI(Cl(data[['SPY']]),50)
roc<-ROC(Cl(data[['SPY']]),50)