Rajandran R Creator of OpenAlgo Sketchmaker, RagZ. Building GenAI Applications. Telecom Engineer turned Full-time Derivative Trader. Mostly Trading Nifty, Banknifty, High Liquid Stock Derivatives. Trading the Markets Since 2006 onwards. Using Market Profile and Orderflow for more than a decade. Designed and published 100+ open source trading systems on various trading tools. Now the recent curiosity on building Trading AI Agents.

Read Your Backtest Drawdown and the Equity Curve

7 min read

Backtest drawdown: a terracotta jar with a high-water ring and a lower water line on a sand field

In Build Smarter Backtest Signals with OpenAlgo Indicators we built a filtered signal on ICICIBANK: a trend filter, a 20-day breakout and an ADX strength check. It finished with a net profit of Rs 62,044.89 after charges. That number felt good, but a final profit says little about backtest drawdown: how far the account fell, and how long it spent getting back.

Did the account climb smoothly, or did it sink for years before recovering? This part answers that question with the result object, a drawdown series and two Plotly charts.

A quick disclosure: OpenAlgo is an open source project created by the founder of Marketcalls.

OpenAlgo: one API for 35+ Indian brokers

FREE AND OPEN SOURCE

OpenAlgo: one API for 35+ Indian brokers

Self-hosted algo trading platform. Send orders from Python, AmiBroker, TradingView, Excel or a no-code flow through one consistent API.

  • Unified REST and WebSocket API
  • Works with AmiBroker, TradingView, ChartInk and Excel
  • Sandbox mode to test before going live
Get OpenAlgo →by Marketcalls

In this series

1. Your First Backtest with the OpenAlgo Python SDK: EMA Crossover.
2. Build Smarter Backtest Signals with OpenAlgo Indicators.
3. Read Your Backtest Drawdown and the Equity Curve (this article).
4. Realistic costs and position sizing.
5. Options and multi-leg backtests.

Same strategy, same data

We do not change a single rule from Part 2, so every number here builds on what you already ran. Long only, ICICIBANK daily bars from 1 January 2021 to 23 November 2026, Rs 1,00,000 starting capital, data from Historify on your own OpenAlgo server, openalgo 2.3.0 on Python 3.13.

import os
import openalgo.backtest as bt
from openalgo import api, ta

client = api(api_key=os.getenv("OPENALGO_API_KEY", "your_api_key"),
             host="http://127.0.0.1:5000")

def trend_breakout(bars):
    ema20 = ta.ema(bars["close"], 20)
    ema50 = ta.ema(bars["close"], 50)
    _, _, adx = ta.adx(bars["high"], bars["low"], bars["close"], period=14)
    up20, _, _ = ta.donchian(bars["high"], bars["low"], period=20)
    entries = (ema20 > ema50) & (bars["close"] > up20.shift(1)) & (adx > 20)
    exits = ema20 < ema50
    return entries, exits

Strategy = bt.from_signals(trend_breakout, "ICICIBANK", "NSE", "D")
result = bt.backtest(Strategy, client, start="2021-01-01", end="2026-11-23",
                     capital=100_000, source="db")
print(result.summary())
Net profit   : Rs 62,044.89
Return       : 62.04%
Max drawdown : -24.83%
Trades       : 9 (56% won), 1 still open
Overfitting  : too few trades to judge (9 closed, 30 needed)

Step 1: Read the summary line by line

The five lines are a quick health check, and each one asks a different question.

  • Net profit and Return answer “did it make money?” These are after Indian charges and slippage on every fill, and they include the open position valued at the last close.
  • Max drawdown answers “how bad did it get?” That backtest drawdown is the worst fall from a peak: at its lowest, the account stood 24.83 percent below its best value so far.
  • Trades answers “how often did it act?” Nine closed trades, five winners.
  • Overfitting is the engine being honest. Its checks need at least 30 closed trades, so with nine it refuses to guess. Treat every figure below as a description of the past, not proof of an edge.

