r - 如何使用 quantmod 将自定义每小时数据绘制到 R 中?

标签 r finance quantmod computational-finance

我正在尝试学习 R,因为对于某些个人项目,我需要 R 和 quantmod 来为我创建 OHCL 图表。我停留在 candleChart 创建步骤,我不确定我明白为什么。使用“每日”输入文件效果很好,但尝试从每小时数据创建每小时图表是一个很大的失败。

这是我正在使用的数据示例:

> zz <- read.csv(dataFile, sep=",", header=TRUE, stringsAsFactors=T)
> head(zz)
                 DATE OPEN HIGH LOW CLOSE VOLUME
1 2012-10-23 02:00:00   22   22  22    22    171
2 2012-10-23 03:00:00   22   22  22    22    171
3 2012-10-23 04:00:00   22   22  22    22    171
4 2012-10-23 05:00:00   22   22  22    22    171
5 2012-10-23 06:00:00   22   22  22    22    171
6 2012-10-23 07:00:00   22   22  22    22    171

如您所见,第一个数据都是一样的,但我的输入文件中有一年的数据,最后价格上涨到 96。

我接下来要做的是从这个 zz 数据帧创建我的 xts 对象,如下所示:

> xx <- xts(zz[,2:6], order.by=as.POSIXct(zz[, 1], tz="", format="%Y-%m-%d %H:%M:%S"))
> head(xx)
                    OPEN HIGH LOW CLOSE VOLUME
2012-10-23 02:00:00   22   22  22    22    171
2012-10-23 03:00:00   22   22  22    22    171
2012-10-23 04:00:00   22   22  22    22    171
2012-10-23 05:00:00   22   22  22    22    171
2012-10-23 06:00:00   22   22  22    22    171
2012-10-23 07:00:00   22   22  22    22    171
> tail(xx)
                    OPEN HIGH LOW CLOSE VOLUME
2013-10-22 06:00:00   96   96  96    96    115
2013-10-22 07:00:00   96   96  96    96    115
2013-10-22 08:00:00   96   96  96    96    115
2013-10-22 09:00:00   96   96  96    96    115
2013-10-22 10:00:00   96   96  96    96    115
2013-10-22 11:00:00   96   96  96    96    118

现在,看起来(对我来说)xts 是正确的。未命名的第 1 列中有日期+时间,其余列的名称正确,以便 quantmod 的 chartCandle() 能够理解。

这是我尝试绘制它时发生的情况:

> candleChart(xx, name=tickerName, subset="last 3 weeks", bar.type = "ohlc")
Error in periodicity(x) : can not calculate periodicity of 1 observation
> candleChart(xx)
Error in periodicity(x) : can not calculate periodicity of 1 observation

我不确定为什么第一个参数是我的 XTS 对象的任何子集? 另外,我发现:

> periodicity(xx)
Error in periodicity(xx) : can not calculate periodicity of 1 observation
> periodicity(xx)
Error in periodicity(xx) : can not calculate periodicity of 1 observation

第二个调用看起来是正确的,但我不确定为什么 periodicity(xx) 会认为我的 xts 中只有 1 个观察值?

最佳答案

periodicity调用:

p <- median(diff(.index(x)))
if (is.na(p)) 
  stop("can not calculate periodicity of 1 observation")

p可以是NA如果x有 1 个观察值,或者如果您的索引中有缺失值(因为 na.rm=TRUE 调用中没有 median

> xx <- xts(1:10, as.POSIXct(c(1:5,NA,7:10),origin='1970-01-01'))
> periodicity(xx)
Error in periodicity(xx) : can not calculate periodicity of 1 observation
> candleChart(xx)
Error in periodicity(x) : can not calculate periodicity of 1 observation

NA在您的索引中可能与转换时的夏令时有关 zz[, 1]POSIXct .

关于r - 如何使用 quantmod 将自定义每小时数据绘制到 R 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19561697/

相关文章:

r - 使用带有 dplyr 管道语法的 base 中的 table() 函数?

r - 绘制方决策树

protocols - 修复内部序列号

python - 摘要不适用于 OLS 估计

r - 使用日期结构略有不同的 xts

r - 如何使用 quantmod 在新图中叠加多个 TA?

r - NA 序列的最小值和最大值

string - 如何将长引号(带有奇怪的字符)存储为字符串

sql - 我应该将 CUSIP 定义为哪种数据库类型?

r - 将 Quantmod 图表系列线条颜色从绿色设置为另一种颜色