这是一个解决方案的框架
prices <- round(cumsum(c(1400, rnorm(99, 20, 40))), 2)
signal <- sample(c(0, 1), 100, replace = TRUE, prob = c(0.9, 0.1))
df <- data.frame(
price = prices,
signal = signal,
response = 0
)
state <- "off"
for (i in 1:nrow(df)) { # loop through data
if (state == "off") { # off state, loop does nothing until signal = 1
if (df$signal[i] == 0) {
next
} else { # signal = 1 encountered
comparison_price <- df$price[i] # save current price for comparing
n_comparisons <- 0 # keep track of how many comparisons
state <- "on" # change state to "on"
}
} else if (state == "on") {
df$response[i] <- 1
if (df$price[i] > comparison_price) { # found higher price
state <- "off"
if (df$signal[i] == 1) {
comparison_price <- df$price[i]
n_comparisons <- 0
state <- "on"
}
} else if (n_comparisons == 10) { # hit comparison limit
state <- "off"
n_comparisons <- 0
if (df$signal[i] == 1) {
comparison_price <- df$price[i]
n_comparisons <- 0
state <- "on"
}
} else { # price less or equal to comparison price
n_comparisons <- n_comparisons + 1
}
}
}
df
"on"/"off"
状态对未来更高价值的搜索只会转向
"on"
击中1信号后。在10次比较失败后,它也会自动关闭。由于它不处理在同一行上发现与1信号相同的更高值的情况,因此它将在这样一行上关闭自己,但您可以添加代码以将其重新打开。
索引
i
表示此代码中的行号
for
1, 2, ..., n
为了您的
n
数据行。因此,如果你想使用下一行
i + 1
.
if (signal[i] == 1) { # Find signal match
comparison_price <- input[i + 1] # Set price for comparing ### Set to +1 row below signal ==1 row)
n_comparisons <- 0 # Sets count to 0
state <- "off" # Turn off
}
signal == 1