Step 2: Pull the figures that matter by name

result.metrics is a plain dict with more than a hundred figures. Percentages are stored as fractions, so :.2% prints them as percents. result.metrics_table() lists every one if you want to browse.

m = result.metrics
print(f"CAGR           : {m['cagr']:.2%}")
print(f"Sharpe ratio   : {m['sharpe']:.2f}")
print(f"Calmar ratio   : {m['calmar']:.2f}")
print(f"Exposure       : {m['exposure']:.0%}")
print(f"Average win    : Rs {m['average_win']:,.2f}")
print(f"Average loss   : Rs {m['average_loss']:,.2f}")
print(f"Payoff ratio   : {m['payoff_ratio']:.2f}")
print(f"Profit factor  : {m['profit_factor']:.2f}")
print(f"Expectancy     : Rs {m['expectancy']:,.2f}")
CAGR           : 8.54%
Sharpe ratio   : 0.56
Calmar ratio   : 0.34
Exposure       : 64%
Average win    : Rs 14,130.18
Average loss   : Rs -6,204.43
Payoff ratio   : 2.28
Profit factor  : 2.85
Expectancy     : Rs 5,092.58

Read them in pairs and they tell a story:

  • Win rate with payoff ratio. A 56 percent win rate is ordinary. What carries the strategy is that the average winner is 2.28 times the average loser.
  • Profit factor with expectancy. Every rupee lost on closed trades was matched by Rs 2.85 of wins, and the average closed trade added about Rs 5,093 after charges.
  • CAGR with Calmar. 8.54 percent a year sounds fine, until you see the Calmar ratio of 0.34. That is CAGR divided by the max drawdown: the worst fall took roughly three years of average return.
  • Exposure. The money was at work 64 percent of the time. The rest of the time it sat in cash.

Step 3: Build the equity curve and backtest drawdown yourself

The equity curve is the account value, cash plus shares, at every close. result.equity holds it, one row per day. From there, backtest drawdown takes two lines of pandas: track the highest value so far, then measure how far below it you are.

equity = result.equity["equity_rupees"]
peak = equity.cummax()            # best value reached so far
drawdown = equity / peak - 1      # 0 at a new high, negative below it

print(f"Hand-made max drawdown : {drawdown.min():.2%}")
print("Matches the engine:",
      bool((drawdown - result.performance.drawdown).abs().max() < 1e-9))
print(f"Days below a previous high: {(drawdown < 0).mean():.0%}")
Hand-made max drawdown : -24.83%
Matches the engine: True
Days below a previous high: 97%

Your hand-made series matches the engine’s own result.performance.drawdown exactly, so you know what the number means rather than trusting a black box.

That last line is the eye-opener. The account sat at its high-water mark on only 47 of 1,461 trading days, and four of those were the days before the first trade. A strategy can be profitable and still spend almost all its life below its best day. That is normal for trend following, and it is exactly what you need to be ready for.

Step 4: Plot it with Plotly

Two charts tell the whole story. The first draws the equity curve with its running peak; the shaded gap between them is the drawdown.

import plotly.graph_objects as go

fig = go.Figure()
fig.add_trace(go.Scatter(x=peak.index, y=peak, name="Running peak",
                         line=dict(color="#9aa5b1", dash="dot")))
fig.add_trace(go.Scatter(x=equity.index, y=equity, name="Account value",
                         fill="tonexty", fillcolor="rgba(214,69,69,0.18)",
                         line=dict(color="#1b9e52", width=4)))
fig.update_layout(template="plotly_white", title="Equity curve and running peak")
fig.write_image("equity_and_peak.png", width=1600, height=1000)

The second is the underwater chart: the drawdown series itself, in percent. Zero means a new high; everything below is time spent recovering.

