您如何根据交易历史计算交易者的盈亏?

How do you calculate a trader's P&L given their trade history?

给定一系列交易

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

您如何以编程方式计算此交易者随时间变化的业绩百分比?有图书馆可以为您做这件事吗?

我们的想法是使用此数据创建随时间变化的 % P&L 图表,以了解该交易者的表现并能够将其与其他交易者进行比较。

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
}