You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用tidyquant的tq_get获取Yahoo Finance股息数据遇无数据报错

修复tidyquant批量获取股息/拆股数据时的空数据报错

问题重现

运行代码

pacman::p_load("tidyverse","tidyquant")
setwd(dirname(rstudioapi::getActiveDocumentContext()$path))
'%&%' <- function(a,b) paste(a,b)

Stocks<-c("MSFT","IWDA.AS")
D  <- tq_get(Stocks, get = "dividends", from = " 2010-01-01",complete_cases = TRUE)

报错信息

Error in `dplyr::mutate()`:
ℹ In argument: `data.. = purrr::map(...)`.
Caused by error in `purrr::map()`:
ℹ In index: 2.
Caused by error in `dimnames<-.xts`:
! 'dimnames' applied to non-array
Run `rlang::last_trace()` to see where the error occurred.

问题背景

当标的列表中存在无股息/拆股数据的资产(如IWDA.AS)时,批量调用tq_get会触发报错。两年前代码可正常执行,推测是tidyquant或Yahoo Finance接口更新后,空数据的处理逻辑发生变化,且无法提前剔除无数据标的。

快速修复方案

方案1:添加错误捕获的批量获取(推荐)

通过purrr::map_dfr遍历每个标的,对无数据的情况返回标准结构的空表,避免批量处理中断:

pacman::p_load("tidyverse","tidyquant")
setwd(dirname(rstudioapi::getActiveDocumentContext()$path))
'%&%' <- function(a,b) paste(a,b)

Stocks<-c("MSFT","IWDA.AS")

# 定义带容错的股息获取函数
get_dividends_safe <- function(symbol) {
  tryCatch(
    tq_get(symbol, get = "dividends", from = "2010-01-01", complete_cases = TRUE),
    error = function(e) {
      # 返回和正常数据结构一致的空表,保留标的符号
      tibble(symbol = symbol, date = as.Date(character()), dividends = numeric())
    }
  )
}

# 批量获取并合并结果
D <- map_dfr(Stocks, get_dividends_safe)

处理后,无数据的标的会生成空行,后续可根据需求过滤或保留完整列表。

方案2:降级tidyquant版本(临时应急)

如果需要完全还原旧版行为,可降级到两年前的稳定版本(以0.5.3为例):

# 卸载当前版本
remove.packages("tidyquant")
# 安装指定旧版本
devtools::install_version("tidyquant", version = "0.5.3", repos = "http://cran.us.r-project.org")

注意:降级可能引发其他兼容性问题,仅作为临时应急方案。

拆股数据的适配

将上述方案中的get = "dividends"替换为get = "splits",即可解决拆股数据获取时的相同报错:

# 定义带容错的拆股获取函数
get_splits_safe <- function(symbol) {
  tryCatch(
    tq_get(symbol, get = "splits", from = "2010-01-01", complete_cases = TRUE),
    error = function(e) {
      tibble(symbol = symbol, date = as.Date(character()), splits = numeric())
    }
  )
}

# 批量获取拆股数据
S <- map_dfr(Stocks, get_splits_safe)

内容的提问来源于stack exchange,提问作者gilberke

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 17:08:25