fig2 = go.Figure(go.Scatter(x=drawdown.index, y=drawdown * 100, fill="tozeroy",
                            fillcolor="rgba(214,69,69,0.30)",
                            line=dict(color="#b83232")))
fig2.update_layout(template="plotly_white", title="Underwater chart",
                   yaxis_ticksuffix="%")
fig2.write_image("underwater_drawdown.png", width=1600, height=1000)

The two images above are the styled charts written by the full script at the end, which labels the 917-day spell under the October 2021 high and marks the three deepest episodes.

Step 5: List the worst episodes

drawdown_details ranks each fall from a peak, with when it bottomed and when it recovered. The table below lists the three worst backtest drawdown episodes.

worst = result.performance.drawdown_details(3)
print(worst[["start", "trough", "end", "depth", "days"]].to_string())
RankPeakTroughRecoveredDepthDays
125 Oct 202124 Feb 202229 Apr 2024-24.83%917
215 Feb 20214 May 202125 Oct 2021-22.24%252
323 Jul 20254 Nov 2026not yet-13.28%488

The deepest fall took only four months to reach bottom, but two and a half years to repair. Look at the flat stretches in the charts: those are spells in cash after an exit, when the drawdown simply froze. That deepest fall had two causes: the trade opened in April 2021 gave back a large part of its open profit after the October peak, before its exit in December, then the January 2022 trade lost Rs 13,566.45, the largest loss of the run.

The year by year view from result.performance.yearly_returns shows the same thing from another angle: 14.01 percent in 2021, then 1.68 and 2.18 percent in 2022 and 2023, before 27.91 percent in 2024. Most of the profit came in a single year.

What to look at first, every time

  • The backtest drawdown and its length, not just its depth. Ask honestly whether you would have kept running the strategy for 917 days below a high.
  • Calmar ratio to weigh yearly return against that worst fall.
  • Payoff ratio with win rate to see how the strategy actually makes money.
  • The overfitting line. Nine trades are a story, not evidence.

What is next

Every figure here already includes the default charges and slippage, and each trade put the whole account to work. In Part 4 we look at both properly: realistic cost settings and position sizing, and how they change the very backtest drawdown you just learned to read.

Full code

Here is the complete script. Set OPENALGO_API_KEY and run it on your own OpenAlgo server to reproduce every figure and both charts above.

# Backtesting with the OpenAlgo Python SDK, Part 3: Reading results, drawdown and the equity curve
# Same rules as Part 2, fixed before any run: EMA 20 above EMA 50 (trend), close above the
# prior 20-day Donchian high (breakout), ADX(14) above 20 (strength). Exit: EMA 20 below EMA 50.
# Data from Historify (source="db") on your own OpenAlgo server. No orders are placed.
# Set OPENALGO_API_KEY in your environment, then run this file to reproduce every figure
# and both charts (images/equity_and_peak.png and images/underwater_drawdown.png).
import os
import pandas as pd
import plotly.graph_objects as go
import openalgo.backtest as bt
from openalgo import api, ta

client = api(api_key=os.getenv("OPENALGO_API_KEY", "your_api_key"),
             host="http://127.0.0.1:5000")

SYMBOL, EXCHANGE = "ICICIBANK", "NSE"
START, END = "2021-01-01", "2026-11-23"
CAPITAL = 100_000


def trend_breakout(bars):
    ema20 = ta.ema(bars["close"], 20)
    ema50 = ta.ema(bars["close"], 50)
    _, _, adx = ta.adx(bars["high"], bars["low"], bars["close"], period=14)
    up20, _, _ = ta.donchian(bars["high"], bars["low"], period=20)
    entries = (ema20 > ema50) & (bars["close"] > up20.shift(1)) & (adx > 20)
    exits = ema20 < ema50
    return entries, exits


Strategy = bt.from_signals(trend_breakout, SYMBOL, EXCHANGE, "D")
result = bt.backtest(Strategy, client, start=START, end=END,
                     capital=CAPITAL, source="db")

