【问题标题】:R loop and download stock prices from yahoo.comR循环并从yahoo.com下载股票价格
【发布时间】:2015-09-10 10:16:08
【问题描述】:

我正在尝试一次从雅虎下载几股股票的价格。我尝试了以下代码,它产生了结果,但我希望结果以每股列的形式呈现。

所以:

library(tseries)
library(zoo)

ticker<-c('AAPL', 'MSFT', 'GOOG')

nShares<-length(ticker)

start<-'2015-01-01'

end<-'2015-09-01'

prices <- function() {

    y=get.hist.quote(instrument = ticker[i],
               start = start,
               end = end, quote = "AdjClose",
               retclass = "zoo")

   dimnames(y)[[2]] <- as.character(ticker[i])
   print (y)
  }  

for (i in 1:nShares){
  prices()
}

我得到的结果是一列包含 3 股的所有时间序列。我想将它们全部放在 3 列中:

Date              AAPL     MSFT    GOOG

2015-xx-xx      xx.xx    xx.xx   xx.xx

我该怎么做?

【问题讨论】:

    标签: r loops download


    【解决方案1】:

    稍微修改一下你的函数:

    prices <- function(ticker, start, end) {
    
      y=get.hist.quote(instrument = ticker,
                       start = start,
                       end = end, quote = "AdjClose",
                       retclass = "zoo")
    
      dimnames(y)[[2]] <- as.character(ticker)
      # print (y)
      y
    } 
    

    你可以在 1 行中实现它:

    zoo_group <- do.call(cbind, lapply(tickers, prices, start=start, end=end))
    head(zoo_group)
                   AAPL     MSFT     GOOG
    2015-01-02 107.9586 45.82758 524.8124
    2015-01-05 104.9172 45.40616 513.8723
    2015-01-06 104.9271 44.73971 501.9623
    2015-01-07 106.3984 45.30815 501.1023
    2015-01-08 110.4864 46.64103 502.6823
    2015-01-09 110.6049 46.24900 496.1723
    

    【讨论】:

    • 非常感谢您的帮助!
    【解决方案2】:

    您也可以尝试新的包tidyquant,它让获取许多股票代码的股票价格变得非常简单:

    library(tidyquant)
    
    ticker <- c('AAPL', 'MSFT', 'GOOG')
    
    ticker %>%
        tq_get(get  = "stock.prices", 
               from = "2015-01-01",
               to   = "2015-09-01")
    

    【讨论】:

      猜你喜欢
      • 2011-03-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-09
      • 2017-01-08
      • 2018-11-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多