Win Rate in Python
The percentage of trades that close with a positive profit, independent of magnitude.
Definition
Win Rate (also called Hit Rate or Accuracy) is the proportion of closed trades that result in a net gain. It is one of the most intuitive but also most misunderstood metrics in algorithmic trading. A high win rate does not imply profitability — a strategy can win 90% of trades yet be a net loser if the 10% losing trades are catastrophically large. Win Rate must always be analyzed in conjunction with the average win/loss ratio to yield a complete picture of a strategy's edge.
Quantitative Formula
Where is the number of closed trades with a positive net P&L, and is the total number of closed trades in the evaluation period. The result is expressed as a percentage between 0% and 100%.
Why It Matters in Backtesting
Trend-following strategies typically have win rates of 30–45% but are highly profitable due to large average winners. Mean-reversion strategies often hit 60–75% win rates with small average wins. Blindly optimizing a backtest for win rate leads to strategies that cut winners early and hold losers too long — one of the most common over-fitting traps. Always pair Win Rate with Profit Factor and Expectancy.
Python Implementation
import pandas as pd
def calculate_win_rate(trade_pnl: pd.Series) -> dict:
"""
Calculates Win Rate and supporting statistics from closed trade P&L.
trade_pnl: Series where each value is the profit or loss of one closed trade.
"""
total_trades = len(trade_pnl)
winning_trades = (trade_pnl > 0).sum()
losing_trades = (trade_pnl < 0).sum()
avg_win = trade_pnl[trade_pnl > 0].mean()
avg_loss = trade_pnl[trade_pnl < 0].mean()
return {
"win_rate": winning_trades / total_trades if total_trades > 0 else 0.0,
"total_trades": total_trades,
"winning_trades": int(winning_trades),
"losing_trades": int(losing_trades),
"avg_win": avg_win,
"avg_loss": avg_loss,
"win_loss_ratio": abs(avg_win / avg_loss) if avg_loss != 0 else float('inf')
}Test this in a live environment
Stop running Jupyter notebooks locally. Paste this Win Rate code directly into Valetha's Strategy Lab and run a full historical backtest in seconds.
Open the Python Strategy Lab