Updated 25 November 2026: added the full code.
In Part 1 we ran a plain 20 and 50 day EMA crossover on ICICIBANK. It worked, but it showed the classic weakness of a single signal: it bought every crossover, including the ones that fizzled out in choppy markets.
This part fixes that the way traders do: by combining OpenAlgo indicators. You will turn openalgo.ta outputs into True or False arrays, stack them into one entry rule, and hand them straight to the backtester.
A quick disclosure: OpenAlgo is an open source project created by the founder of Marketcalls.
In this series
1. Your first backtest with the OpenAlgo SDK (EMA crossover).
2. Signals with OpenAlgo indicators (this article).
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.
The rules, stated up front
We fix the rules before running anything, so the test cannot be tuned to the answer. Each piece does one job.
- Trend filter: the 20-day EMA is above the 50-day EMA. This is Part 1’s crossover, turned from an event into a state.
- Breakout trigger: today’s close is above the highest high of the previous 20 days (the upper Donchian channel).
- Strength filter: ADX(14) is above 20, so there is a trend worth riding.
- Entry: all three are true at the close. Buy at the next day’s open.
- Exit: the 20-day EMA falls below the 50-day EMA.
Long only, ICICIBANK, daily bars from 1 January 2021 to 23 November 2026, Rs 1,00,000 starting capital, all of it in each trade. The settings are textbook values, not optimised.
Step 1: Fetch the data
The setup is the same as Part 1. This run used openalgo 2.3.0 on Python 3.13.
pip install -U openalgo plotly kaleido
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-23"
# 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")
source="db" reads Historify, the market database inside OpenAlgo. Switch to source="api" to read from your broker’s history through OpenAlgo instead.
Step 2: Indicator outputs as columns
Every function below is used exactly as the OpenAlgo indicator docs give it. Two details matter.
ta.adx returns three values, +DI, -DI and ADX, with ADX last. ta.donchian also returns three: upper, middle and lower. Unpack them and keep only what you need with _.
df["ema20"] = ta.ema(df["close"], 20)
df["ema50"] = ta.ema(df["close"], 50)
_, _, df["adx"] = ta.adx(df["high"], df["low"], df["close"], period=14)
df["dc_up20"], _, _ = ta.donchian(df["high"], df["low"], period=20)
Step 3: Turn indicators into True or False arrays
This is the heart of the lesson. A signal is just a comparison, and a comparison on a pandas column gives you a column of True and False, one per day.
uptrend = df["ema20"] > df["ema50"] # trend filter
breakout = df["close"] > df["dc_up20"].shift(1) # close above prior 20-day high
strong = df["adx"] > 20 # trend strength filter
entries = uptrend & breakout & strong
exits = df["ema20"] < df["ema50"]
Three habits are worth building here:
- Use
&,|and~, notand,orandnot. The symbols work element by element. - Mind the
.shift(1). The Donchian upper band includes today’s high, so a close can never exceed it. Yesterday’s band asks the real question: did today break the previous 20-day high? - Warm-up is safe. Rows where an indicator is still
NaNcompare as False, so nothing fires early.
Now count how hard each filter works:
w = slice(START, END)
print("Breakout days :", int(breakout.loc[w].sum()))
print(" ...in an uptrend :", int((breakout & uptrend).loc[w].sum()))
print(" ...with ADX above 20 :", int(entries.loc[w].sum()))
Breakout days : 111
...in an uptrend : 91
...with ADX above 20 : 63
Out of 1,461 trading days, the stock closed above its prior 20-day high on 111. The trend filter removed 20 and the ADX filter 28 more. This funnel shows how selective a rule is before you look at any profit.
Step 4: Hand the arrays to the backtester
In Part 1 we wrote a class with init and on_bar. When the rules are pure conditions there is a shorter way: bt.from_signals. You give it a function that receives the bars as a DataFrame and returns (entries, exits).
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")
The engine does careful work for you:
- It runs your function on extra history first, so indicators are warmed up on day one.
- It reruns the function on cut-off copies of the data and stops with an error if any value changes, a built-in check against peeking at future prices.
- A True entry while flat buys and a True exit while long sells, at the next bar’s open.
Step 5: Run it
result = bt.backtest(Strategy, client, start=START, end=END,
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)
These figures are after Indian charges and slippage on every fill. result.metrics adds a CAGR of 8.54 percent, 64 percent time in the market, a profit factor of 2.85 and Rs 2,595.24 in charges. The nine closed trades made Rs 45,833.21 net, and the position still open showed an unrealised Rs 16,380 at the last close.

