我有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发出信号,但我无法使用它。我只能在50微秒前使用信号
所以我需要这个结果data.frame
在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
是否有R / python解决方案生成结果data.frame?例如,假设我们首先将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
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句