Howwise RSS
Trading Software7 min read

Max Drawdown in Pandas: Tested Functions and Pitfalls

Short answer

To compute max drawdown in pandas, build an equity curve, take its running peak with cummax(), then compute equity / peak - 1 and call min(). Never apply cummax to raw returns, and include initial capital as the first peak.

Key takeaways
  • Max drawdown is (equity / equity.cummax() - 1).min(), and it must be applied to an equity curve, never to a returns Series.
  • Prepend the initial capital as a row so a loss on the first bar is measured against it.
  • Log returns need equity = start * exp(cumsum(r)), and log drawdowns need expm1 to become percentages.
  • Report time underwater in both calendar time and bars, and treat a drawdown that has not recovered as open, not as zero length.
  • When your number disagrees with another library, check sampling frequency, realised versus mark-to-market equity, and the initial-capital peak first.

How do I calculate max drawdown in pandas?

Drawdown is the distance between the equity curve and the highest value it has reached so far. In pandas that is three vectorised lines: a running peak, a ratio or difference against it, and a minimum.

The functions below are the base for the rest of this page. They sort the index, remove duplicate timestamps, drop NaN and inf values, and keep the initial capital in play as a peak.

import numpy as np
import pandas as pd

def clean_equity(eq: pd.Series) -> pd.Series:
    eq = eq.sort_index()
    eq = eq[~eq.index.duplicated(keep="last")]
    return eq.replace([np.inf, -np.inf], np.nan).dropna().astype(float)

def with_initial(eq: pd.Series, initial: float) -> pd.Series:
    """Prepend starting capital one bar before the first observation."""
    step = eq.index[1] - eq.index[0]
    first = pd.Series([initial], index=[eq.index[0] - step])
    return pd.concat([first, eq])

def drawdown(eq: pd.Series) -> pd.DataFrame:
    peak = eq.cummax()
    return pd.DataFrame({
        "equity": eq,
        "peak": peak,
        "dd_abs": eq - peak,                      # <= 0, in account currency
        "dd_pct": (eq / peak - 1).where(peak > 0)  # <= 0, NaN if peak <= 0
    })

def max_drawdown(eq: pd.Series):
    d = drawdown(eq)
    trough = d["dd_pct"].idxmin()
    peak_date = eq.loc[:trough].idxmax()
    return d["dd_pct"].min(), d["dd_abs"].min(), peak_date, trough
Warning: idxmax returns the first date among equal highs, and the percent trough and the absolute trough can be on different dates. Use the episode table below when the exact dates matter.

Why does my max drawdown differ from my backtest library?

Most disagreements come from a short list of input mistakes. Each one changes the number without raising an error, so check them in this order.

The most common one is running cummax() on returns. A returns Series has no memory of level, so its running maximum is meaningless. Convert first with start * (1 + r).cumprod().

PitfallWrongRightEffect
Returns used as equityr.cummax(); r / r.cummax() - 1eq = start * (1 + r).cumprod()Meaningless number, often near zero or huge
Log returns treated as simple(1 + r).cumprod() on log rstart * np.exp(r.cumsum())Small drift that grows with volatility
No initial capitaleq.cummax() starting at bar 1Prepend initial row, or peak.clip(lower=initial)First-bar loss missed, depth understated
Bars versus calendar timelen(episode)episode end minus start as TimedeltaWeekends and gaps distort durations
Open drawdown droppedOnly episodes with a recovery dateKeep end = NaT, measure to last barLongest underwater period understated
Closed-trade equityEquity updated at exit onlyMark-to-market equity every barIntrabar and open-trade losses hidden
Zero or negative equityeq / peak - 1Absolute drawdown, mask peak <= 0inf or NaN, or a sign flip

How do I get equity from returns, including log returns?

Simple returns compound multiplicatively. Log returns add, so the equity curve is the exponential of their cumulative sum.

In log space, drawdown is log(equity / peak), which equals cumulative log return minus its running maximum. That value is always at or below zero and is not a percentage. Convert it with expm1: a log drawdown of -0.3567 is expm1(-0.3567) = -0.30, a 30% drop.

Applying expm1 matters because log drawdowns look larger or smaller than they are. A 50% loss is -0.693 in log terms, and a 100% gain is +0.693.

def equity_from_returns(r: pd.Series, start=100_000.0, log=False) -> pd.Series:
    r = r.dropna()
    growth = np.exp(r.cumsum()) if log else (1 + r).cumprod()
    return with_initial(start * growth, start)

