Search code examples
rfilterquantmod

Get object names by specific column value of a list


I'm running the following code to get consecutive days of price up/down for several tickers

library(quantmod)

f <- function(symbol, dataStartDate = as.Date("2020-04-01")) {
  
  consecutiveTruesExtractor <- function(data){
    genNumOfConsecutiveTrues <- function(x, y) { (x+y)*y  } #Y is either 0 or 1
    upDaysCount <- Reduce( genNumOfConsecutiveTrues, data, accumulate=TRUE)
    upDaysCount <- as.vector(Lag(upDaysCount))
    upDaysCount[is.na(upDaysCount)] <- 0
    
    downDaysCount <- Reduce( genNumOfConsecutiveTrues, !data, accumulate=TRUE)
    downDaysCount <- as.vector(Lag(downDaysCount))
    downDaysCount[is.na(downDaysCount)] <- 0
    consecutiveTruesExtractor <- upDaysCount-downDaysCount
  }
  
  symbolData <- new.env() #Make a new environment for quantmod to store data in
  getSymbols(symbol, env = symbolData, src = "yahoo", from = dataStartDate)
  mktdata <- eval( parse(text = paste("symbolData$", sub("^", "", symbol, fixed=TRUE))))
  opClRet <- (Cl(mktdata)/Op(mktdata))-1
  consecutiveDir <- consecutiveTruesExtractor(as.matrix(opClRet>0))
  completeData<- cbind(opClRet,consecutiveDir)
  colnames(completeData) <- c("OpClRet","ConsecutiveDir")
  
  mktdata$Consecutive <- completeData$ConsecutiveDir
  
  mktdata
}

Symbols <- c("AMD","A","AAL","ABBV","ABT","ACAD","ADBE")
             
L <- Map(f, Symbols) 


last_row_values<-lapply(L,tail,1)

At the end of the code, I have created last_row_values xts object to get only the last line of list L.

Now, I'd like to get the stock names filtered by a value of the column "Consecutive".

For example, Which tickers have a value of "2" in the "Consecutive" column of last_row_values?

The desired result is to get names of the tickers with an specific value in the column "Consecutive"


Solution

  • You can use purrr::map_lgl to create a vector with the condition result, then get the names of the vector where the condition passed:

    purrr::map_lgl(last_row_values, ~.x$Consecutive == 2) %>% {names(.)[.]}
    

    Obs: you'll need the magrittr pipe %>% for this