R ';滞后';在不规则时间序列中
我有data.frame,它显示了股票的当前买入价和卖出价以及我当时的信号R ';滞后';在不规则时间序列中,r,xts,R,Xts,我有data.frame,它显示了股票的当前买入价和卖出价以及我当时的信号 time bid_price ask_price signal 10:10:01.000500 50.02 50.05 50.03 10:10:01.000855 50.02 50.03 50.05 10:10:01.000856 50.02 50.03 50.06 在10:10:01.000856,当我在50:06有
time bid_price ask_price signal
10:10:01.000500 50.02 50.05 50.03
10:10:01.000855 50.02 50.03 50.05
10:10:01.000856 50.02 50.03 50.06
在10:10:01.000856,当我在50:06有信号时,我不能使用它。我只能在50微秒前使用信号
所以我需要这个结果数据框架
50微秒前的10:10:01.000856,时间是10:01:01.000806,因此该时间的可用信号是50.03
time bid_price ask_price signal signal_50microseconds_ago
10:10:01.000500 50.02 50.05 50.03 NA
10:10:01.000855 50.02 50.04 50.05 50.03
10:10:01.000856 50.02 50.04 50.06 50.03
是否有生成结果data.frame的R/python解决方案?
例如,假设我们首先将data.frame加载到xts
对象中,那么我们可能会
xts_obj$signal_50microseconds_ago <- get_time_lag_wish_this_function_exists(xts_obj$signal,lag=0.000050)
这是我将采取的方法,以使这些值与之前的最新观察结果保持一致。它仅使用
xts
merge函数和na.locf()
向前填充合并的时间值:
d <- read.table(stringsAsFactors=F, header=T, text="
time bid_price ask_price signal
10:10:01.000500 50.02 50.05 50.03
10:10:01.000855 50.02 50.03 50.05
10:10:01.000856 50.02 50.03 50.06
")
t <- as.POSIXct(paste0("2015-05-28 ", d$time))
#format(t, "%Y-%m-%d %H:%M:%OS9")
library(xts)
d_xts <- xts(d[,-1], order.by=t)
## Lag the signal by 50 microseconds:
signal_lag <- xts(d[,"signal"], order.by=t+0.000050)
merge_xts <- merge(d_xts, signal_lag)
## Carry last lagged value forward:
merge_xts$signal_lag <- na.locf(merge_xts$signal_lag)
## Finally subset back to only original rows:
merge_xts <- merge_xts[ !is.na(merge_xts$signal) ]
d <- read.table(stringsAsFactors=F, header=T, text="
time bid_price ask_price signal
10:10:01.000500 50.02 50.05 50.03
10:10:01.000855 50.02 50.03 50.05
10:10:01.000856 50.02 50.03 50.06
")
t <- as.POSIXct(paste0("2015-05-28 ", d$time))
#format(t, "%Y-%m-%d %H:%M:%OS9")
library(xts)
d_xts <- xts(d[,-1], order.by=t)
## Lag the signal by 50 microseconds:
signal_lag <- xts(d[,"signal"], order.by=t+0.000050)
merge_xts <- merge(d_xts, signal_lag)
## Carry last lagged value forward:
merge_xts$signal_lag <- na.locf(merge_xts$signal_lag)
## Finally subset back to only original rows:
merge_xts <- merge_xts[ !is.na(merge_xts$signal) ]
> merge_xts
bid_price ask_price
2015-05-28 10:10:01 50.02 50.05
2015-05-28 10:10:01 50.02 50.03
2015-05-28 10:10:01 50.02 50.03
signal signal_lag
2015-05-28 10:10:01 50.03 NA
2015-05-28 10:10:01 50.05 50.03
2015-05-28 10:10:01 50.06 50.03