PacktPublishing / Learn-Algorithmic-Trading

Learn Algorithmic Trading, Published by Packt
MIT License
802 stars 302 forks source link

volatility_mean_reversion_with_dynamic_risk_allocation wrong closed pnl calculation #11

Open bbbkbc opened 2 years ago

bbbkbc commented 2 years ago

Hi there, I checked this script, and i my opinion, there is a bug on a stage where open close pnl is calculated. As a solution i propose make something like that:

This section updates Open/Unrealized & Closed/Realized positions

  if position > 0:
    open_pnl = 0
    if sell_sum_qty > 0:  # long position and some sell trades have been made against it, close that amount based on how much was sold against this long position
      open_pnl = abs(sell_sum_qty) * (sell_sum_price_qty / sell_sum_qty - buy_sum_price_qty / buy_sum_qty)
    # mark the remaining position to market i.e. pnl would be what it would be if we closed at current price
    open_pnl += abs(sell_sum_qty - position) * (close_price - buy_sum_price_qty / buy_sum_qty)
  elif position < 0:
    open_pnl = 0
    if buy_sum_qty > 0:  # short position and some buy trades have been made against it, close that amount based on how much was bought against this short position
      open_pnl = abs(buy_sum_qty) * (sell_sum_price_qty / sell_sum_qty - buy_sum_price_qty / buy_sum_qty)
    # mark the remaining position to market i.e. pnl would be what it would be if we closed at current price
    open_pnl += abs(buy_sum_qty - position) * (sell_sum_price_qty / sell_sum_qty - close_price)
  else:
    # flat, so update closed_pnl and reset tracking variables for positions & pnls
    closed_pnl += open_pnl
    buy_sum_price_qty = 0
    buy_sum_qty = 0
    sell_sum_price_qty = 0
    sell_sum_qty = 0
    last_buy_price = 0
    last_sell_price = 0
    open_pnl = 0