Given a series of trades
Symbol,Quantity,Price,Side
SPY,100,127,Buy
SPY,87,125,Sell
SPY,109,115,Sell
SPY,122,95,Sell
SPY,66,89,Buy
SPY,101,175,Sell
How do you programmatically calculate this trader's performance over time in % terms? Are there libraries that can do this for you?
The idea is to use this data to create a % P&L chart over time to get an idea of this trader's performance and be able to compare it to other traders.
variables used:
- pos_base = 0 // base price of the position, at any given time
- pos_amount = 0 // position amount (negative for shorts), at any given time
- pl = 0 // total P/L, at any given time, fees already removed
- tot_fees = 0 // total fees paid
- volume = 0 // total volume exchanged
RECORD_EXECUTION(side, amount, price, fee_rate)
{
// normalize amount
n_amount = amount * (side == buy ? 1.0 : -1.0)
// remember base price and amount before changing them
prev_base = pos_base
prev_amount = pos_amount
// update 'virtual' position
pos_amount += n_amount
pos_base = pos_amount == 0.0 ? 0.0 : (prev_amount * prev_base + n_amount * price) / pos_amount
if ((prev_amount < 0.0 && pos_amount > 0.0) || (prev_amount > 0.0 && pos_amount < 0.0)) pos_base = price
// calculate fees paid
fees_paid = amount * price * fee_rate
tot_fees += fees_paid
// update P/L
if (prev_amount < 0.0 && pos_amount >= 0.0) pl += (prev_base - price) * -prev_amount // short closed
if (prev_amount > 0.0 && pos_amount <= 0.0) pl += (price - prev_base) * prev_amount // long closed
pl -= fees_paid
// keep track of total volume
volume += amount
}