【问题标题】:Getting the subset for a quantmod chartSeries after a call to zooom在调用 zoom 后获取 quantmod chartSeries 的子集
【发布时间】:2011-11-02 18:52:48
【问题描述】:

在调用 zoom 函数(允许用户通过单击缩放的最左侧和最右侧边界以交互方式更改图表的缩放)后,是否可以显示结果子集?

我想要这个的原因:

  1. 根据我添加的自定义 TA 为我的图表设置适当的 yrange,否则将不可见,因为自动 yrange 仅基于传递给 chartSeries 的原始调用的时间序列
  2. 实现图表左右平移功能

不涉及获取当前子集的这 2 个目标的解决方法也会有所帮助。目前我能想到的唯一选择是避免使用交互式缩放功能,而只使用图表缩放。

【问题讨论】:

  • 我发现 chartSeries 返回一个对象,该对象具有指定图表的各种详细信息的属性,包括具有时间序列索引的属性 xrange。然而,当我调用 zoom 时,chartSeries 返回的原始对象的属性似乎没有被修改,并且 zoom 没有返回任何内容。
  • 抱歉编辑问题,我现在知道确实有一个拼写为zooom的函数

标签: r quantmod


【解决方案1】:

首先要知道为什么zoomChart() 返回你想要的值,而zooom() 没有。

zoomChart() 这样做是因为它调用了函数reChart(),该函数以invisible(chob) 行结束。 (chob 是您要查找的对象的名称。)

zooom() 不这样做。它调用zoomChart(),但它没有安排将chob 传递出正在评估zoomChart() 的环境。不过,您可以通过创建 zooom() 的修改版本来做到这一点

我首先将zooom 转储到一个文件中,然后创建一个名为zooom2 的编辑函数:

require(quantmod)
dump("zooom", file="zooom2.R")

我所做的三个修改是:

  1. 将对get.chob() 的调用替换为对quantmod:::get.chob() 的调用。这是必需的,因为与 zooom 不同,zooom2 没有 namespace:quantmod 作为其封闭环境。

  2. zoomChart()的输出赋值给对象chob

  3. invisible(chob)结束函数,将chob返回到调用环境。

这是修改后的函数:

zooom2 <-
function (n = 1, eps = 2) 
{
for (i in 1:n) {
    cat("select left and right extremes by clicking the chart\n")
    points <- locator(2)
    if (abs(diff(points$x)) < eps) {
    zoomChart()
    }
    else {
    usr <- par("usr")
    xdata <- quantmod:::get.chob()[[2]]@xdata
    xsubset <- quantmod:::get.chob()[[2]]@xsubset
    sq <- floor(seq(usr[1], usr[2], 1))
    st <- which(floor(points$x[1]) == sq)/length(sq) * 
        NROW(xdata[xsubset])
    en <- which(floor(points$x[2]) == sq)/length(sq) * 
        NROW(xdata[xsubset])
    sorted <- sort(c(st, en))
    st <- sorted[1]
    en <- sorted[2] * 1.05
    chob <- zoomChart(paste(index(xdata[xsubset])[max(1, floor(st), 
        na.rm = TRUE)], index(xdata[xsubset])[min(ceiling(en), 
        NROW(xdata[xsubset]), na.rm = TRUE)], sep = "::"))
    }
}
cat("done\n")
invisible(chob)

}

您可以将函数获取或粘贴回您的 R 会话中,然后像这样使用它(例如):

  data(sample_matrix)
  chartSeries(sample_matrix)
  d <- zooom2()
  # Click to interactively zoom in

  # extract the data visible in the selected region
  d_sub <- d@xdata[d@xsubset,]
  head(d_sub)
#                Open     High      Low    Close
# 2007-03-28 48.33090 48.53595 48.33090 48.53595
# 2007-03-29 48.59236 48.69988 48.57432 48.69988
# 2007-03-30 48.74562 49.00218 48.74562 48.93546
# 2007-03-31 48.95616 49.09728 48.95616 48.97490
# 2007-04-01 48.94407 48.97816 48.80962 48.87032
# 2007-04-02 48.90488 49.08400 48.90488 49.06316

如果这对您有用,您可能希望将其添加到 quantmod 源中,然后重新编译您自己的软件包版本。

希望这会有所帮助。

【讨论】:

  • 那就是完美的工作。我是 R 新手,所以我不知道转储功能,非常有用。
猜你喜欢
  • 1970-01-01
  • 2013-07-21
  • 2023-03-28
  • 1970-01-01
  • 2018-03-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多