计算策略统计指标

calculate_statistics函数是基于逐日盯市盈亏情况(DateFrame格式)来计算衍生指标,如最大回撤、年化收益、盈亏比、夏普比率等。

  1. df["balance"] = df["net_pnl"].cumsum() + self.capital
  2. df["return"] = np.log(df["balance"] / df["balance"].shift(1)).fillna(0)
  3. df["highlevel"] = (
  4. df["balance"].rolling(
  5. min_periods=1, window=len(df), center=False).max()
  6. )
  7. df["drawdown"] = df["balance"] - df["highlevel"]
  8. df["ddpercent"] = df["drawdown"] / df["highlevel"] * 100
  9.  
  10. # Calculate statistics value
  11. start_date = df.index[0]
  12. end_date = df.index[-1]
  13.  
  14. total_days = len(df)
  15. profit_days = len(df[df["net_pnl"] > 0])
  16. loss_days = len(df[df["net_pnl"] < 0])
  17.  
  18. end_balance = df["balance"].iloc[-1]
  19. max_drawdown = df["drawdown"].min()
  20. max_ddpercent = df["ddpercent"].min()
  21.  
  22. total_net_pnl = df["net_pnl"].sum()
  23. daily_net_pnl = total_net_pnl / total_days
  24.  
  25. total_commission = df["commission"].sum()
  26. daily_commission = total_commission / total_days
  27.  
  28. total_slippage = df["slippage"].sum()
  29. daily_slippage = total_slippage / total_days
  30.  
  31. total_turnover = df["turnover"].sum()
  32. daily_turnover = total_turnover / total_days
  33.  
  34. total_trade_count = df["trade_count"].sum()
  35. daily_trade_count = total_trade_count / total_days
  36.  
  37. total_return = (end_balance / self.capital - 1) * 100
  38. annual_return = total_return / total_days * 240
  39. daily_return = df["return"].mean() * 100
  40. return_std = df["return"].std() * 100
  41.  
  42. if return_std:
  43. sharpe_ratio = daily_return / return_std * np.sqrt(240)
  44. else:
  45. sharpe_ratio = 0