2012-07-13 34 views
0

我想循環查看代碼清單,獲取財務數據並將它們導出到我桌面上的文件夾中的CSV文件。但是,我一直遇到與Quantmod包中的viewFinancials()有關的R中的錯誤。代碼和錯誤如下所示。Quantmod獲取/查看循環中的財務報告

所以,我的問題是如何分配一個變量作爲類財務的對象,以便我的循環正常運行?或者如果有人有另一種選擇,我會很高興聽到它!

以下是錯誤消息:

錯誤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) 
} 
+0

如果你想分配數據到'co.f',那麼你必須使用'auto.assign = FALSE' – GSee 2012-07-13 17:42:28

回答

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) 

也可行,可能更直截了當。

+0

謝謝!現在就開始運行 – Dedwards 2012-07-13 17:35:42

0

您可能會考慮使用tidyquant包來使多個庫存被傳遞給tq_get()函數,而不是編寫循環。設置tq_get(get = "financials")將允許您下載多個股票的財務數據。下面是和示例:

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

這將返回年度和季度期間的所有財務報表數據的嵌套的數據幀(損益表,資產負債表,現金流)。您可以使用unnest()函數剝離圖層。

如果您需要保存數據,則可以使用write_csv()函數將其寫入csv。