Blotter intraday realized PL

286 views Asked by At

This is a question about the realized PL of the transactions in the amzn_test demo of the blotter R package. The transactions are a sequence of 7 trades that open and close positions intraday. A call to getTxns('amzn_port', 'amzn') returns

                    Txn.Qty Txn.Price Txn.Fees Txn.Value Txn.Avg.Cost Net.Txn.Realized.PL
2010-01-14 00:00:00       0      0.00        0         0         0.00                   0
2010-01-14 10:18:50    -400    127.49        0    -50996       127.49               50996
2010-01-14 10:18:53     400    127.49        0     50996       127.49                   0
...

Why is Net.Txn.Realized.PL non-zero for the opening transaction and zero for the closing transaction? With daily transactions, the realized P&L would be non-zero on the day of the closing transaction.

I am running blotter 0.9.1666 on 64-bit Windows.

Thanks for your patience.

1

There are 1 answers

0
Joshua Ulrich On

This looks like a bug in addTxns because the net realized P&L looks reasonable if you call addTxn for each row in amzn.trades.

require(blotter)
# load the example data
data("amzn")
currency("USD")
stock("amzn",currency="USD",multiplier=1)
# Initialize the Portfolio
initPortf("amzn_port",symbols="amzn",initDate="2010-01-14")
initAcct("amzn_acct",portfolios="amzn_port",initDate="2010-01-14", initEq=10000)
# Add the transactions to the portfolio
for (i in 1:nrow(amzn.trades)) {
  x <- amzn.trades[i,]
  addTxn("amzn_port", "amzn", index(x), coredata(x$TxnQty), coredata(x$TxnPrice))
}
# update the portfolio`
updatePortf("amzn_port",Dates="2010-01-14")
getTxns("amzn_port", "amzn")

I'll investigate and report back once I've found/fixed the bug.


This is now fixed in revision 1693. Here's the patch:

--- pkg/blotter/R/addTxn.R  2015/04/15 02:33:20 1685
+++ pkg/blotter/R/addTxn.R  2015/08/09 16:29:59 1693
@@ -246,9 +246,11 @@
     NewTxns$Pos.Qty <- cumsum(initPosQty + NewTxns$Txn.Qty)
     # only pass non-zero initial position qty and average cost
     NewTxns$Pos.Avg.Cost <- .calcPosAvgCost_C(initPosQty[1], initPosAvgCost[1], NewTxns$Txn.Value, NewTxns$Pos.Qty, ConMult)
-    # need lagged position average cost
+    # need lagged position average cost and quantity
     lagPosAvgCost <- c(initPosAvgCost[1], NewTxns$Pos.Avg.Cost[-nrow(NewTxns)])
+    lagPosQty <- c(initPosQty[1], NewTxns$Pos.Qty[-nrow(NewTxns)])
     NewTxns$Gross.Txn.Realized.PL <- NewTxns$Txn.Qty * ConMult * (lagPosAvgCost - NewTxns$Txn.Avg.Cost)
+    NewTxns$Gross.Txn.Realized.PL[abs(lagPosQty) < abs(NewTxns$Pos.Qty) | lagPosQty == 0] <- 0
     NewTxns$Net.Txn.Realized.PL <- NewTxns$Gross.Txn.Realized.PL - NewTxns$Txn.Fees
     NewTxns$Con.Mult <- ConMult