【问题标题】:How to fix the error when download stock price using tq_get in r?在 r 中使用 tq_get 下载股票价格时如何修复错误?
【发布时间】:2022-07-21 18:54:02
【问题描述】:

我正在尝试使用 tq_get 根据代码下载股票价格。这是我的数据集merge_df 的负责人。我有 300 多家公司,我需要在提交日期的前一天获取他们的股票价格。

symbol company_name date.filed
A Agilent Technologies 2020-12-18
A Agilent Technologies 2019-12-19
A Agilent Technologies 2021-12-17
AA Alcoa 2020-02-21
AA Alcoa 2019-02-26
AA Alcoa 2021-02-25

在这里,我要感谢@Tom Hoel,他为我提供了一种解决方案。但是当我尝试这段代码时,我发现它只有在一家公司只有一个日期时才有效。 代码如下:

final_df <- merge_df %>%  
  mutate(date.filed = date.filed %>% as.Date(), 
         price_before_filing = map2(.x = symbol, 
                                    .y = date.filed, 
                                    ~ tq_get(.x, from = as.Date(.y) - 1) %>% 
                                      slice(1) %>% 
                                      pull(adjusted)) %>% 
           as.numeric()) %>% 
  select(symbol, company_name, price_before_filing, everything())


报错为:

Warning: Problem with `mutate()` column `price_before_filing`.
ℹ `price_before_filing = `%>%`(...)`.
ℹ x = 'BAND', get = 'stock.prices': Error in getSymbols.yahoo(Symbols = "BAND", env = <environment>, verbose = FALSE, : Unable to import “BAND”.
BAND download failed after two attempts. Error message:
HTTP error 401.

Error: Problem with `mutate()` column `price_before_filing`.
ℹ `price_before_filing = `%>%`(...)`.
x no applicable method for 'slice' applied to an object of class "logical"
Run `rlang::last_error()` to see where the error occurred.

有谁知道我为什么会出现这个错误以及如何解决它?

非常感谢!!

【问题讨论】:

  • 是否只有代码 BAND 会导致错误?那家公司的申请日期是什么时候,我可能需要对具体案例进行故障排除

标签: r finance stock yahoo-finance quantmod


【解决方案1】:

奇怪,我没有收到任何错误。你的包裹是最新的吗? 我正在运行tidyquant 1.0.4tidyverse 1.3.1

library(tidyquant)
library(tidyverse)

df %>%  
  mutate(date.filed = date.filed %>% as.Date(), 
         price_before_filing = map2(.x = symbol, 
                             .y = date.filed, 
                             ~ tq_get(.x, 
                                      from = as.Date(.y) - 1) %>% 
                               slice(1) %>% 
                               pull(adjusted)) %>% 
           as.numeric()) 

# A tibble: 6 x 4
  symbol company_name         date.filed price_before_filing
  <chr>  <chr>                <date>                   <dbl>
1 A      Agilent_Technologies 2020-12-18               118. 
2 A      Agilent_Technologies 2019-12-19                81.9
3 A      Agilent_Technologies 2021-12-17               150. 
4 AA     Alcoa                2020-02-21                16.0
5 AA     Alcoa                2019-02-26                30.6
6 AA     Alcoa                2021-02-25                27.1

【讨论】:

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