使用quantMod的chartSeries绘制1分钟OHLCV数据时遇yrange错误求助
解决quantMod中chartSeries绘制分钟级OHLCV数据的报错问题
问题重现
用户尝试用quantMod包的chartSeries函数绘制1分钟级OHLCV时间序列,运行代码时出现报错:
ES = structure(list( ES.Time = structure(c(1126042320, 1126042380, 1126042440, 1126042500, 1126042560, 1126042620, 1126042680, 1126042740, 1126042800, 1126042860, 1126042920, 1126042980, 1126043040, 1126043100, 1126043220), class = c("POSIXct", "POSIXt"), tzone = ""), ES.Open = c(1114.25, 1114.5, 1114.5, 1114.25, 1114.25, 1114.25, 1114.25, 1114.25, 1114.25, 1114, 1114, 1114, 1114.25, 1114, 1114.25), ES.High = c(1114.5, 1114.75, 1114.5, 1114.5, 1114.5, 1114.25, 1114.25, 1114.25, 1114.25, 1114.25, 1114.25, 1114, 1114.25, 1114, 1114.25), ES.Low = c(1114.25, 1114.25, 1114.25, 1114.25, 1114.25, 1114.25, 1114, 1114.25, 1114, 1114, 1114, 1114, 1114, 1114, 1114.25), ES.Close = c(1114.25, 1114.5, 1114.5, 1114.25, 1114.5, 1114.25, 1114.25, 1114.25, 1114, 1114.25, 1114, 1114, 1114, 1114, 1114.25), ES.Volume = c(98, 423, 131, 274, 46, 20, 218, 13, 14, 43, 15, 8, 56, 2, 10) ), class = "data.frame", row.names = c(NA,-15L)) ES = xts(ES, order.by = ES$ES.Time) chartSeries(ES)
报错信息:
Error in (function (cl, name, valueClass) :
assignment of an object of class “character” is not valid for @‘yrange’ in an object of class “chob”; is(value, "numeric") is not TRUE
用户尝试移除ES.Time列并将所有列转为numeric类型,但仍出现相同错误。
错误原因
quantMod的chartSeries函数要求输入的xts对象必须包含标准命名的OHLCV列(Open、High、Low、Close、Volume),用户数据中的列名带有ES.前缀(如ES.Open),导致函数无法识别正确的OHLCV字段,进而在计算Y轴范围时出现类型错误。
解决方案
方法1:重命名列名
直接将列名改为quantMod识别的标准名称:
# 移除ES.Time列 ES = subset(ES, select=-c(ES.Time)) # 重命名为标准OHLCV列名 colnames(ES) = c("Open", "High", "Low", "Close", "Volume") # 绘制图表 chartSeries(ES)
方法2:使用quantMod的OHLC函数转换
利用quantMod提供的工具函数将带前缀的列转换为标准OHLC对象:
# 移除ES.Time列 ES = subset(ES, select=-c(ES.Time)) # 转换为标准OHLC结构 es_ohlc = OHLC(ES, col.names = c("Open", "High", "Low", "Close")) # 添加Volume列 es_ohlc$Volume = ES$ES.Volume # 绘制图表 chartSeries(es_ohlc)
两种方法均可让chartSeries正确识别OHLCV数据,成功生成K线图。
内容的提问来源于stack exchange,提问作者Sam
相关产品推荐
相关产品推荐

