循环代码筛选多只股票

Loop code to screen multiple stocks

我正在使用以下代码来识别过去 6 个月内增长的股票。

library(quantmod)
getSymbols("AMZN")
monthly_stock<-to.monthly(AMZN)
adx <- ADX(HLC(monthly_stock), n = 14, maType = "EMA", wilder = TRUE)[, c("DIp", "DIn", "ADX")]
adx$DIp-adx$DIn[(nrow(adx)-5):nrow(adx),]>10

输出是

Jul 2015 TRUE
Aug 2015 TRUE
Sep 2015 TRUE
Oct 2015 TRUE
Nov 2015 TRUE
Dec 2015 TRUE

但我对每只股票都这样做 "manually"。我想使流程自动化,以便一次加载多个股票

stocklist<-c("AMZN","GOOG","AAPL","FB","TSLA") 
getSymbols(stocklist)

在这些下载的股票中,我想像上面那样过滤掉满足这些条件的股票("TRUE" 过去 6 个月)。有什么建议吗?

你需要的是diff函数。

library(quantmod)
getSymbols("AMZN")
monthly_stock<-to.monthly(AMZN)
adx <- ADX(HLC(monthly_stock), n = 14, maType = "EMA", wilder = TRUE)[, c("DIp", "DIn", "ADX")]
adx$DIp-adx$DIn[(nrow(adx)-5):nrow(adx),]>10

adx <- tail(adx, 7)
adx.res <- sapply(1:ncol(adx), function(x){
  y <- diff(as.vector(adx[, x]))
  if (all(y>0)) {
    return(x)
  }
})

names(adx)[unlist(adx.res)]
# ADX

我会按照以下几行布局代码:

stock.list = c("AMZN","GOOG","AAPL","FB")
res = list()
for(ss in stock.list) {
     stock.data = getSymbols(ss, from="1900-01-01", auto.assign=F)
     monthly.data = to.monthly(stock.data)
     adx = ADX(HLC(monthly.data),n=14,maType="EMA",wilder=TRUE)[,c("DIp","DIn","ADX")]
     monthly.adx = adx$DIp-adx$DIn[(nrow(adx)-5):nrow(adx),]>10
     if(all(as.logical(monthly.adx[,1]))) {
        res[[ss]] = monthly.adx
     }
}
# res is a list.
# names(res) gives you the stock symbols for the interesting stocks
# res[["AMZN"]] contains the data - the adx for the last six months in this case