# 1. The summary
print(result.summary())

# 2. Named figures from result.metrics
m = result.metrics
print(f"CAGR           : {m['cagr']:.2%}")
print(f"Sharpe ratio   : {m['sharpe']:.2f}")
print(f"Calmar ratio   : {m['calmar']:.2f}")
print(f"Exposure       : {m['exposure']:.0%}")
print(f"Win rate       : {m['win_rate']:.0%}")
print(f"Average win    : Rs {m['average_win']:,.2f}")
print(f"Average loss   : Rs {m['average_loss']:,.2f}")
print(f"Payoff ratio   : {m['payoff_ratio']:.2f}")
print(f"Profit factor  : {m['profit_factor']:.2f}")
print(f"Expectancy     : Rs {m['expectancy']:,.2f}")
print(f"Largest loss   : Rs {m['largest_loss']:,.2f}")

# 3. Drawdown figures
print(f"Max drawdown   : {m['max_drawdown']:.2%} (Rs {m['max_drawdown_amount']:,.2f})")
print(f"Peak / trough  : {m['max_drawdown_peak'].date()} / {m['max_drawdown_trough'].date()}")
print(f"Recovered on   : {m['max_drawdown_recovery'].date()}")
print(f"Days under peak: {m['max_drawdown_days']:.0f}")

# 4. The equity curve and the drawdown series, computed by hand
equity = result.equity["equity_rupees"]
peak = equity.cummax()
drawdown = equity / peak - 1
print(f"Hand-made max drawdown : {drawdown.min():.2%}")
print("Matches result.performance.drawdown:",
      bool((drawdown - result.performance.drawdown).abs().max() < 1e-9))
print(f"Days below a previous high: {(drawdown < 0).mean():.0%}")
print(f"Drawdown on {END}: {drawdown.iloc[-1]:.2%}")

# 5. The three deepest drawdown episodes
worst = result.performance.drawdown_details(3)
print(worst[["start", "trough", "end", "depth", "days"]].to_string())

# 6. Year by year
for year, value in result.performance.yearly_returns.items():
    print(year, f"{value:7.2%}")

# 7. Save the series, then write the two charts shown in the article
HERE = os.path.dirname(os.path.abspath(__file__))
if os.path.basename(HERE) == "scripts":
    DATA_DIR = os.path.join(HERE, "..", "data")
    IMG = os.path.join(HERE, "..", "images")
else:
    DATA_DIR = os.path.join(HERE, "data")
    IMG = os.path.join(HERE, "images")
os.makedirs(DATA_DIR, exist_ok=True)
os.makedirs(IMG, exist_ok=True)

curve = pd.DataFrame({"equity": equity, "peak": peak, "drawdown": drawdown})
curve.to_pickle(os.path.join(DATA_DIR, "equity_drawdown.pkl"))
worst.to_pickle(os.path.join(DATA_DIR, "worst.pkl"))

def naive_index(idx):
    if getattr(idx, "tz", None) is not None:
        return idx.tz_convert(None)
    return idx

def naive_ts(ts):
    ts = pd.Timestamp(ts)
    if ts.tzinfo is not None:
        ts = ts.tz_convert(None)
    return ts.normalize()

eq = equity.copy()
pk = peak.copy()
dd = drawdown.copy()
eq.index = naive_index(eq.index)
pk.index = naive_index(pk.index)
dd.index = naive_index(dd.index)

FONT = dict(family="Georgia, 'Times New Roman', serif", size=24, color="#1f2933")

