The example below creates a buy signal (1) when a stock (IBM) has a greater than 10% daily drop in value.
It then creates a hold signal for 4 additional days. If the number of hold days were to increase, the code would become more unruly. Is there any way to rewrite the holdsig code using either an apply function or something of similar efficiency (i.e., not a for loop)?
library(quantmod)
getSymbols("IBM")
buysig <- Lag(ifelse(dailyReturn(IBM) < -.10,1,0))
holdsig <- ifelse( Lag(sig) == 1 | Lag(sig, k=2) == 1 | Lag(sig, k=3) == 1 | Lag(sig, k=4) == 1, 1, 0)
Every time I feel like I'm getting better with apply, I take two steps backwards.
First, notice that Lag
can take a vector of k
values:
head(Lag(buysig, k=1:4)
# Lag.1 Lag.2 Lag.3 Lag.4
# 2007-01-03 NA NA NA NA
# 2007-01-04 NA NA NA NA
# 2007-01-05 0 NA NA NA
# 2007-01-08 0 0 NA NA
# 2007-01-09 0 0 0 NA
# 2007-01-10 0 0 0 0
That makes things pretty easy: you can then check row-by-row (apply
with MARGIN = 1
) if any
of the values is equal to 1
:
apply(Lag(buysig, k=1:4) == 1, 1, any)
(and you can pass the output through as.numeric
if you need to turn {TRUE,FALSE} into {1,0})