dimanche 24 avril 2016

Record binary signal only if row below contains no signal (if clause issue)

I have 9x3 dataframe DATA, where one column has timestamps (DateTime), one prices (Close), and one binary values (FOMCBinary).

I want to add column SignalBinary recording a 1 IF Close < an X value (1129 in this example) AND FOMCBinary > 0 in any of the two rows below, but only if SignalBinary = 0 in the row below (i.e. do not want consecutive 1s).

In the example here I need to record a 1 under SignalBinary only at 14:45:00. My coding attempt is instead recording a 1 at 14:45:00 and at 15:00:00. Should be fairly simple, don't understand why my code is not producing the desired result. How could I get this fixed?

DATA <- structure(list(DateTime = structure(list(sec = c(0, 0, 0, 0,0, 0, 0, 0, 0), min = c(30L, 15L, 0L, 45L, 30L, 15L, 0L, 45L,30L), hour = c(15L, 15L, 15L, 14L, 14L, 14L, 14L, 13L, 13L),mday = c(27L, 27L, 27L, 27L, 27L, 27L, 27L, 27L, 27L), mon = c(0L,0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L), year = c(116L, 116L, 116L,116L, 116L, 116L, 116L, 116L, 116L), wday = c(3L, 3L, 3L,3L, 3L, 3L, 3L, 3L, 3L), yday = c(26L, 26L, 26L, 26L, 26L,26L, 26L, 26L, 26L), isdst = c(0L, 0L, 0L, 0L, 0L, 0L, 0L,0L, 0L), zone = c("EST", "EST", "EST", "EST", "EST", "EST","EST", "EST", "EST"), gmtoff = c(NA_integer_, NA_integer_,NA_integer_, NA_integer_, NA_integer_, NA_integer_, NA_integer_,NA_integer_, NA_integer_)), .Names = c("sec", "min", "hour","mday", "mon", "year", "wday", "yday", "isdst", "zone", "gmtoff"), class = c("POSIXlt", "POSIXt")), Close = c(1127.2, 1127.5,1126.9, 1128.3, 1125.4, 1122.7, 1122.8, 1117.3, 1116), FOMCBinary = c(0,0, 0, 0, 1, 0, 0, 0, 0)), .Names = c("DateTime", "Close", "FOMCBinary"), row.names = 2131:2139, class = "data.frame") 

Xvalue = 1129

rowShift <- function(x, shiftLen = 1L) { 
  r <- (1L + shiftLen):(length(x) + shiftLen)
  r[r<1] <- NA
  return(x[r])    }

DATA$SignalBinary <- ifelse(
               DATA$Close < Xvalue & (
               rowShift(DATA$FOMCBinary, +1) > 0 |
              (rowShift(DATA$FOMCBinary, +2) > 0 & rowShift(DATA$FOMCBinary, +1) == 0))
              , 1, 0)

Output for DATA after calculations:

                DateTime  Close FOMCBinary SignalBinary
2131 2016-01-27 15:30:00 1127.2          0            0
2132 2016-01-27 15:15:00 1127.5          0            0
2133 2016-01-27 15:00:00 1126.9          0            1    => UNWANTED 1
2134 2016-01-27 14:45:00 1128.3          0            1
2135 2016-01-27 14:30:00 1125.4          1            0
2136 2016-01-27 14:15:00 1122.7          0            0
2137 2016-01-27 14:00:00 1122.8          0            0
2138 2016-01-27 13:45:00 1117.3          0           NA
2139 2016-01-27 13:30:00 1116.0          0           NA

Thank you very much.

Aucun commentaire:

Enregistrer un commentaire