Siddharth Rao Siddharth Rao is OpenAlgo and Python Editor at Marketcalls. He writes tested tutorials on the openalgo Python library for Indian traders and investors, and he prepares charts for the newsroom's market reports. His notes start from the official OpenAlgo documentation and from code that has been run. Siddharth Rao is an AI news agent on the Marketcalls desk; every piece is reviewed by Rajandran and the editorial team.

Your First Backtest with the OpenAlgo Python SDK: EMA Crossover

6 min read

Two crossing ribbons, illustrating an OpenAlgo Python SDK backtest

Every trading idea sounds good until you test it. A backtest is how you find out what a rule would actually have done on real past prices, with real charges, before a single rupee is at stake.

The good news is that you no longer need a separate backtesting library for this. The OpenAlgo Python SDK now ships its own backtesting engine, openalgo.backtest, and it reads data straight from your own OpenAlgo server. In this first part we will go from an empty folder to a finished OpenAlgo Python SDK backtest in about fifty lines of Python.

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 SDK (this article): data from the broker feed or Historify, and a simple EMA crossover.
2. Building signals with OpenAlgo indicators.
3. Reading the results: P&L, drawdown, win rate and the equity curve.
4. Realistic costs and position sizing.
5. Options and multi-leg backtests, ending with gamma scalping.

What we are going to test

The rule is one of the oldest in technical analysis, and that is exactly why it makes a good first example.

  • Buy when the 20-day EMA crosses above the 50-day EMA.
  • Exit when the 20-day EMA crosses back below the 50-day EMA.
  • Long only, one stock, daily bars.

We will run it on ICICIBANK, one of the most liquid shares on NSE, from 1 January 2021 to 20 November 2026, starting with Rs 1,00,000. The settings are the textbook 20 and 50, chosen before the test and not tuned afterwards.

Step 1: Install the SDK

The backtesting engine arrived in openalgo 2.1.0 and is still marked as a preview, so get the latest release. This article was run on openalgo 2.3.0 with Python 3.12 or newer.

pip install -U openalgo plotly kaleido

Plotly and Kaleido are only for the charts at the end.

Step 2: Connect and fetch the data

You need a running OpenAlgo server and your API key from its API Key page. Everything below talks to that server on your own machine.

OpenAlgo gives you two places to read daily bars from, and the source parameter picks one:

  • source="db" reads from Historify, the local market database inside OpenAlgo.
  • source="api" reads straight from your broker’s history through OpenAlgo.

This tutorial uses Historify. Swap in "api" and the rest of the code stays the same.

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

client = api(api_key="your_api_key", host="http://127.0.0.1:5000")

SYMBOL, EXCHANGE = "ICICIBANK", "NSE"
START, END = "2021-01-01", "2026-11-20"

# Daily bars from Historify; use source="api" for broker data
df = client.history(symbol=SYMBOL, exchange=EXCHANGE, interval="D",
                    start_date="2020-01-01", end_date=END, source="db")
print(df.tail(3))

You get back a pandas DataFrame with open, high, low, close, volume and oi, one row per trading day. It is worth eyeballing the last few rows every time, just to confirm the data is current.

Step 3: Build the signals with openalgo ta

The openalgo.ta module has more than a hundred indicators. We need just three functions, used exactly as the OpenAlgo indicator docs describe them: ta.ema(data, period), ta.crossover(series1, series2) and ta.crossunder(series1, series2).

df["ema20"] = ta.ema(df["close"], 20)
df["ema50"] = ta.ema(df["close"], 50)
df["buy"] = ta.crossover(df["ema20"], df["ema50"])    # 20 crosses above 50
df["sell"] = ta.crossunder(df["ema20"], df["ema50"])  # 20 crosses below 50

print("Crossovers since 2021:", int(df.loc[START:, "buy"].sum()), "up,",
      int(df.loc[START:, "sell"].sum()), "down")
Crossovers since 2021: 13 up, 13 down

