Search code examples
rquantmod

Data extraction in for loop using r


I am trying to find and compare daily gain and loss percentage in two stocks in r. This is the code

library(quantmod) 
stockData <- new.env() #Make a new environment for quantmod to store data in
tickers <- c("AAPL","GOOG") 
#Set start date
start_date=as.Date("2014-01-01")
getSymbols(tickers, src="yahoo", env=stockData,from=start_date)
for (tick in tickers) {
  x <- get(tick, pos=stockData)  # get data from stockData environment  
  x$gl<-((Cl(x)-Op(x))/Op(x))*100 #Daily gain loss percentage
}

I am able to calculate daily gain/loss percentage for individual stocks but I don't know how to proceed further and extract-compare gain/loss percentage of multiple stocks separately.

Example

if AAPL(gain/loss percentage) is greater than GOOG(gain/loss percentage) then 1 else -1

Solution

  • Your code is a good starting point. However, I would suggest that you store the data of the tickers in a list. As the code is now, only the data of the last ticker treated in the loop is stored in x.

    This slightly modified version might help:

    library(quantmod) 
    stockData <- new.env() #Make a new environment for quantmod to store data in
    tickers <- c("AAPL","GOOG","YHOO","FB") 
    #Set start date
    start_date <- as.Date("2014-01-01")
    getSymbols(tickers, src="yahoo", env=stockData, from=start_date)
    x <- list()
    for (i in 1:length(tickers)) {
      x[[i]] <- get(tickers[i], pos=stockData)  # get data from stockData environment  
      x[[i]]$gl <-((Cl(x[[i]])-Op(x[[i]]))/Op(x[[i]]))*100 #Daily gain loss percentage
    }
    compare_pl <- function(x,y){ifelse(x$gl > y$gl, 1, -1)}
    aapl_vs_goog <- compare_pl(x[[1]],x[[2]])
    

    Now the variable aapl_vs_goog contains the data on the days where AAPL outperformed GOOG (+1) or vice versa (-1):

    > tail(aapl_vs_goog)
    #           gl
    #2015-08-19 -1
    #2015-08-20  1
    #2015-08-21  1
    #2015-08-24  1
    #2015-08-25 -1
    #2015-08-26 -1
    

    Needless to say that this can be performed in the same way for any other ticker.