Oposum
Oposum

Reputation: 1243

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?

Upvotes: 0

Views: 358

Answers (2)

Ivan Popivanov
Ivan Popivanov

Reputation: 189

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

Upvotes: 1

Ven Yao
Ven Yao

Reputation: 3710

What you need is the diff function.

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

Upvotes: 1

Related Questions