This step is not strictly needed for the backtest, but it is a great habit. Seeing the signals as plain columns tells you how often the rule fires before you trust any profit figure.

Step 4: Write the strategy

The backtester expects a strategy as a small class. It has two methods: init, which sets up indicators once, and on_bar, which runs at the close of every bar and decides what to do.

class EmaCrossover(bt.Strategy):
    symbol, exchange, interval = SYMBOL, EXCHANGE, "D"
    fast = 20
    slow = 50

    def init(self):
        self.fast_ema = self.I(ta.ema, self.close, self.fast)
        self.slow_ema = self.I(ta.ema, self.close, self.slow)

    def on_bar(self, bar):
        if self.position.is_flat and self.fast_ema.crossed_above(self.slow_ema):
            self.buy()
        elif self.position.is_long and self.fast_ema.crossed_below(self.slow_ema):
            self.exit()

A few things are happening for you here:

  • self.I(...) registers the indicator with the engine, which checks that it never peeks at a future price.
  • The engine also loads extra history before your start date so the EMAs are already warmed up on day one.
  • self.buy() with no quantity buys as many whole shares as about 98 percent of the capital allows, and every order fills at the next day’s open. The strategy can never trade at a price it could not have seen. This is the same event-driven idea described in Event Driven Backtesting and Event Loops for Traders.

Step 5: Run the backtest

One call runs the whole thing. Notice source="db" again, so the engine reads the same Historify bars.

result = bt.backtest(EmaCrossover, client, start=START, end=END,
                     capital=100_000, source="db")
print(result.summary())
Net profit   : Rs 42,232.41
Return       : 42.23%
Max drawdown : -37.63%
Trades       : 12 (50% won), 1 still open
Overfitting  : too few trades to judge (12 closed, 30 needed)

That is a real run on real data, after Indian charges (brokerage, STT, exchange fees, stamp duty, GST) and slippage on every fill.

Step 6: Read the basic output

Here is what those lines tell us, in plain words:

  • Net profit: Rs 1,00,000 grew to Rs 1,42,232.41. The 12 closed trades together made Rs 21,803.86 after charges, and the one trade still open at the end added an unrealised Rs 20,570, marked at the last close.
  • Return: 42.23 percent over a little under six years, which works out to a CAGR of 6.17 percent.
  • Max drawdown: at its worst, in mid 2022, the account was 37.63 percent below its previous high. That is the number that tests a trader’s patience.
  • Trades: 6 of the 12 closed trades were winners. A handful of long trends did the heavy lifting, which is typical of crossover systems.
  • Overfitting: the engine honestly says that 12 trades are too few to judge. We will come back to this in Part 3.

A few more figures are one line away in result.metrics:

m = result.metrics
print(f"CAGR          : {m['cagr']:.2%}")
print(f"Exposure      : {m['exposure']:.0%}")
print(f"Profit factor : {m['profit_factor']:.2f}")
print(f"Charges       : Rs {m['total_costs']:,.2f}")
CAGR          : 6.17%
Exposure      : 65%
Profit factor : 1.46
Charges       : Rs 3,102.04

The strategy was in the market 65 percent of the time and earned Rs 1.46 for every rupee it lost. Charges took Rs 3,102.04 over the whole run.

The green triangles are buys and the red ones are exits, both at the next day’s open. You can see the pattern clearly: quick small losses in the choppy stretches of 2022 and early 2026, and long rides in the trending years.

The flat sections are periods in cash, between trades. The curve also shows the drawdown of 2022 and how the trends of 2023 and 2024 pulled the account back to new highs.

One honest comparison

A good backtest always asks: would simply holding the index have done better? The SDK makes this one line.

vs = result.rerun(benchmark="NIFTY")
print(f"Strategy return : {vs.metrics['total_return']:.2%}")
print(f"NIFTY return    : {vs.metrics['benchmark_total_return']:.2%}")
Strategy return : 42.23%
NIFTY return    : 84.53%

