使用 R 查找时间序列中的事件

问题描述

使用从压力传感器数据生成的滚动时间序列,我希望动态查找特定模式的事件。给定开始日期和结束日期的离散系统更容易完成,但通过滚动系列,我正在努力隔离回溯期,锚定某些点,然后观察定义整体模式的后续观察。

对几个样品进行目视检查后,重复出现的模式如下所示。

  1. 从某个最高点开始
  2. 在观察 1 的分钟 n 个周期内找到最低点
  3. 在观察 2 的分钟 n 个周期内找到观察 1 回撤百分比的点
  4. 在观察 3 的分钟 n 时间段内找到观察 2 的第二个最低 +/- x%

您将如何隔离并找到下面的事件 A 和 B?

library(ggplot2)

# Create series
set.seed(77114)
y <- runif(50,8,9)

# Event observations
eA <- c(10,5,7.5,5)
eB <- c(9.5,4,5.5,4.25)

# Event index positions
eA_idx <- c(10,11,12,13)
eB_idx <- c(30,33,36,40)

# Insert events
y[eA_idx] <- eA
y[eB_idx] <- eB


dat <- data.frame(x = 1:length(y),y = y,col = c(rep("black",9),rep("red",length(min(eA_idx):max(eA_idx))),rep("black",length(14:29)),rep("blue",length(min(eB_idx):max(eB_idx))),length(41:50))))


ggplot(dat,aes(x = x,y = y)) +
  geom_line(aes(colour = col,group = 1)) +
  scale_colour_identity() +
  annotate("text",x = 12,y = 4,label = "Event A",colour = "red") +
  annotate("text",x = 37,label = "Event B",colour = "blue") +
  ylim(3,10)

enter image description here

我看到了一些关于股票市场系列内容的包和函数,但需要对回溯范围进行硬编码。我还研究了时间序列主题和矩阵配置文件,但也需要比我想要的更多的参数,我开始编写一个复杂的 while 循环,在容器中保存观察,但相信必须有更直接的索引功能方法

无法找到帖子,因为我解除了此代码以给予信任,但我调整了某人的 argmin/max 函数来查找局部最小值和最大值,这非常有效。除此之外,我正在努力编写下一步函数来锚定每个点并定义模式。

library(zoo)

argmax <- function(x,y,w = 1,s = .05) {
  n <- length(y)
  y.smooth <- loess(y ~ x,span = s)$fitted
  y.max <- rollapply(zoo(y.smooth),2 * w + 1,max,align = "center")
  delta <- y.max - y.smooth[-c(1:w,n + 1 - 1:w)]
  i.max <- which(delta <= 0) + w
  list(x = x[i.max],i = i.max,y.hat = y.smooth)
}

argmin <- function(x,span = s)$fitted
  y.min <- rollapply(zoo(y.smooth),min,align = "center")
  delta <- y.min - y.smooth[-c(1:w,n + 1 - 1:w)]
  i.min <- which(delta >= 0) + w
  list(x = x[i.min],i = i.min,y.hat = y.smooth)
}


minmax <- function(x,w,s) {
  peaks <- argmax(x,s)
  troughs <- argmin(x,s)
  
  plot(x,cex = 0.75,col = "Gray",main = paste("w = ",",span = ",s,sep = ""))
  lines(x,peaks$y.hat,lwd = 1.5)
  points(x[peaks$i],peaks$y.hat[peaks$i],col = "Blue",pch = 19,cex = 1.25)
  points(x[troughs$i],troughs$y.hat[troughs$i],col = "Red",cex = 1.25)
  
  return(list(peaks = peaks$x,troughs = troughs$x))
}

minmax(x = 1:nrow(dat[-1,]),y = dat$y[-1],s = .05)

enter image description here

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)