'lagging' 不规则时间序列

'lagging' in irregular time series

我有 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

at 10:10:01.000856,虽然我在 50.06 有信号,但我无法使用它。我只能使用50微秒前的信号

所以我需要这个结果data.frame

at 10:10:01.000856,50微秒前,时间是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.lag 1 因为我最终会向下移动 50.05,而不是 50.03

time            bid_price   ask_price   signal  signal_from_lag1
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.05

这是我用来使值与最近的观察值保持一致的方法。它仅使用 xts 合并功能和 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) ]

生成的 merge_xts 对象:

> 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