I've imported price data for the S&P500 for the last 20 years and created a separate XTS containing only the close price for each day. I now need to create a loop that goes through the data and records every time the price has declined for three days in a row.
This is the code I entered with the aim of returning a vector that has a value of 1 every time there is a straight three-day decline in the price, and 0 other wise.
# Create an empty vector to store the results
result2 <- numeric(length(SPY.Close))
# Loop through the time series and check if each value has declined three times in a row
for(i in 3:length(SPY.Close)){
if(SPY.Close[i] < SPY.Close[i-1] && SPY.Close[i-1] < SPY.Close[i-2]){
result2[i] <- 1
} else {
result2[i] <- 0
}
}
However, I keep getting the following error:
Error in if (SPY.Close[i] < SPY.Close[i - 1] && SPY.Close[i - 1] < SPY.Close[i - :
missing value where TRUE/FALSE needed
I've googled using the is.na function, but not sure how to implement it in my code