计算策略统计指标
calculate_statistics函数是基于逐日盯市盈亏情况(DateFrame格式)来计算衍生指标,如最大回撤、年化收益、盈亏比、夏普比率等。
- df["balance"] = df["net_pnl"].cumsum() + self.capital
- df["return"] = np.log(df["balance"] / df["balance"].shift(1)).fillna(0)
- df["highlevel"] = (
- df["balance"].rolling(
- min_periods=1, window=len(df), center=False).max()
- )
- df["drawdown"] = df["balance"] - df["highlevel"]
- df["ddpercent"] = df["drawdown"] / df["highlevel"] * 100
- # Calculate statistics value
- start_date = df.index[0]
- end_date = df.index[-1]
- total_days = len(df)
- profit_days = len(df[df["net_pnl"] > 0])
- loss_days = len(df[df["net_pnl"] < 0])
- end_balance = df["balance"].iloc[-1]
- max_drawdown = df["drawdown"].min()
- max_ddpercent = df["ddpercent"].min()
- total_net_pnl = df["net_pnl"].sum()
- daily_net_pnl = total_net_pnl / total_days
- total_commission = df["commission"].sum()
- daily_commission = total_commission / total_days
- total_slippage = df["slippage"].sum()
- daily_slippage = total_slippage / total_days
- total_turnover = df["turnover"].sum()
- daily_turnover = total_turnover / total_days
- total_trade_count = df["trade_count"].sum()
- daily_trade_count = total_trade_count / total_days
- total_return = (end_balance / self.capital - 1) * 100
- annual_return = total_return / total_days * 240
- daily_return = df["return"].mean() * 100
- return_std = df["return"].std() * 100
- if return_std:
- sharpe_ratio = daily_return / return_std * np.sqrt(240)
- else:
- sharpe_ratio = 0