Search code examples
rfinancialquantmod

Quantmod get/viewFinancials in Loop


I would like to cycle through a list of tickers, get their financials and export them to CSV files in a folder on my desktop. However, I have been having trouble with an error in R related to viewFinancials() in the Quantmod package. The code and error are shown below.

And so, my question is how to assign a variable as an object of class financial so that my loop runs properly? Or if anyone has another alternative, I would be excited to hear it!

Here is the error message:

Error in viewFinancials(co.f, "BS", "Q") : ‘x’ must be of type ‘financials’

Here is the code I am working on:

 tickers <- c('AAPL','ORCL','MSFT')

 for(i in 1:length(tickers)){

     co <- tickers[1]
     #co.f <- paste(co,".f",sep='') #First attempt, was worth a try

     co.f <- getFin(co, auto.assign=T)  # automatically assigns data to "co.f" object
     BS.q<-viewFinancials(co.f,'BS',"Q")  # quarterly balance sheet
     IS.q<-viewFinancials(co.f,"IS","Q")  # quarterly income statement
     CF.q<-viewFinancials(co.f,"CF","Q")  # quarterly cash flow statement
     BS<-viewFinancials(co.f,"BS","A")  # annual balance sheet
     IS<-viewFinancials(co.f,"IS","A")  # annual income statement
     CF<-viewFinancials(co.f,"CF","A")  # annual cash flow statement

     d<-Sys.Date()

     combinedA <- rbind(BS,IS,CF)
     combinedQ <- rbind(BS.q,IS.q,CF.q)

     BSAfile <- paste('/Users/dedwards/Desktop/RFinancials/',d,' ',co,'_BS_A.csv',sep='')
     BSQfile <- paste('/Users/dedwards/Desktop/RFinancials/',d,' ',co,'_BS_Q.csv',sep='')
     write.csv(combinedA, file = BSAfile, row.names=TRUE)
     write.csv(combinedQ, file = BSQfile, row.names=TRUE)
}

Solution

  • co.f contains the name of the object in the workspace that actually contains the financials object. To actually use that object you need to call get(co.f)

    obj <- get(co.f)
    # now you can use obj where you were previously trying to use co.f
    

    Alternatively it looks like

    co.f <- getFin(co, auto.assign = FALSE)
    

    also works and is probably more straight forward.