def log_drawdown_pct(logret: pd.Series) -> pd.Series:
    cum = logret.fillna(0).cumsum()
    cum = pd.concat([pd.Series([0.0], index=[cum.index[0] - (cum.index[1] - cum.index[0])]), cum])
    return np.expm1(cum - cum.cummax())   # identical to equity / peak - 1
Tip: Do not sum percent drawdowns or average them as if they were additive. A 20% loss followed by a 20% loss is a 36% drawdown (0.8 * 0.8 = 0.64), not 40%.

Percent or absolute drawdown: which should I use?

Percent drawdown is scale free, so it is the right choice for comparing strategies, sizing risk limits as a fraction of capital, and feeding ratios such as Calmar. Absolute drawdown is in account currency and depends directly on position size, so a strategy that trades twice the size shows twice the absolute drawdown for the same behaviour.

Absolute drawdown is the right tool when equity can be zero or negative, for example a futures account tracked as cumulative P&L starting at 0. There, equity / peak divides by zero or flips sign. The drawdown function above masks percent values where the peak is not positive, so you get NaN instead of misleading numbers.

For P&L-style curves, add the account's starting capital before measuring percent drawdown, or report only absolute drawdown. Check np.isfinite(d["dd_pct"]).all() as a guard before publishing a figure.

How do I build a table of drawdown episodes with recovery dates?

An episode starts at a peak, covers every bar below that peak, and ends at the first bar where equity is back at or above it. Labelling is a one-liner: (dd == 0).cumsum() increments on every new high, so all bars of one episode share a label with the peak row first.

The function below returns start (peak date), trough, end (recovery date, NaT if still open), depth, and lengths both in calendar time and in bars. It requires a unique index, which clean_equity guarantees.

def drawdown_episodes(eq: pd.Series) -> pd.DataFrame:
    peak = eq.cummax()
    dd = (eq / peak - 1).where(peak > 0)
    label = (dd == 0).cumsum()
    idx, rows = eq.index, []
    for _, g in dd.groupby(label):
        if len(g) < 2:
            continue                       # no bar below the peak
        start, trough = g.index[0], g.idxmin()
        p0 = idx.get_loc(start)
        end_pos = p0 + len(g)              # first bar back at/above the peak
        end = idx[end_pos] if end_pos < len(idx) else pd.NaT
        last = end if pd.notna(end) else idx[-1]
        rows.append({
            "start": start, "trough": trough, "end": end,
            "peak_equity": eq.loc[start], "trough_equity": eq.loc[trough],
            "depth_pct": g.min(),
            "depth_abs": eq.loc[trough] - eq.loc[start],
            "peak_to_trough": trough - start,
            "time_underwater": last - start,          # open: measured to last bar
            "bars_to_trough": idx.get_loc(trough) - p0,
            "bars_underwater": (end_pos if pd.notna(end) else len(idx) - 1) - p0,
            "recovered": pd.notna(end),
        })
    return pd.DataFrame(rows).sort_values("depth_pct").reset_index(drop=True)

# Synthetic test with a hand-checkable answer
idx = pd.date_range("2024-01-01", periods=8, freq="D")
eq = pd.Series([100, 120, 90, 100, 120, 150, 105, 120], index=idx, dtype=float)
ep = drawdown_episodes(eq)
assert abs(ep.loc[0, "depth_pct"] - (-0.30)) < 1e-12      # 150 -> 105
assert ep.loc[0, "recovered"] == False                      # still open
assert abs(ep.loc[1, "depth_pct"] - (-0.25)) < 1e-12      # 120 -> 90
assert ep.loc[1, "end"] == pd.Timestamp("2024-01-05")      # 120 >= 120
assert ep.loc[1, "time_underwater"] == pd.Timedelta(days=3)
assert ep.loc[0, "depth_abs"] == -45.0
Tip: By hand: the first peak is 120 and the trough is 90, which is -25%, recovered on day 5 when equity reaches 120 again. The second peak is 150 and the trough is 105, which is -30% or -45 absolute, still open on the last bar.

How do I find the longest time underwater?

Sort the episode table by time_underwater (or bars_underwater) instead of depth. The deepest drawdown is often not the longest one.

