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

R语言获取雅虎财经股票OHLC数据并构建扫描指标时的ymd函数日期显示异常问题求助

解决lubridate::ymd日期显示错误的问题

看起来你遇到的核心问题是通过字符串解析日期时的不可靠性——quantmod返回的xts对象本身已经带有原生的日期索引,不需要把它转成字符串再用ymd解析,直接提取索引并转换为Date类型会更稳定。

问题根源

getSymbols返回的xts对象的行名(索引)本质是Date或POSIXct类型,当你用rownames_to_column把它转成字符串后,再用ymd解析时,可能因为系统locale设置、字符串格式的细微差异(比如是否带时间戳)导致解析错误,即使添加truncated=2也无法彻底解决。

解决方案:直接提取xts的日期索引

我们可以跳过字符串解析的步骤,直接从xts对象中提取原生的日期索引,这样能保证日期的准确性。

1. 修改get_stock_prices函数

替换原来的日期转换逻辑,直接提取xts的索引:

get_stock_prices <- function(ticker, return_format = "tibble", ...) {
  # 获取股票价格
  stock_prices_xts <- getSymbols(Symbols = ticker, auto.assign = FALSE, ...)
  # 重命名列名
  names(stock_prices_xts) <- c("Open", "High", "Low", "Close", "Volume", "Adjusted")
  
  if (return_format == "tibble") {
    # 直接提取xts的日期索引,无需转字符串再解析
    stock_prices <- tibble(
      Date = index(stock_prices_xts),
      Open = coredata(stock_prices_xts$Open),
      High = coredata(stock_prices_xts$High),
      Low = coredata(stock_prices_xts$Low),
      Close = coredata(stock_prices_xts$Close),
      Volume = coredata(stock_prices_xts$Volume),
      Adjusted = coredata(stock_prices_xts$Adjusted)
    ) %>%
      # 确保日期是Date类型(如果是POSIXct的话转换)
      mutate(Date = as.Date(Date))
  } else {
    stock_prices <- stock_prices_xts
  }
  stock_prices
}

2. 修改sma函数

同样,直接提取SMA结果的日期索引:

sma <- function(x, return_format = "tibble", n = 10) {
  x = na.omit(x)
  
  if (!is.xts(x)) {
    x <- xts(x[,-1], order.by = x$Date)
  }
  
  sma_xts <- SMA(x = x$Adjusted, n = n)
  names(sma_xts) <- "SMA"
  
  if (return_format == "tibble") {
    sma <- tibble(
      Date = index(sma_xts),
      SMA = coredata(sma_xts)
    ) %>%
      mutate(Date = as.Date(Date))
  } else {
    sma <- sma_xts
  }
  sma
}

额外优化(可选)

如果你习惯用timetk包(属于tidyquant生态),可以用tk_tbl函数更简洁地把xts转成tibble,同时保留日期索引:

# 在get_stock_prices中替换为:
stock_prices <- stock_prices_xts %>%
  timetk::tk_tbl(preserve_index = TRUE, rename_index = "Date") %>%
  mutate(Date = as.Date(Date))

# 在sma函数中替换为:
sma <- sma_xts %>%
  timetk::tk_tbl(preserve_index = TRUE, rename_index = "Date") %>%
  mutate(Date = as.Date(Date))

这样代码会更简洁,而且同样能保证日期的准确性。

验证修改

运行你的批量处理代码后,检查stocklist$stock.prices和stocklist$SMA中的Date列,应该能看到正确的Date类型(比如2022-01-03这样的格式),而不是错误的解析结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.27 15:02:46