计算策略盈亏情况
基于收盘价、当日持仓量、合约规模、滑点、手续费率等计算总盈亏与净盈亏,并且其计算结果以DataFrame格式输出,完成基于逐日盯市盈亏统计。
下面展示盈亏情况的计算过程
浮动盈亏 = 持仓量 (当日收盘价 - 昨日收盘价) 合约规模
实际盈亏 = 持仓变化量 (当时收盘价 - 开仓成交价) 合约规模
总盈亏 = 浮动盈亏 + 实际盈亏
净盈亏 = 总盈亏 - 总手续费 - 总滑点
- def calculate_pnl(
- self,
- pre_close: float,
- start_pos: float,
- size: int,
- rate: float,
- slippage: float,
- ):
- """"""
- self.pre_close = pre_close
- # Holding pnl is the pnl from holding position at day start
- self.start_pos = start_pos
- self.end_pos = start_pos
- self.holding_pnl = self.start_pos * \
- (self.close_price - self.pre_close) * size
- # Trading pnl is the pnl from new trade during the day
- self.trade_count = len(self.trades)
- for trade in self.trades:
- if trade.direction == Direction.LONG:
- pos_change = trade.volume
- else:
- pos_change = -trade.volume
- turnover = trade.price * trade.volume * size
- self.trading_pnl += pos_change * \
- (self.close_price - trade.price) * size
- self.end_pos += pos_change
- self.turnover += turnover
- self.commission += turnover * rate
- self.slippage += trade.volume * size * slippage
- # Net pnl takes account of commission and slippage cost
- self.total_pnl = self.trading_pnl + self.holding_pnl
- self.net_pnl = self.total_pnl - self.commission - self.slippage