Pythonintermediatepythonmetricsrisk
Max Drawdown in Python
A vectorized NumPy/pandas function to compute the maximum peak-to-trough drawdown of an equity curve.
1 min
Maximum drawdown is the largest peak-to-trough decline of an equity curve. This vectorized implementation runs in a single pass over a pandas Series.
import pandas as pd
def max_drawdown(equity: pd.Series) -> float:
"""Return the maximum drawdown as a positive fraction (0.25 == 25%)."""
if len(equity) < 2:
raise ValueError("equity needs at least two points")
running_peak = equity.cummax()
drawdowns = (running_peak - equity) / running_peak
return float(drawdowns.max())
if __name__ == "__main__":
curve = pd.Series([100, 120, 90, 110, 60, 80])
print(f"Max drawdown: {max_drawdown(curve):.1%}") # 50.0%How it works
cummax() gives the running peak at each point. Subtracting the equity and
dividing by the peak yields the drawdown at every bar; the maximum of that series
is the answer. Recovering from a drawdown d requires a gain of d / (1 - d) —
a 50% drawdown needs a 100% gain to get back to even.
Try the interactive version on the Max Drawdown Calculator.