# Drawdown Chart in Python: Underwater Plot and Maximum Drawdown with pandas

> Make a drawdown chart in Python. Compute drawdown with pandas cummax, plot the underwater curve, mark the maximum drawdown and list the worst drawdown periods with their recovery times.

Source: https://www.pythoncharts.com/python/drawdown-chart-python/ | Published: 2026-12-05 | Author: Alex Scott | Category: Python | Tags: drawdown, underwater-plot, maximum-drawdown, cummax, stock, financial-chart, matplotlib, pandas, time-series

To make a drawdown chart in Python, compute `drawdown = price / price.cummax() - 1`, which gives the percentage below the highest price so far, then draw it with `ax.fill_between(drawdown.index, drawdown, 0)`. The result is often called an underwater plot: it sits at zero whenever the price is at a new high and dips below zero while you are waiting to get back. The lowest point of the curve is the maximum drawdown, the standard "how bad did it get" number for a stock, fund or strategy.

## Quick Example

The prices are simulated, 8 years of daily values for a growth portfolio. Replace `price` with your own Series of prices or portfolio values.

```python
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

rng = np.random.default_rng(1)
dates = pd.bdate_range("2018-01-01", periods=2080, name="Date")
daily_vol = np.where((np.arange(2080) // 260) % 3 == 1, 0.019, 0.010)  # every third year is turbulent
price = pd.Series(100 * np.exp(np.cumsum(rng.normal(0.0005, daily_vol))), index=dates, name="Growth")

drawdown = price / price.cummax() - 1
trough = drawdown.idxmin()

fig, ax = plt.subplots(figsize=(10, 4.5))
ax.fill_between(drawdown.index, drawdown, 0, color="#b5443b", alpha=0.45)
ax.plot(drawdown, color="#8c2f28", lw=0.8)
ax.annotate(f"Max drawdown {drawdown.min():.1%}\n{trough:%b %d, %Y}", xy=(trough, drawdown.min()),
            xytext=(30, 30), textcoords="offset points", arrowprops=dict(arrowstyle="->"),
            bbox=dict(fc="white", ec="none", alpha=0.85))
ax.yaxis.set_major_formatter("{x:.0%}")
ax.set_ylabel("Drawdown from previous high")
ax.margins(y=0.15)
plt.show()
```