Keep three durations apart. Peak to trough is the fall, trough to recovery is the climb back, and peak to recovery is the full time underwater that most people mean. An open episode has no recovery, so it is measured to the last bar and flagged recovered = False. It can still be the longest, so never filter it out.

Calendar time and bars answer different questions. On daily data with weekends, 10 bars can span 14 calendar days, and holidays add more. Use calendar time when comparing with a broker report, and bars when comparing strategies on the same grid. Intraday data needs bars or trading-time durations, because overnight gaps inflate the Timedelta.

longest_time = ep.sort_values("time_underwater", ascending=False).iloc[0]
longest_bars = ep.sort_values("bars_underwater", ascending=False).iloc[0]

Which data issues silently change max drawdown?

Drawdown is a path statistic, so anything that alters the path alters the number. NaNs are the first suspect: cummax skips them but the NaN row stays NaN, and forward-filling can hide a gap that should not exist. Decide explicitly between dropna and ffill, and document it.

Unsorted or duplicated timestamps break cummax ordering and get_loc. Sort, then deduplicate, as clean_equity does. Mixed timezones need conversion to one zone with tz_convert before sorting.

Sampling frequency matters because a daily close misses intraday lows. The same strategy can show a deeper maximum drawdown on 1-minute equity than on daily closes, and finer sampling can never produce a smaller one, only equal or larger. Always state the frequency next to the figure.

Realised (closed-trade) equity ignores the floating loss on open positions, so it can show a much shallower drawdown than mark-to-market equity. Broker reports often use balance, equity, or end-of-day values. Confirm which one you are comparing against.

  1. Confirm both sides use the same series: balance versus equity, closed trades versus marked to market.
  2. Match frequency and timestamp convention, such as daily close versus intraday, and one timezone.
  3. Check initial capital is included, and that fees and slippage are applied consistently.
  4. Check simple versus log returns and whether the library compounds or sums returns.
  5. Compare the maximum percent and absolute drawdown separately, then the trough date.
  6. If a library gives a different figure, feed it your equity curve instead of your returns to isolate the cause.

What related metrics use drawdown, and how do I sanity-check them?

Calmar ratio is CAGR divided by the absolute value of max drawdown. Average drawdown is the mean of the episode depths, or the mean of the drawdown series if you want a time-weighted view, so state which one. The Ulcer index is the root mean square of percent drawdowns, which rewards short, shallow dips over long, deep ones.

For a cross-check, compare with empyrical's max_drawdown(returns) or vectorbt's drawdown stats on the same returns. Matching only works if they all use the same initial row and frequency. Any difference at the fourth decimal usually points to a missing initial capital row or different compounding.

def ratios(eq: pd.Series) -> dict:
    d = drawdown(eq)["dd_pct"]
    years = (eq.index[-1] - eq.index[0]).total_seconds() / (365.25 * 86400)
    cagr = (eq.iloc[-1] / eq.iloc[0]) ** (1 / years) - 1
    mdd = d.min()
    return {
        "max_dd": mdd,
        "calmar": cagr / abs(mdd) if mdd < 0 else np.nan,
        "ulcer": np.sqrt(((d * 100) ** 2).mean()),
        "avg_dd_series": d.mean(),
    }

# Underwater plot
ax = (drawdown(eq)["dd_pct"] * 100).plot.area(color="tab:red", alpha=0.4)
ax.set_ylabel("Drawdown (%)")

Common questions

Can I calculate max drawdown directly from a returns Series?

Yes, but convert to equity first: (1 + r).cumprod(), prepend 1.0 as the starting level, then use cummax. Calling cummax or min on returns gives a number that has no relation to drawdown.

Why is my max drawdown understated when the first bar loses money?

Without the initial capital as a row, the first bar's equity becomes the first peak, so the loss from the starting level is never counted. Prepend the starting capital or clip the peak at the initial value.

How do I get the recovery date of the worst drawdown?

Take the first date after the trough where equity is at or above the prior peak value. In the episode table this is the end column, and it is NaT if the drawdown is still open.

Does max drawdown change with data frequency?

Yes. Daily closes miss intraday lows, so intraday equity gives an equal or deeper maximum drawdown. Quote the sampling frequency with every figure.

Is the Calmar ratio computed with percent or absolute drawdown?

It uses percent drawdown, as an absolute value: CAGR divided by abs(max drawdown). Absolute currency drawdown would make the ratio depend on account size.

Related topics:pandasdrawdownbacktestingrisk metricspython