Search code examples
rloopsquantmod

a loop function in R


currently have below lines n would like to write a loop function to reduce lines:

example with one dataset to be downloaded:

library(quantmod)
start_date="2013-01-01"
end_date="2014-01-01"

AAPL<-getSymbols("AAPL",from=start_date,to=end_date,auto.assign = FALSE)
AAPL_ret<-apply(AAPL[,6],2,diff)

n I try to below function to do the work:

test_function<-function(ticker){
  x<-getSymbols(ticker, from=start_date,to=end_date,auto.assign = FALSE)
  x_ret<-apply(x[,6],2,diff)
  plot(x_ret)
}

However, in the case where I have more than one set of data to be downloaded, is it more feasible to write a for loop function? Say if there are a list of tickers which I need to download data:

test_list<-c("AAPL","TSLA","TGT")

Can I transform the test_function above to loop thru the ticker in test_list?

Thanks.


Solution

  • One approach would be to wrap the function in Vectorize, which will allow it to accept a vector input:

    test_function <- Vectorize(function(ticker) {
      x <- getSymbols(ticker,
                   from = start_date,
                   to = end_date,
                   auto.assign = FALSE)
      x_ret <- apply(x[, 6], 2, diff)
      plot(x_ret, main = ticker)
    })
    

    Then when you run test_list through, it will plot each one (below, I am changing the layout to plot all three for visualization purposes):

    test_list <- c("AAPL","TSLA","TGT")
    
    par(mfrow = c(2, 2))
    test_function(test_list)
    

    enter image description here