def style(fig, title, ytitle):
    fig.update_layout(template="plotly_white", font=FONT, paper_bgcolor="#fbfaf7",
                      plot_bgcolor="#fbfaf7",
                      title=dict(text=title, font=dict(size=34), x=0.02, y=0.97),
                      yaxis_title=ytitle, width=1600, height=1000,
                      legend=dict(orientation="h", y=1.0, x=0.0, yanchor="bottom",
                                  font=dict(size=24)),
                      margin=dict(l=120, r=40, t=170, b=80))
    fig.update_xaxes(showgrid=False, linecolor="#9aa5b1", tickfont=dict(size=22))
    fig.update_yaxes(gridcolor="#e4e7eb", tickfont=dict(size=22))
    fig.add_annotation(text="openalgo.in", xref="paper", yref="paper", x=1.0, y=1.11,
                       xanchor="right", yanchor="bottom", showarrow=False,
                       font=dict(size=20, color="#7b8794"))

fig = go.Figure()
fig.add_trace(go.Scatter(x=pk.index, y=pk, name="Running peak",
                         line=dict(color="#9aa5b1", width=3, dash="dot")))
fig.add_trace(go.Scatter(x=eq.index, y=eq, name="Account value after charges",
                         fill="tonexty", fillcolor="rgba(214,69,69,0.18)",
                         line=dict(color="#1b9e52", width=5)))
fig.add_hline(y=100_000, line=dict(color="#444444", width=2, dash="dash"))
peak_2021 = pk.loc["2021-10-25"]
if hasattr(peak_2021, "iloc"):
    peak_2021 = peak_2021.iloc[0]
fig.add_annotation(x="2023-03-01", y=peak_2021 + 9000,
                   text="917 days below the October 2021 high", showarrow=False,
                   font=dict(size=24, color="#8a2c2c"))
style(fig, "ICICIBANK trend + breakout + ADX: equity curve and running peak",
      "Account value (Rs)")
fig.update_yaxes(tickformat=",.0f")
fig.write_image(os.path.join(IMG, "equity_and_peak.png"))

dd_pct = dd * 100
fig2 = go.Figure()
fig2.add_trace(go.Scatter(x=dd_pct.index, y=dd_pct, name="Drawdown", fill="tozeroy",
                          fillcolor="rgba(214,69,69,0.30)",
                          line=dict(color="#b83232", width=3)))
for rank, row in worst.iterrows():
    t = naive_ts(row["trough"])
    fig2.add_annotation(x=t, y=row["depth"] * 100, text=f"#{rank}: {row['depth']:.1%}",
                        showarrow=True, arrowhead=0, ax=0, ay=40 if rank != 3 else 45,
                        font=dict(size=24, color="#5c1414"),
                        bgcolor="rgba(251,250,247,0.9)")
style(fig2, "Underwater chart: how far the account sat below its last high",
      "Drawdown (%)")
fig2.update_yaxes(ticksuffix="%", range=[-30, 2])
fig2.update_layout(showlegend=False)
fig2.write_image(os.path.join(IMG, "underwater_drawdown.png"))
print("charts saved:", os.path.join(IMG, "equity_and_peak.png"),
      os.path.join(IMG, "underwater_drawdown.png"))
Python Elite membership

MEMBERSHIP

Python Elite membership

15 Python, AI and algo trading programs in one plan, including QuantFlow and AI Bootcamp live mentorship.

  • Python from fundamentals to trading apps
  • Backtesting, broker APIs and OpenAlgo
  • Live QuantFlow and AI Bootcamp sessions
View Python Elite →by Marketcalls

Learn by watching: free videos every week

Market Profile, order flow, Python, AI and OpenAlgo tutorials on YouTube.

Rajandran R Creator of OpenAlgo Sketchmaker, RagZ. Building GenAI Applications. Telecom Engineer turned Full-time Derivative Trader. Mostly Trading Nifty, Banknifty, High Liquid Stock Derivatives. Trading the Markets Since 2006 onwards. Using Market Profile and Orderflow for more than a decade. Designed and published 100+ open source trading systems on various trading tools. Now the recent curiosity on building Trading AI Agents.

Leave a Reply

Get Notifications, Alerts on Market Updates, Trading Tools, Automation & More