![Underwater chart of drawdowns for a simulated portfolio, a red area hanging below zero with the deepest point annotated](https://www.pythoncharts.com/python/drawdown-chart-python/images/drawdown-quick-example.png)

The curve touches 0% only on days when the portfolio closed at a new high, which is just 5.5% of the 2,080 days here. The maximum drawdown is −35.3%, reached on January 26, 2022. For 939 days (45%) the portfolio was more than 10% below its previous high. A line chart of the price hides how long that felt.

`price.cummax()` is the running maximum, so `price / price.cummax()` is 1 at a new high and falls below 1 otherwise. Subtract 1 to get a percentage. `drawdown.min()` is the maximum drawdown and `drawdown.idxmin()` is the date of the trough.

## How do I show the price and its drawdown together?

Put the price on top and the underwater curve below with a shared x-axis, then shade the worst drawdown on the price chart. The drawdown starts at the last high before the trough and ends when the price first gets back to that high:

```python
peak_date = price.loc[:trough].idxmax()
recovered = price.loc[trough:][price.loc[trough:] >= price.loc[peak_date]]
recovery_date = recovered.index[0] if len(recovered) else None   # None: still underwater
shade_end = recovery_date if recovery_date is not None else price.index[-1]

fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(10, 6.5), sharex=True, gridspec_kw={"height_ratios": [2, 1]})
ax1.plot(price, color="#2d3e50", lw=1.1)
ax1.axvspan(peak_date, shade_end, color="#b5443b", alpha=0.15, label="Worst drawdown")
ax1.scatter([peak_date, trough], [price[peak_date], price[trough]], color="#8c2f28", zorder=3)
ax1.set_ylabel("Portfolio value")
ax1.legend(loc="upper left")

ax2.fill_between(drawdown.index, drawdown, 0, color="#b5443b", alpha=0.45)
ax2.axvspan(peak_date, shade_end, color="#b5443b", alpha=0.15)
ax2.yaxis.set_major_formatter("{x:.0%}")
ax2.set_ylabel("Drawdown")
plt.tight_layout()
plt.show()
print(f"peak {peak_date:%Y-%m-%d}, trough {trough:%Y-%m-%d}, recovered {recovery_date:%Y-%m-%d}" if recovery_date is not None
      else f"peak {peak_date:%Y-%m-%d}, trough {trough:%Y-%m-%d}, not recovered")
```

![Two stacked charts: the portfolio value with its worst drawdown period shaded, and the underwater curve below with the same period shaded](https://www.pythoncharts.com/python/drawdown-chart-python/images/drawdown-price-and-underwater.png)

The worst drawdown began at the March 13, 2020 high, bottomed on January 26, 2022 and did not get back to the old high until December 29, 2022. That is 1,021 calendar days under water, nearly three years, for a loss that took 684 days to reach its low. The trough is only part of the story, which is why the shaded span matters. If the price never recovers, `recovery_date` is `None` and the shading runs to the last date.

## How do I list the worst drawdowns and how long they lasted?

Every stretch between two new highs is one drawdown episode. Label the episodes with `(price == price.cummax()).cumsum()`, then use `groupby` to get each episode's depth, trough date and the date it recovered. The first row of each group is the peak itself:

```python
def drawdown_table(price, top=5):
    peak = price.cummax()
    dd = price / peak - 1
    episode = (price == peak).cumsum()          # a new id starts at every new high
    starts = price.groupby(episode).head(1).index
    rows = []
    for i, (_, g) in enumerate(dd.groupby(episode)):
        if g.min() == 0:
            continue
        recovered = starts[i + 1] if i + 1 < len(starts) else pd.NaT
        rows.append({"peak": g.index[0].date(), "trough": g.idxmin().date(), "depth": g.min(),
                     "recovery": recovered.date() if pd.notna(recovered) else None,
                     "peak to recovery (days)": (recovered - g.index[0]).days if pd.notna(recovered) else None})
    return pd.DataFrame(rows).sort_values("depth").head(top).reset_index(drop=True)

table = drawdown_table(price)
print(table.to_string(formatters={"depth": "{:.1%}".format}))
```

```text
         peak      trough  depth    recovery  peak to recovery (days)
0  2020-03-13  2022-01-26 -35.3%  2022-12-29                   1021.0
1  2018-02-01  2019-05-07 -31.4%  2019-10-09                    615.0
2  2023-04-03  2023-09-28 -18.4%  2023-12-20                    261.0
3  2024-06-20  2024-07-11 -10.9%  2024-10-18                    120.0
4  2025-01-06  2025-02-05 -10.8%  2025-02-20                     45.0
```

Two drawdowns of more than 30% stand out. The depth and the recovery time are not the same ranking: the 2018 to 2019 episode was almost as deep but recovered in 615 days instead of 1,021. If an episode has not recovered by the end of the data, `recovery` is `None` and the days column is `NaN`. The days column prints as a float (`1021.0`) because pandas stores a missing value as `NaN`.

## How do I compare the drawdowns of two portfolios?

Plot both underwater curves on one axis. The one that stays closer to zero had the smoother ride, even if the final value is lower. Here a lower-risk "balanced" series is built from the same market shocks as the growth series, scaled to half the volatility:

```python
shocks = np.diff(np.log(price), prepend=np.log(price.iloc[0]))
balanced = pd.Series(100 * np.exp(np.cumsum(0.5 * shocks + 0.0001)), index=dates, name="Balanced")

fig, ax = plt.subplots(figsize=(10, 4.5))
for series, color in [(price, "#b5443b"), (balanced, "#2a7f8e")]:
    dd = series / series.cummax() - 1
    ax.plot(dd, color=color, lw=1.3, label=f"{series.name} (max {dd.min():.1%})")
ax.yaxis.set_major_formatter("{x:.0%}")
ax.set_ylabel("Drawdown from previous high")
ax.legend(loc="lower left")
plt.show()
```

![Line chart of two underwater curves, the growth portfolio reaching deeper drawdowns than the balanced portfolio](https://www.pythoncharts.com/python/drawdown-chart-python/images/drawdown-compare.png)

The balanced series has a maximum drawdown of −15.5% against −35.3% for the growth series, and ends at 218.7 instead of 316.7 (both start at 100). It still spends 93% of days below a previous high, so a lower drawdown does not mean it is always at a peak. Where the red line dives, the teal line dives less than half as far.

## What if I only have returns, not prices?

Build the equity curve first with `(1 + returns).cumprod()` (for simple returns) or `np.exp(log_returns.cumsum())` (for log returns). Then use the same formula:

```python
returns = price.pct_change().dropna()
equity = (1 + returns).cumprod()
dd_from_returns = equity / equity.cummax() - 1
print(f"{dd_from_returns.min():.4f} vs {drawdown.min():.4f}")
```

```text
-0.3528 vs -0.3528
```

## Practical Tips

- **Drawdown is measured from the running peak,** not from the start. `cummax()` is what makes it path-dependent, so the same final value can hide very different drawdowns.
- **Use the portfolio value, not just one stock's price,** if you want the drawdown of a strategy. Include dividends by using adjusted prices.
- **Max drawdown depends on the period you pick.** A longer window can only make it larger or equal. Quote the dates with the number.
- **Look at duration as well as depth.** A 15% drop that recovers in two months is a different experience from one that takes two years.
- **The calculation needs the whole history up to each date.** If you slice `price` to a window first, the "previous high" becomes the window's high, not the all-time one.

## Similar Topics

- [Bollinger Bands and Moving Averages in Python with pandas](https://www.pythoncharts.com/python/bollinger-bands-python/)
- [Plot the Distribution of Stock Returns in Python](https://www.pythoncharts.com/python/stock-returns-distribution-python/)
- [Candlestick Charts in Python with mplfinance](https://www.pythoncharts.com/python/mplfinance-candlestick-chart/)
