Since you want to evaluate the results over time, you will need to value open positions between trades.
Essentially, create an equity curve for each single-instrument trade; then sum these equity curves at every timestamp.
Here is example code how the equity curve could be computed with the PMwR
package, which I maintain. See the PMwR
manual for more details.
In the example, I assume you traded two stocks, A
and B
. For simplicity, I use numeric timestamps (but you could use Date
, POSIXct
, etc as well). I then compute the cumulative profit/loss for timestamps 1 to 10.
I start by putting the trades into journals.
library("PMwR")
A <- journal(instrument = "A",
timestamp = c(3.2, 5.1),
amount = c(1, -1),
price = c(99, 102))
## instrument timestamp amount price
## 1 A 3.2 1 99
## 2 A 5.1 -1 102
##
## 2 transactions
B <- journal(instrument = "B",
timestamp = c(1.1, 4.1),
amount = c(1,-1),
price = c(12,12))
## instrument timestamp amount price
## 1 B 1.1 1 12
## 2 B 4.1 -1 12
##
## 2 transactions
The prices to be used for valuation are stored in a matrix prices
, with column names matching the stocks' names.
prices <- cbind(A = 101:110,
B = 11:20)
## A B
## [1,] 101 11
## [2,] 102 12
## [3,] 103 13
## [4,] 104 14
## [5,] 105 15
## [6,] 106 16
## [7,] 107 17
## [8,] 108 18
## [9,] 109 19
##[10,] 110 20
I can then look at aggregated profit/loss...
pl(c(A,B))
##
## A
## P/L total 3
## average buy 99
## average sell 102
## cum. volume 2
##
## B
## P/L total 0
## average buy 12
## average sell 12
## cum. volume 2
##
## 'P/L total' is in units of instrument;
## 'volume' is sum of /absolute/ amounts.
... and also at profit/loss over time.
profit_loss <- pl(c(A,B),
along.timestamp = 1:10,
vprice = prices)
rowSums(sapply(profit_loss, `[[`, "pl"))
## 1 2 3 4 5 6 7 8 9 10
## 0 0 1 7 6 3 3 3 3 3