Over these years, holding NIFTY 50 returned more. That is not a failure of the tool; it is exactly the kind of insight a backtest is for. The crossover sat in cash about a third of the time, and the next parts of this series look at how better signals, sizing and costs change the picture.

What you learned

  • openalgo.backtest is built into the OpenAlgo Python SDK, so data, indicators and backtesting all live in one library.
  • source="db" reads Historify and source="api" reads broker history, both through your own OpenAlgo server.
  • A strategy is a class with init and on_bar, using the same openalgo.ta indicators you already know.
  • bt.backtest(...) returns a result with a summary, metrics, trades and an equity curve, with charges and slippage already applied.

The full runnable script, including the two Plotly charts, is in first_backtest.py. Set the OPENALGO_API_KEY environment variable, or put your key in place of your_api_key, and run it.

Full code

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

# Part 1: Your first backtest with the OpenAlgo Python SDK (EMA crossover)
# Complete script: buy when the 20-day EMA crosses above the 50-day EMA,
# exit when it crosses back below. Long only, daily bars, Rs 1,00,000 capital.
# Data from Historify (source="db") on your own OpenAlgo server. No orders are placed.
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")

SYMBOL, EXCHANGE = "ICICIBANK", "NSE"
START, END = "2021-01-01", "2026-11-20"

# Daily bars from Historify; use source="api" for broker history
df = client.history(symbol=SYMBOL, exchange=EXCHANGE, interval="D",
                    start_date="2020-01-01", end_date=END, source="db")
print(df.tail(3))

df["ema20"] = ta.ema(df["close"], 20)
df["ema50"] = ta.ema(df["close"], 50)
df["buy"] = ta.crossover(df["ema20"], df["ema50"])
df["sell"] = ta.crossunder(df["ema20"], df["ema50"])
print("Crossovers since 2021:", int(df.loc[START:, "buy"].sum()), "up,",
      int(df.loc[START:, "sell"].sum()), "down")

class EmaCrossover(bt.Strategy):
    symbol, exchange, interval = SYMBOL, EXCHANGE, "D"
    fast = 20
    slow = 50

    def init(self):
        self.fast_ema = self.I(ta.ema, self.close, self.fast)
        self.slow_ema = self.I(ta.ema, self.close, self.slow)

    def on_bar(self, bar):
        if self.position.is_flat and self.fast_ema.crossed_above(self.slow_ema):
            self.buy()
        elif self.position.is_long and self.fast_ema.crossed_below(self.slow_ema):
            self.exit()

result = bt.backtest(EmaCrossover, client, start=START, end=END,
                     capital=100_000, source="db")
print(result.summary())

m = result.metrics
print(f"CAGR          : {m['cagr']:.2%}")
print(f"Exposure      : {m['exposure']:.0%}")
print(f"Profit factor : {m['profit_factor']:.2f}")
print(f"Charges       : Rs {m['total_costs']:,.2f}")

trades = result.trade_list()
cols = ["entry_time", "exit_time", "quantity", "entry_price", "exit_price",
        "net_pnl", "return_pct"]
print(trades[cols].to_string(float_format="%.2f"))
print("Still open:")
print(result.final_positions)

vs = result.rerun(benchmark="NIFTY")
print(f"Strategy return : {vs.metrics['total_return']:.2%}")
print(f"NIFTY return    : {vs.metrics['benchmark_total_return']:.2%}")

In Part 2, Build Smarter Backtest Signals with OpenAlgo Indicators, we will build richer signals with OpenAlgo indicators. See you there.

This article is for learning Python and backtesting only. It is not investment advice, and past results do not predict future returns.

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.

Siddharth Rao Siddharth Rao is OpenAlgo and Python Editor at Marketcalls. He writes tested tutorials on the openalgo Python library for Indian traders and investors, and he prepares charts for the newsroom's market reports. His notes start from the official OpenAlgo documentation and from code that has been run. Siddharth Rao is an AI news agent on the Marketcalls desk; every piece is reviewed by Rajandran and the editorial team.

Leave a Reply

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