Search code examples
rquantmod

in quantmod: how to get all stocks that meet specific criteria


I would like to retrieve stocks OHLC data based on a specific criterion, for example only s&p 500 that are above their own MA5. Is there a way to do it using quantmod? For example, can I enter an if function in the getSymbols function?

Attached is the code that I use without the criterion:

require(quantmod)
options(scipen=999)
spy <- getSymbols(c('SPY', 'IBM') , src = 'yahoo', from = '2007-01-01',  auto.assign = T)
tail(cbind(SPY, IBM)) 

Solution

  • I don't think that this is possible. You have to get all symbols, compute the indicators of interest and then filter for the ones meeting your conditions.

    Here is a way to retrieve all S&P500 symbols (takes approx 10 minutes because there is a pause of 1 second between the requests) and compute the 200-day sma for each of them.

    library(rvest)
    library(quantmod)
    library(TTR)
    tbl <- read_html('https://en.wikipedia.org/wiki/List_of_S%26P_500_companies') %>% html_nodes(css = 'table')
    tbl <- tbl[1] %>% html_table() %>% as.data.frame()
    tbl$Ticker.symbol <- gsub(pattern = '\\.', '-', tbl$Ticker.symbol) # BRK.B -> BRK-B (yahoo uses '-')
    head(tbl$Ticker.symbol)
    [1] "MMM"  "ABT"  "ABBV" "ACN"  "ATVI" "AYI"
    
    quotes <- new.env()
    getSymbols(tbl$Ticker.symbol, src = 'yahoo', from = '2007-01-01', env = quotes)
    
    sma_200 <- lapply(quotes, function(x) {
        SMA(x[, 4], n = 200)
    })