R - 时间序列中的下一个最高值 [英] R - Next highest value in a time series

查看:50
本文介绍了R - 时间序列中的下一个最高值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个相对简单的问题,但我似乎找不到任何例子.

我有一个简单的外汇价格数据,它位于一个名为 subx1 的 2 列 xts 对象中:

日期时间,价格2016-09-01 00:00:01, 1.115632016-09-01 00:00:01, 1.115642016-09-01 00:00:02, 1.115642016-09-01 00:00:03, 1.11565

...等等.

我试图找到下午 2 点之后价格高于下午 2 点前的高点的第一时间,该高点位于另一个名为 daypeakxts$before2.High 的对象列中,并且

daypeakxts 的样本在哪里:

日期,before2.High2016-09-01, 1.115672016-09-02, 1.11987

这是我正在尝试做的一个不好的例子:

subxresult <- index(subx1, subx1$datetime > daypeakxts$before2.High)

...所以我希望使用带有另一个 xts 对象中一天值的条件语句来发现价格的日期时间.

解决方案

您没有为 可重现示例提供足够的数据

a>,所以我要使用xts包自带的一些日常数据.

库(xts)数据(样本矩阵)x <- as.xts(sample_matrix, dateForamt = "Date")# 汇总并找出每周的最高点Week.High <- apply.weekly(x, function(x) max(x$High))# 找到下午 2 点前的高点将类似于:# Pre.2pm.High <- apply.daily(x["T00:00/T14:00"], function(x) max(x$High))# 将期间高点与原始数据合并,然后# 用最后一个观察结转填充NAy <- 合并(x,Week.High,fill = na.locf)# 将周期滞后于高位,因此它与下一个周期一致y$Week.High <- 滞后(y$Week.High)# 找到下一个时期高点的第一个实例# 高于前一时期的高点y$First.Higher <- apply.weekly(y, function(x) which(x$High > x$Week.High)[1])

A relatively simple question, but one I can't seem to find any examples.

I have simple forex price data which is in a 2 column xts object called subx1:

Datetime, Price   
2016-09-01 00:00:01, 1.11563  
2016-09-01 00:00:01, 1.11564  
2016-09-01 00:00:02, 1.11564  
2016-09-01 00:00:03, 1.11565

... and so forth.

I'm trying to find the first time after 2pm when the price goes higher than the pre-2pm high which is held in another object's column called daypeakxts$before2.High and

Where a sample of daypeakxts is:

Date, before2.High  
2016-09-01, 1.11567    
2016-09-02, 1.11987

This is a bad example of what I'm trying to do:

subxresult <- index(subx1, subx1$datetime > daypeakxts$before2.High)

... so I'm looking to discover a datetime for a price using a conditional statement with a day's value in another xts object.

解决方案

You didn't provide enough data for a reproducible example, so I'm going to use some daily data that comes with the xts package.

library(xts)
data(sample_matrix)
x <- as.xts(sample_matrix, dateForamt = "Date")

# Aggregate and find the high for each week
Week.High <- apply.weekly(x, function(x) max(x$High))

# Finding the pre-2pm high would be something like:
# Pre.2pm.High <- apply.daily(x["T00:00/T14:00"], function(x) max(x$High))

# Merge the period high with the original data, and
# fill NA with the last observation carried forward
y <- merge(x, Week.High, fill = na.locf)

# Lag the period high, so it aligns with the following period
y$Week.High <- lag(y$Week.High)

# Find the first instance where the next period's high
# is higher than the previous period's high
y$First.Higher <- apply.weekly(y, function(x) which(x$High > x$Week.High)[1])

这篇关于R - 时间序列中的下一个最高值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