我需要的是用某种智能 na.fill / nomatch 以一种有效的方式执行完全外连接。我已经使用循环完成了它,但我想使用矩阵代数或 data.table 操作来加速这个过程。
下面的数据是股票未结订单信息的样本,在询价未结订单和投标未结订单数据集之间执行完全外连接。A 数据集是询价,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 不匹配的每一行(询问或出价)(请记住,除 cum_value 之外的所有其他字段都与询问或出价有关):
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 操作或任何其他有效方法来避免循环整个数据集来获得预期的结果?
提前致谢