如何简化quantmod命令以加载库存数据

时间:2016-05-01 16:17:14

标签: r quantmod

如果我想加载库存数据,我就是这样做的(以谷歌为例):

## most recent close price
getSymbols("GOOG")
last(GOOG)[,4]

## total equity
getFinancials("GOOG")
viewFinancials(GOOG.f, type='BS', period='A',subset = NULL)['Total Equity',1]

## Net Income
viewFinancials(GOOG.f, type='IS', period='Q',subset = NULL)['Net Income',1]

......列表继续。

但是,只需键入GOOG一次,然后在其余代码中将其替换为通用名称,这将更加实际。如何在quantmod

中完成此操作

2 个答案:

答案 0 :(得分:1)

选项auto.assign=FALSE应解决问题。

以下是您的代码的修改版本。将其扩展到更多数量的代码并且例如在循环中处理它们应该是直截了当的。

library(quantmod)
CollectionOfTickers <- c("GOOG")
IndexOfCurrentTicker <- 1
# the part that follows could be extracted as a function
CurrentTicker <- getSymbols(CollectionOfTickers[IndexOfCurrentTicker], auto.assign=FALSE)
Cl(last(CurrentTicker)) ## most recent close price
## total equity
CurrentTickerFinancials <- getFinancials(CollectionOfTickers[IndexOfCurrentTicker], auto.assign=FALSE)
viewFinancials(CurrentTickerFinancials, type='BS', period='A',subset = NULL)['Total Equity',1]

## Net Income
viewFinancials(CurrentTickerFinancials, type='IS', period='Q',subset = NULL)['Net Income',1]

请注意,“GOOG”不再是硬编码的。它只在向量CollectionOfTickers中定义一次,并且使用变量IndexOfCurrentTicker检索此向量的条目,该变量可以代表更大的代码集合中的循环变量。

修改

这个代码的一个变体来执行几个代码的循环可以这样编程:

library(quantmod)
CollectionOfTickers <- c("GOOG","AAPL","TSLA","MSFT")
for (TickerName in CollectionOfTickers) {
  CurrentTicker <- getSymbols(TickerName, auto.assign=FALSE)
  cat("========\nData for ticker ", TickerName,"\n")
  ## most recent close price:
  print(Cl(last(CurrentTicker))) 
  CurrentTickerFinancials <- getFinancials(TickerName, auto.assign=FALSE)
  ## total equity:
  print(viewFinancials(CurrentTickerFinancials, type='BS', period='A',subset = NULL)['Total Equity',1])
  ## Net Income:
  print(viewFinancials(CurrentTickerFinancials, type='IS', period='Q',subset = NULL)['Net Income',1])
  cat("========\n")
}

通过进一步的重构可以提高代码质量,但无论如何这都应该有效。

希望这有帮助。

答案 1 :(得分:1)

我认为这就是你想要的。如果你还需要别的东西......回复...

require(XML)
require(plyr)

getKeyStats_xpath <- function(symbol) {
  yahoo.URL <- "http://finance.yahoo.com/q/ks?s="
  html_text <- htmlParse(paste(yahoo.URL, symbol, sep = ""), encoding="UTF-8")

  #search for <td> nodes anywhere that have class 'yfnc_tablehead1'
  nodes <- getNodeSet(html_text, "/*//td[@class='yfnc_tablehead1']")

  if(length(nodes) > 0 ) {
    measures <- sapply(nodes, xmlValue)

    #Clean up the column name
    measures <- gsub(" *[0-9]*:", "", gsub(" \\(.*?\\)[0-9]*:","", measures))   

    #Remove dups
    dups <- which(duplicated(measures))
    #print(dups) 
    for(i in 1:length(dups)) 
      measures[dups[i]] = paste(measures[dups[i]], i, sep=" ")

    #use siblings function to get value
    values <- sapply(nodes, function(x)  xmlValue(getSibling(x)))

    df <- data.frame(t(values))
    colnames(df) <- measures
    return(df)
  } else {
    # break
    cat("Could not find",symbol,"\n")
    return(data.frame(NA))
  }
}


tickers <- c("AXP","BA","CAT","CSCO","CVX","DD","DIS","GE","GS","HD","IBM","INTC","JNJ","JPM","KO","MCD","MMM","MRK","MSFT","NKE","PFE","PG","T","TRV","UNH","UTX","V","VZ","WMT","XOM")
stats <- ldply(tickers, getKeyStats_xpath)
stats <- stats[!rowSums(is.na(stats)) == length(stats),]
rownames(stats) <- tickers
write.csv(t(stats), "FinancialStats_updated.csv",row.names=TRUE)