Quantmod get / viewFinancials in Loop

时间:2012-07-13 17:18:07

标签: r financial quantmod

我想循环浏览一系列代码,获取财务状况并将其导出到桌面文件夹中的CSV文件中。但是,我在使用Quantmod包中与viewFinancials()相关的错误时遇到了问题。代码和错误如下所示。

所以,我的问题是如何将变量指定为类财务对象,以便我的循环正常运行?或者,如果有人有另一种选择,我会很高兴听到它!

以下是错误消息:

  

viewFinancials中的错误(co.f,“BS”,“Q”):    'x'必须是'财务'类型

以下是我正在处理的代码:

 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)
}

2 个答案:

答案 0 :(得分:1)

co.f包含工作空间中实际包含财务对象的对象的名称。要实际使用该对象,您需要调用get(co.f)

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

或者它看起来像

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

也有效,可能更直接。

答案 1 :(得分:0)

您可以考虑tidyquant包,它可以将多个股票传递给tq_get()函数,而不是编写循环。设置tq_get(get = "financials")将允许您下载多个股票的财务。以下是示例:

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

这将在年度和季度期间返回所有财务报表数据(损益表,资产负债表,现金流)的嵌套数据框。您可以使用unnest()功能剥离图层。

如果您需要保存数据,则可以使用write_csv()函数取消然后写入csv。