计算策略盈亏情况

基于收盘价、当日持仓量、合约规模、滑点、手续费率等计算总盈亏与净盈亏,并且其计算结果以DataFrame格式输出,完成基于逐日盯市盈亏统计。

下面展示盈亏情况的计算过程

  • 浮动盈亏 = 持仓量 (当日收盘价 - 昨日收盘价) 合约规模

  • 实际盈亏 = 持仓变化量 (当时收盘价 - 开仓成交价) 合约规模

  • 总盈亏 = 浮动盈亏 + 实际盈亏

  • 净盈亏 = 总盈亏 - 总手续费 - 总滑点

  1. def calculate_pnl(
  2. self,
  3. pre_close: float,
  4. start_pos: float,
  5. size: int,
  6. rate: float,
  7. slippage: float,
  8. ):
  9. """"""
  10. self.pre_close = pre_close
  11.  
  12. # Holding pnl is the pnl from holding position at day start
  13. self.start_pos = start_pos
  14. self.end_pos = start_pos
  15. self.holding_pnl = self.start_pos * \
  16. (self.close_price - self.pre_close) * size
  17.  
  18. # Trading pnl is the pnl from new trade during the day
  19. self.trade_count = len(self.trades)
  20.  
  21. for trade in self.trades:
  22. if trade.direction == Direction.LONG:
  23. pos_change = trade.volume
  24. else:
  25. pos_change = -trade.volume
  26.  
  27. turnover = trade.price * trade.volume * size
  28.  
  29. self.trading_pnl += pos_change * \
  30. (self.close_price - trade.price) * size
  31. self.end_pos += pos_change
  32. self.turnover += turnover
  33. self.commission += turnover * rate
  34. self.slippage += trade.volume * size * slippage
  35.  
  36. # Net pnl takes account of commission and slippage cost
  37. self.total_pnl = self.trading_pnl + self.holding_pnl
  38. self.net_pnl = self.total_pnl - self.commission - self.slippage