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.

Six-Stock Trend Portfolio Backtest with the OpenAlgo SDK

5 min read

Portfolio backtest illustration: six kites of different colours tied to one string

So far this series tested one stock at a time. Real accounts hold several positions at once, so in this final part we run a six-stock portfolio backtest on one account with the OpenAlgo Python SDK, charge realistic Indian costs, and then compare the result with simply holding the same stocks.

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.
4. Add Realistic Costs and Position Sizing to Your OpenAlgo Backtest.
5. Six-Stock Trend Portfolio Backtest with the OpenAlgo SDK (this article).

The rules, stated before the run

We fixed every choice below before running anything, and we ran it once. Nothing was tuned afterwards.

  • Stocks: Reliance, HDFC Bank, TCS, L&T, ITC and Sun Pharma, six large caps from different sectors.
  • Entry: buy when the close is above the highest high of the previous 55 days (a Donchian breakout).
  • Exit: sell when the close falls below the lowest low of the previous 20 days.
  • Long only, CNC (delivery), daily bars, from 1 January 2021 to 23 November 2026.
  • Money: Rs 1,00,000 for each stock, Rs 6,00,000 for the account.
  • Costs: the realistic model from Part 4. Delivery brokerage of 0.03 percent capped at Rs 20 per order, the dated statutory charges, a DP fee of Rs 13 plus GST per sell, and 5 bps of slippage per fill.
  • Data: daily bars from your own OpenAlgo server (source="db").

One thing to know first. A portfolio backtest that runs a list of strategies on one account needs openalgo 2.4.0 or later, so run pip install -U openalgo. The earlier parts of this series ran on openalgo 2.3.0, and this part ran on 2.4.1.

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

How to build the portfolio backtest

bt.backtest accepts a list of strategies. The engine then keeps one account, shares the cash between them and gives back a portfolio result. We reuse the from_signals style of the earlier parts, with one small class per stock. Each class needs its own name, so we set it from the symbol.

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

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

SYMBOLS = ["RELIANCE", "HDFCBANK", "TCS", "LT", "ITC", "SUNPHARMA"]

def breakout(bars):
    up55, _, _ = ta.donchian(bars["high"], bars["low"], period=55)
    _, _, lo20 = ta.donchian(bars["high"], bars["low"], period=20)
    entries = bars["close"] > up55.shift(1)
    exits = bars["close"] < lo20.shift(1)
    return entries, exits

def make(symbol):
    cls = bt.from_signals(breakout, symbol, "NSE", "D", product="CNC")
    cls.__name__ = symbol.title() + "Trend"
    return cls

The shift(1) matters. It compares today’s close with the channel as it stood yesterday, so a bar cannot break a level that it helped to create.

Now the realistic costs from Part 4, and one call for the whole account.

REALISTIC = costs.CostModel(costs.custom(
    delivery=("percent", 0.03, 20), intraday=("percent", 0.03, 20),
    futures=("percent", 0.03, 20), options=20, dp_fee=13, name="discount_capped"))

pf = bt.backtest([make(s) for s in SYMBOLS], client,
                 start="2021-01-01", end="2026-11-23", capital=100_000,
                 source="db", costs=REALISTIC, slippage=bt.slippage.bps(5),
                 benchmark="NIFTY")
print(pf.summary())

The capital is per strategy, so the account starts with Rs 6,00,000. Run the script after you set OPENALGO_API_KEY in your environment. Never paste the key into code you share.

The portfolio backtest result

Net profit   : Rs 25,016.27
Return       : 4.17%
Max drawdown : -14.87%
Trades       : 67 (40% won), 4 still open
Overfitting  : each strategy's own trades below; none of the account's trades together
  RelianceTrend  : too few trades to judge (10 closed, 30 needed)
  HdfcbankTrend  : too few trades to judge (14 closed, 30 needed)
  TcsTrend       : too few trades to judge (11 closed, 30 needed)
  LtTrend        : too few trades to judge (12 closed, 30 needed)
  ItcTrend       : too few trades to judge (9 closed, 30 needed)
  SunpharmaTrend : too few trades to judge (11 closed, 30 needed)
Benchmark    : 81.43% return (NIFTY)

The account finished positive after costs, with a net profit of Rs 25,016.27 on Rs 6,00,000, a return of 4.17 percent. Charges came to Rs 19,925.68 and slippage to Rs 7,362.90, so costs were a real drag on a strategy that traded 67 times. Only 40 percent of trades won, which is normal for breakout systems: many small losses, a few large gains.

The window is about six years and the market mostly rose, so a choppy stretch could look different. The engine also flags 9 to 14 closed trades per stock as too few to judge, against a 30-trade rule of thumb.

Where the profit came from

for name in pf.strategies:
    m = pf.strategy(name).metrics
    print(f"{name:<18} return {m['total_return']:.2%}  maxDD {m['max_drawdown']:.2%}  trades {m['trades']}")
print(pf.contribution[["net_pnl_rupees", "share_pct"]].round(2))
Net profit by stock for the six-stock trend portfolio backtest, in rupees

Three stocks made money and three lost it:

