I'm having trouble referencing conditions that take place in multiple rows using a for loop.
The idea is as follows. There is a dataframe with columns LastPrice and KCT. Want to add SignalBinary column to the dataframe, and if
1) LastPrice[j] > KCT[j] in any 3 consecutive rows, &
2) LastPrice[j+1] - LastPrice [j+1+3] > 12 in any of rows j+1 to j+1+10 (i.e. 10 rows below)
then want to record a 1 in SignalBinary[i].
df <- data.frame(nrow =20, ncol =2)
df <- data.frame(LastPrice = c(1221,1220,1220,1217,1216,1218,1216,1216,1217,1220,1219,1218,1220,1216,1217,1218,1218,1207,1206,1205), KCT = c(1218,1218,1219,1218,1221,1217,1217,1216,1219,1216,1217,1216,1219,1217,1218,1217,1217,1217,1219,1217))
df$SignalBinary <-for(j in1:20){for(i in1:10){ifelse (df$LastPrice[j]> df$KCT[j]& df$LastPrice[j+1]> df$KCT[j+1]& df$LastPrice[j+2]> df$KCT[j+2]& df$LastPrice[j+i]- df$LastPrice[j+i+3]>12,1,0)}}
Based on the data, would have expected the code to record a 1 in rows 10 and 11, and 0s in the rest. But I'm doing something wrong. Running the code does not give an error message, but it does not create df$SignalBinary. Running df$SignalBinary says NULL.
BTW the purpose of this is to apply the code to a large database of prices, to run statistics on binary signals.
Hope someone may help. Thank you very much