因此,我在loop
(Generating all realized and unrealized trades using sql?)中的类似问题中看到了SQL
的解决方案
我知道如何使用循环来解决此问题(您可能会蛮力地以逻辑方式计算已实现交易的FIFO记帐方式)。我有兴趣尝试在R中找到矢量化解决方案。
假设我的数据采用以下格式:
structure(list(Symbol = structure(c(1L, 1L, 1L, 1L, 1L), .Label = "AAPL", class = "factor"),
TradeDate = structure(c(1L, 1L, 1L, 1L, 1L), .Label = "2018-06-27", class = "factor"),
Date.Time = structure(c(2L, 3L, 3L, 4L, 4L), .Label = c("2018-06-27;103743",
"2018-06-27;131314", "2018-06-27;132000", "2018-06-27;153317"
), class = "factor"), OrderTime = structure(c(2L, 3L, 3L,
4L, 4L), .Label = c("2018-06-27;102850", "2018-06-27;130954",
"2018-06-27;132000", "2018-06-27;153018"), class = "factor"),
Buy.Sell = structure(c(1L, 1L, 1L, 2L, 2L), .Label = c("BUY",
"SELL"), class = "factor"), Quantity = c(539L, 8L, 100L,
-200L, -447L), Price = c(185, 184.4, 184.3969, 185.3, 185.3
), Proceeds = c(-99715, -1475.2, -18439.69, 37060, 82829.1
), Commission = c(-2.695, -1, 0, -1.50558, -3.3649713)), .Names = c("Symbol",
"TradeDate", "Date.Time", "OrderTime", "Buy.Sell", "Quantity",
"Price", "Proceeds", "Commission"), class = c("data.table", "data.frame"
), row.names = c(NA, -5L), .internal.selfref = <pointer: 0x03f524a0>)
Symbol TradeDate Date.Time OrderTime Buy.Sell Quantity Price Proceeds Commission
1: AAPL 2018-06-27 2018-06-27;131314 2018-06-27;130954 BUY 539 185.0000 -99715.00 -2.695000
2: AAPL 2018-06-27 2018-06-27;132000 2018-06-27;132000 BUY 8 184.4000 -1475.20 -1.000000
3: AAPL 2018-06-27 2018-06-27;132000 2018-06-27;132000 BUY 100 184.3969 -18439.69 0.000000
4: AAPL 2018-06-27 2018-06-27;153317 2018-06-27;153018 SELL -200 185.3000 37060.00 -1.505580
5: AAPL 2018-06-27 2018-06-27;153317 2018-06-27;153018 SELL -447 185.3000 82829.10 -3.364971
我想要的结果看起来像这样:
Symbol Buy.Sell Quantity Price Proceeds Commission BUYTIME SellPrice SELLTIME PROFIT
1: AAPL BUY 539 185.0000 -99715.00 -2.695 2018-06-27 13:20:00 185.3 2018-06-27 15:33:17 161.70
2: AAPL BUY 8 184.4000 -1475.20 -1.000 2018-06-27 13:20:00 185.3 2018-06-27 15:33:17 7.20
3: AAPL BUY 100 184.3969 -18439.69 0.000 2018-06-27 10:37:43 185.3 2018-06-27 15:33:17 90.31
在这里,我们将购买的AAPL的前539只股票与前200只的配对。使用先进先出会计。然后继续出售剩余的447。我们的第一层现在剩下539-200 = 339只股票。因此我们也出售第二批447卖出的产品。剩下447-339 =108。然后我们卖出下一个8的买单。最后,我们卖出最后一个100。在这个例子中,所有的卖价都相同。但这可能有所不同!
我正在考虑在cumsum
上使用Quantity
,以找出Quantity
的累积总和为0的点。在这些点之间是所有先前的头寸都被平仓的(因为我有按时间顺序过滤的数据)。我不确定从这里去哪里。
一旦找到一个解决方案的解决方案,我认为使用data.table
参数将by
与其他解决方案一起应用于整个表很容易。