Решение Base R:
open_close_idx_list <- vector("list", 4)
open_close_idx_func <- function(df, m, k, s){
list(open_upper = which(df$ratio > (m + k*s)),
open_lower = which(df$ratio < (m - k*s)),
close_upper = which(df$ratio <= m),
close_lower = which(df$ratio >= m))
}
# Note the arguments passed to this function represent m, k, and s, and have been arbitrarily chosen:
open_close_idx_list <- open_close_idx_func(retail_stocks, .8, .2, .3)
retail_stocks[c(open_close_idx_list$open_upper),]
retail_stocks[c(open_close_idx_list$open_lower),]
retail_stocks[c(open_close_idx_list$close_upper),]
retail_stocks[c(open_close_idx_list$close_lower),]
Пересмотренные входные данные:
retail_stocks <- structure(list(date = structure(c(7306, 7307, 7308, 7309, 7312, 7313, 7314, 7315, 7316, 7319, 7320, 7321, 7322, 7323, 7326, 7327, 7328, 7329, 7330, 7333), class = "Date"),
TGT = c(3.141479, 3.171741, 3.177794, 3.183848, 3.214115, 3.171741, 3.171741, 3.1899, 3.099107, 3.050683, 3.038576, 3.020419, 2.996207, 2.965943, 2.899359, 2.935676, 2.971996, 2.941731, 2.881201, 2.905412), WMT = c(3.880284, 3.880284, 3.859697, 3.818529, 3.869992, 3.767066, 3.767066, 3.808233, 3.664141, 3.612676, 3.674432, 3.633262, 3.571507, 3.581798, 3.489166, 3.489166, 3.509751, 3.447996, 3.468581, 3.489166),
ratio = c(0.809600276680779, 0.81739919036854, 0.82332732336243, 0.833789137125841, 0.830522388676773, 0.841965869459149, 0.841965869459149, 0.837632571326387, 0.845793598008374, 0.844438582369412, 0.826951213139881, 0.7, 0.83891953732696, 0.82805981800202, 0.830960464477758, 0.841368968974248, 0.846782578023341, 0.853171233377301, 0.830656974710984, 0.832695262994079)), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA, -20L))