【问题标题】:How to find a stock price on a particular date?如何查找特定日期的股票价格?
【发布时间】:2020-10-13 04:03:28
【问题描述】:

使用 quantmod 或 tidy quant,可以从一个周期范围内下载股票价格。但是,我希望将股票价格列添加到其中包含股票代码和日期的现有数据框中。在 google 电子表格中,有一个简单的公式可以找到特定日期的股票价格。

=GOOGLEFINANCE("AMZN","price",date(2017,2,7))

但是,在 R 中,似乎没有办法做到这一点。

我拥有的是一个数据框:

Date.    Ticker.  Revenue.  Profit...

x.          y        z        i      
...         ...      ...      ...

我需要在 x 上添加一个股票价格为 y 的附加列,以获得

Date.    Ticker.  Revenue.  Profit...   Price

x.          y        z        I          p (of y on x)
...         ...      ...      ...        ...

有没有办法做到这一点?

【问题讨论】:

    标签: r quantmod tidy quandl


    【解决方案1】:

    您可以将 tiingo 与 quantmod"(或 tidyquant)一起使用。我希望 yahoo 也能正常工作,但是在使用 yahoo 时,我在使用 1 天检索时总是遇到错误(yahoo 方面的工作质量低劣)。

    library(quantmod)
    my_api <- "my_api" # <- here goes your tiingo api
    amzn <- getSymbols("AMZN", auto.assign = FALSE, 
                       src = "tiingo",
                       api = my_api,
                       from = "2017-02-07",
                       to = "2017-02-07")
    
    amzn
               AMZN.Open AMZN.High AMZN.Low AMZN.Close AMZN.Volume
    2017-02-07    809.31    816.16    807.5      812.5     3466091
    

    将所有内容组合在一个 data.frame 中:

    library(quantmod)
    library(dplyr)
    library(purrr)
    
    my_api <- "my_api"  # <- here goes your tiingo api
    
    
    # helper function to just get the close price
    get_price <- function(ticker, date) {
      data <- getSymbols(ticker, 
                        auto.assign = FALSE, 
                        src = "tiingo",
                        api = my_api,
                        from = date,
                        to = date)
      
      out <- as.numeric(quantmod::Cl(data))
      out
    }
    
    
    my_data %>% 
      mutate(close = map2(ticker, date, get_price))
    
            date ticker revenue profit close
    1 2017-02-07   AMZN   10000     10 812.5
    2 2018-03-05   MSFT   20000     20 93.64
    

    数据:

    my_data <- data.frame(date = c("2017-02-07", "2018-03-05"),
                          ticker = c("AMZN", "MSFT"),
                          revenue = c(10000, 20000),
                          profit = c(10, 20))
    

    【讨论】:

    • 谢谢,但问题是如何将该价格添加到现有的df中,如问题所示
    • @azmath,请参阅答案中的其他信息。下次请创建更多可重现的示例。
    • 嗨@phiver,谢谢!但是,我无法复制。它显示一个错误:错误:Problem with mutate()` 输入close。 x 无法导入“AMZN”。 HTTP 错误 401。ℹ 输入 closemap2(ticker, date, get_price)。运行rlang::last_error() 看看哪里出错了。``
    • @azmath,你能提供一个小的dput 你的data.frame 吗?看起来您的日期可能不是预期的格式。
    • 你确实有一个用于 tiingo 的 api,不是吗?您可以从他们那里免费获得一台。
    猜你喜欢
    • 2016-11-18
    • 1970-01-01
    • 1970-01-01
    • 2021-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多