Question

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)
}
Was it helpful?

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.

OTHER TIPS

Rather than writing a loop, you might consider the tidyquant package which enables multiple stocks to be passed to the tq_get() function. Setting tq_get(get = "financials") will allow you to download the financials for multiple stocks. Here's and example:

library(tidyquant)
c("FB", "AMZN", "NFLX", "GOOG") %>%
    tq_get(get = "financials")

This returns a nested data frame of all the financial statement data (income statement, balance sheet, cashflow) in both annual and quarterly periods. You can use the unnest() function to peel away the layers.

If you need to save the data, you can unnest then write to a csv using the write_csv() function.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top