This is the latest in my series "How to avoid for loops in R." I imagine at some point, I will get it.
Below is the code, for the sake of this example, just run it with Strikes = 530. There is no need to test all the others and worry about the GetStrikesForDay function.
TargetStrikes <- function(data, StrikeIncrement=2.50)
{
epsilon = 0.10
Strikes = GetStrikesForDay(data, StrikeIncrement)
for (i in Strikes)
{
AtStrike <- abs(data$Close - i) <= epsilon
data <- cbind.zoo (data, AtStrike)
colnames(data)[length(colnames(data))] <- i
}
return(data)
}
As it is written, AtStrikes works beautifully. It contains all True/False for the condition specified, one for each row in data. I would like to add another condition and it is failing.
AtStrike <- abs(data$Close - i) <= epsilon || data$High>=i && data$Low <=i
Atstrike now beomes a single value, False, and that's it. I no longer get a nice list of booleans which is what I want.
I know I can loop through each row, but I'd like to avoid that. What is the best way to do this? Right now, I am getting nowhere with it. I've tried all sorts of combinations and no luck.
9:38 should be true based on the High being above 530 and the Low being below or equal to 530
Here is the data,
Open High Low Close
2014-03-07 09:35:00 530.33 530.91 530.25 530.36
2014-03-07 09:36:00 530.54 530.98 530.37 530.73
2014-03-07 09:37:00 530.61 531.33 530.60 531.18
2014-03-07 09:38:00 531.19 531.25 530.00 530.19
2014-03-07 09:39:00 530.30 530.30 529.31 529.78
2014-03-07 09:40:00 529.71 529.89 529.32 529.59
Here is how I would like it to look after running the loop/statement:
Open High Low Close AtStrike
2014-03-07 09:35:00 530.33 530.91 530.25 530.36 FALSE
2014-03-07 09:36:00 530.54 530.98 530.37 530.73 FALSE
2014-03-07 09:37:00 530.61 531.33 530.60 531.18 FALSE
2014-03-07 09:38:00 531.19 531.25 530.00 530.19 TRUE
2014-03-07 09:39:00 530.30 530.30 529.31 529.78 FALSE
2014-03-07 09:40:00 529.71 529.89 529.32 529.59 FALSE
And for entry into R,
structure(c(530.33, 530.54, 530.61, 531.19, 530.3, 529.71, 530.91,
530.98, 531.33, 531.25, 530.3, 529.89, 530.25, 530.37, 530.6,
530, 529.31, 529.32, 530.36, 530.73, 531.18, 530.19, 529.78,
529.59), .Dim = c(6L, 4L), .Dimnames = list(NULL, c("Open", "High",
"Low", "Close")), index = structure(c(1394202900, 1394202960,
1394203020, 1394203080, 1394203140, 1394203200), class = c("POSIXct",
"POSIXt"), tzone = ""), class = "zoo")