我需要的是以有效的方式使用某种智能na.fill / nomatch执行完全外连接。我已经使用循环完成了它,但我想使用矩阵代数或data.table操作来加速这个过程。
以下数据是股票未结订单信息的样本,在要求未结订单和出价未结订单的数据集之间执行完全外部联接。要求数据集,B是出价。两个数据集都存储原子订单及其累积总和。任务是按累计值匹配所有询价单和出价单,反之亦然。 填充示例数据:
price = c(11.25,11.26,11.35,12.5,14.2)
amount = c(1.2,0.4,2.75,6.5,15.2)
A <- data.table(ask_price = price, ask_amount = amount, ask_cum_amount = cumsum(amount), cum_value = cumsum(price*amount), ask_avg_price = cumsum(price*amount)/cumsum(amount))
price = c(11.18,11.1,10.55,10.25,9.7)
amount = c(0.15,0.6,10.2,3.5,12)
B <- data.table(bid_price = price, bid_amount = amount, bid_cum_amount = cumsum(amount), cum_value = cumsum(price*amount), bid_avg_price = cumsum(price*amount)/cumsum(amount))
常规全外连接及其结果:
setkey(A, cum_value)
setkey(B, cum_value)
C <- merge(A,B,all=TRUE)
print(C)
na.fill / nomatch 伪代码公式,对于cum_value不匹配的每一行(ask或bid)(请记住,除了cum_value之外的所有其他字段都与ask OR bid相关):< / p>
avg_price["current NA"] <- cum_value["last non NA"]/cum_value["current NA"] * avg_price["last non NA"] + (1-cum_value["last non NA"]/cum_value["current NA"]) * price["next non NA"]
cum_amount["current NA"] <- cum_value["current NA"] / avg_price["current NA"]
预期结果:
D <- data.table(
cum_value = c(1.677,8.337,13.5,18.004,49.2165,115.947,130.4665,151.822,268.222,346.3065),
ask_price = c(NA,NA,11.25,11.26,11.35,NA,12.5,NA,NA,14.2),
ask_amount = c(NA,NA,1.2,0.4,2.75,NA,6.5,NA,NA,15.2),
ask_cum_amount = c(0.149066666666667,0.741066666666667,1.2,1.6,4.35,9.66496172396059,10.85,12.3126600707381,20.4097766460076,26.05),
ask_avg_price = c(11.25,11.25,11.25,11.2525,11.31414,11.9966331281534,12.02456,12.3305605066459,13.1418390633132,13.29392),
bid_price = c(11.18,11.1,NA,NA,NA,10.55,NA,10.25,9.7,NA),
bid_amount = c(0.15,0.6,NA,NA,NA,10.2,NA,3.5,12,NA),
bid_cum_amount = c(0.15,0.75,1.23858478466587,1.66517233847558,4.6230572556498,10.95,12.3652404387114,14.45,26.45,NA),
bid_avg_price = c(11.18,11.116,10.8995364444444,10.8120940902022,10.6458772362927,10.58877,10.5510685899445,10.50671,10.14072,NA)
)
print(D)
请注意,在预期结果中,最后一个NA仍为NA,这是因为相反的订单无法匹配,因为市场深度不足以以任何价格履行订单。
是否有可能使用矩阵代数或data.table操作或任何其他有效方法来获得预期结果,以避免在整个数据集上循环?
提前致谢
答案 0 :(得分:1)
将A
和B
与roll
合并,以查找上一个/下一个非NA价格。
E.g。查看这两个合并的bid_avg_price
输出值:
B[merge(A, B, all = T), roll = Inf]
B[merge(A, B, all = T), roll = -Inf]
这应该为您提供计算这些数量所需的所有信息。