StockNet P&L (Rs)ReturnTrades
Sun Pharma44,965.0344.97%11
ITC35,006.5235.01%9
L&T15,244.6415.24%12
Reliance-8,947.91-8.95%10
TCS-21,955.14-21.96%11
HDFC Bank-39,296.87-39.30%14

The three winners earned Rs 95,216.19 and the three losers gave back Rs 70,199.92. HDFC Bank alone cost more than Reliance and TCS together. The account only ended ahead because the winners were larger than the losers.

The daily returns of the six strategies were only loosely related, with correlations mostly between 0.0 and 0.25. That is why the account’s drawdown of 14.87 percent was smaller than the drawdown of any single stock strategy. The shallowest of those was ITC at 17.62 percent.

The honest comparison: buy and hold

A backtest means little without a yardstick. We took the same six stocks, put equal money in each on the first day and held to the end, using closing prices only and no costs at all. That is a generous benchmark for holding, so the true gap is a little smaller than the table shows.

Account value of the trend portfolio backtest after costs against equal-weight buy and hold, 2021 to 2026
Net returnMax drawdown
Trend portfolio, after costs4.17%-14.87%
Equal-weight buy and hold90.13%-21.47%
NIFTY (benchmark)81.43%not compared

Buy and hold won, by a wide margin. L&T and Sun Pharma more than doubled over the period, up 217.30 percent and 211.11 percent. A breakout system that waits for 55-day highs and leaves on 20-day lows gave up most of that. The one advantage the trend portfolio kept is a shallower worst fall, 14.87 percent against 21.47 percent.

So the lesson is not that this portfolio beats the market. It does not. In this window, in a market that mostly rose, a rule-based exit protected the account a little and cost most of the upside.

The full portfolio backtest script

You can copy the complete script below, or download the zip. It needs a running OpenAlgo server, openalgo 2.4.0 or later, and daily bars already on that server. Set OPENALGO_API_KEY first, then run it. The figures in this article came from this exact script.

# Six-stock trend portfolio on one account, OpenAlgo SDK backtest engine.
# Needs openalgo 2.4.0 or later: pip install -U openalgo
# Rules fixed before the run: Donchian 55-day breakout in, 20-day low exit, long only, CNC.
# Set OPENALGO_API_KEY in your environment. Never paste the key into code you share.

import os
import pandas as pd
import openalgo.backtest as bt
from openalgo import api, ta
from openalgo.backtest import costs

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

SYMBOLS = ["RELIANCE", "HDFCBANK", "TCS", "LT", "ITC", "SUNPHARMA"]
START, END, CAPITAL = "2021-01-01", "2026-11-23", 100_000


def breakout(bars):
    up55, _, _ = ta.donchian(bars["high"], bars["low"], period=55)
    _, _, lo20 = ta.donchian(bars["high"], bars["low"], period=20)
    entries = bars["close"] > up55.shift(1)
    exits = bars["close"] < lo20.shift(1)
    return entries, exits


def make(symbol):
    cls = bt.from_signals(breakout, symbol, "NSE", "D", product="CNC")
    cls.__name__ = symbol.title().replace(" ", "") + "Trend"
    return cls


REALISTIC = costs.CostModel(costs.custom(
    delivery=("percent", 0.03, 20),
    intraday=("percent", 0.03, 20),
    futures=("percent", 0.03, 20),
    options=20,
    dp_fee=13,
    name="discount_capped",
))


if __name__ == "__main__":
    pf = bt.backtest(
        [make(s) for s in SYMBOLS],
        client,
        start=START,
        end=END,
        capital=CAPITAL,
        source="db",
        costs=REALISTIC,
        slippage=bt.slippage.bps(5),
        benchmark="NIFTY",
    )
    print(pf.summary())
    for name in pf.strategies:
        m = pf.strategy(name).metrics
        print(
            f"{name:<18} return {m['total_return']:.2%}  "
            f"maxDD {m['max_drawdown']:.2%}  trades {m['trades']}"
        )
    print(pf.contribution[["net_pnl_rupees", "share_pct"]].round(2))

    # Equal-weight buy and hold, price only, no costs.
    closes = {}
    for s in SYMBOLS:
        d = client.history(
            symbol=s,
            exchange="NSE",
            interval="D",
            start_date=START,
            end_date=END,
            source="db",
        )
        closes[s] = d["close"]
    px = pd.DataFrame(closes).dropna()
    bh = (px / px.iloc[0]).mean(axis=1) * CAPITAL * len(SYMBOLS)
    print(
        "Buy and hold final", round(float(bh.iloc[-1]), 2),
        "net", round(float(bh.iloc[-1] - CAPITAL * len(SYMBOLS)), 2),
        "ret", round(float(bh.iloc[-1] / (CAPITAL * len(SYMBOLS)) - 1), 4),
        "maxDD", round(float((bh / bh.cummax() - 1).min()), 4),
    )
    print({s: round(float(px[s].iloc[-1] / px[s].iloc[0] - 1), 4) for s in SYMBOLS})

What you learned in this series

You can now run a backtest from your own OpenAlgo server, build signals with OpenAlgo indicators, read drawdown and the equity curve, add Indian costs and position sizing, and test several stocks on one account. The most useful habit is the one in this article: state the rules first, run once, and compare with buy and hold before you believe the result.

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