Did the filters help?
The fair test is Part 1’s plain crossover on the same stock and the same dates. With from_signals that is just another small function returning ta.crossover and ta.crossunder, wrapped as pandas Series because these helpers return NumPy arrays.
import pandas as pd
def plain_crossover(bars):
ema20 = ta.ema(bars["close"], 20)
ema50 = ta.ema(bars["close"], 50)
up = pd.Series(ta.crossover(ema20, ema50), index=bars.index)
down = pd.Series(ta.crossunder(ema20, ema50), index=bars.index)
return up, down
base = bt.backtest(bt.from_signals(plain_crossover, SYMBOL, EXCHANGE, "D"),
client, start=START, end=END, capital=100_000, source="db")
| Through 23 Nov 2026 | Plain crossover | Trend + breakout + ADX |
|---|---|---|
| Net profit | Rs 37,778.41 | Rs 62,044.89 |
| Max drawdown | -37.63% | -24.83% |
| Closed trades (won) | 12 (50%) | 9 (56%) |
| Profit factor | 1.46 | 2.85 |
| Charges | Rs 3,102.04 | Rs 2,595.24 |
The plain crossover’s numbers differ slightly from Part 1 because this window runs three trading days longer, to 23 November.

The biggest difference came in 2022. The plain crossover kept buying in the choppy first half of the year; the breakout and ADX filters skipped most of those entries and waited for a stronger move.
A word of caution
Filters are not magic. A similar breakout design tested on LT over the same years (200-day SMA trend filter, ADX above 20, 20-day breakout entry, 10-day breakdown exit) lost Rs 5,781.20 after costs. An idea can work on one stock and fail on another, and nine closed trades prove nothing yet, as the engine’s overfitting line says.
What you learned
- A comparison turns any
openalgo.taoutput into a signal; combine signals with&,|and~. bt.from_signalsturns a function returning(entries, exits)into a strategy.- Always compare a new rule with a simpler baseline on the same dates.
For another worked example with the same backtester, see the Supertrend backtest on SBIN with the OpenAlgo Python SDK. The event-driven idea behind on_bar is also covered in Event Driven Backtesting and Event Loops for Traders.
The full script, including both Plotly charts, is in signals_backtest.py and charts.py. Set OPENALGO_API_KEY and run them on your own OpenAlgo server.
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.
# Backtesting with the OpenAlgo Python SDK, Part 2: Signals with OpenAlgo indicators
# Complete script: 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.
import os
import pandas as pd
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
# 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["adx"] = ta.adx(df["high"], df["low"], df["close"], period=14)
df["dc_up20"], _, _ = ta.donchian(df["high"], df["low"], period=20)
uptrend = df["ema20"] > df["ema50"]
breakout = df["close"] > df["dc_up20"].shift(1)
strong = df["adx"] > 20
entries = uptrend & breakout & strong
exits = df["ema20"] < df["ema50"]
w = slice(START, END)
print("Trading days :", len(df.loc[w]))
print("Breakout days :", int(breakout.loc[w].sum()))
print(" ...in an uptrend :", int((breakout & uptrend).loc[w].sum()))
print(" ...with ADX above 20 :", int(entries.loc[w].sum()))
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")
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", "exit_reason"]
print(trades[cols].to_string(float_format="%.2f"))
print("Closed-trade net P&L sum:", round(trades["net_pnl"].sum(), 2))
print("Final positions:")
print(result.final_positions[["symbol", "quantity_units", "average_price_rupees",
"mark_rupees", "unrealized_rupees"]].to_string())
def plain_crossover(bars):
ema20 = ta.ema(bars["close"], 20)
ema50 = ta.ema(bars["close"], 50)
up = pd.Series(ta.crossover(ema20, ema50), index=bars.index)
down = pd.Series(ta.crossunder(ema20, ema50), index=bars.index)
return up, down
base = bt.backtest(bt.from_signals(plain_crossover, SYMBOL, EXCHANGE, "D"),
client, start=START, end=END, capital=CAPITAL, source="db")
print("Plain EMA 20/50 crossover (Part 1 rules):")
print(base.summary())
print(f"Profit factor : {base.metrics['profit_factor']:.2f}")
print(f"Charges : Rs {base.metrics['total_costs']:,.2f}")
In Part 3 we will dig into the result object properly: the equity curve, drawdowns, win rate, and what that “too few trades to judge” line really means.
This article is for learning Python and backtesting only. It is not investment advice, and past results do not predict future returns.
Learn by watching: free videos every week
Market Profile, order flow, Python, AI and OpenAlgo tutorials on YouTube.

