Search code examples
rquantmod

Loop code to screen multiple stocks


I am using the following code to identify the stocks that have experienced growth for the past 6 months.

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

The output is

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

But I do it "manually" for each stock. I want to automate the process so that I load multiple stocks at once

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

And out of these downloaded stocks, I want to filter out those that satisfy these criteria ("TRUE" for the past 6 months) like I did above. Any suggestions how I can do that?


Solution

  • I would layout the code along the following lines:

    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