在 quantmod 中:如何获得所有符合特定条件的股票

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

我想根据特定标准检索股票 OHLC 数据,例如仅标准普尔 500 指数高于其自身 MA5。有没有办法使用 quantmod 来做到这一点?比如我可以在getSymbols函数中输入一个if函数吗?

附上我使用的没有标准的代码:

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

我不认为这是可能的。您必须获取所有交易品种,计算感兴趣的指标,然后过滤出满足您条件的交易品种。

这是一种检索所有 S&P500 代码的方法(大约需要 10 分钟,因为请求之间有 1 秒的暂停)并计算每个代码的 200 天均线。

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)
})