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.

Nifty 100 Low Volatility Strategy Beats the Index: Python Backtest

19 min read

Nifty 100 low volatility strategy illustration of a calm boat on steady water between rough waves

This is a Python tutorial, not a trading recommendation: it backtests a Nifty 100 low volatility strategy on survivorship-bias-free data.

A Nifty 100 low volatility strategy that holds the 10 calmest index members, rebalanced every quarter, returned 15.2% a year from January 2022 to November 2025 against 11.3% for the NIFTY 100, after charges and slippage. Its worst fall in that stretch was 15.6%, against 17.5% for the index. In the sealed year from December 2025 to November 2026 it gained 8.4% while the index lost 1.0%.

The backtest runs on a survivorship-bias-free universe: on every rebalance date it ranks only the stocks that were actually in the Nifty 100 that day, including the ones that later left the index or stopped trading. This tutorial shows how that data is organised, how the Python code uses it with the OpenAlgo backtest engine, and the full tear sheet against the index. The complete script and the data files are at the end.

Build desktop apps with Claude Code
LIVE COURSE · DEC 2026

Build desktop apps with Claude Code

Plan, build, package and distribute desktop apps for Windows, macOS and Linux, with Claude Code as your development partner.

  • 5 live sessions, 10 hours, starts 7 December 2026
  • CRM, algo trading and NSE Bhavcopy projects
  • Installers for Windows, macOS and Linux
Join the course →by Marketcalls

Nifty 100 low volatility strategy results in three periods

The rules were judged in three separate stretches of time. The first was used to choose the settings. The second and third were run only after the rules were fixed.

PeriodStrategy CAGRNIFTY 100 CAGRStrategy max drawdownNIFTY 100 max drawdownStrategy SharpeNIFTY 100 SharpeTurnover a year
Tuning, Jan 2015 to Dec 202118.5%11.4%-23.9%-38.1%0.890.373.1x
Test, Jan 2022 to Nov 202515.2%11.3%-15.6%-17.5%0.780.423.5x
Sealed year, Dec 2025 to Nov 20268.4%-1.0%-11.5%-15.0%0.23-0.394.1x

Every figure is after standard Indian delivery charges and 0.1% slippage on each fill. Sharpe is measured against a 6% cash return, the same rate credited to idle cash in the portfolio. The sealed-year figure is its 12-month return.

The strategy beat the index in all three periods, and it did so with a shallower drawdown each time. Chaining the three periods together, ₹100 invested in January 2015 grew to about ₹618 by 27 November 2026, against about ₹319 for the NIFTY 100. These are backtest results on past data.

The low volatility strategy rules in plain words

The rules fit in five lines:

  • When: on the first trading session of January, April, July and October.
  • Who can be picked: only the stocks that were in the Nifty 100 on that session.
  • Ranking: each eligible stock is scored by how much its price swung from day to day over the last 126 trading sessions, about six months. The stock with the smallest daily swings ranks first. In other words, the calmest stocks come first.
  • Selection: walk down that list and buy the 10 calmest stocks in equal amounts, but take no more than 3 from any one sector. If a fourth stock from a full sector comes up, skip it and move to the next name.
  • Holding: keep the 10 stocks until the next quarterly rebalance, then repeat.

Orders are decided on the rebalance session’s closing prices and filled at the next session’s open. The portfolio keeps 2% in cash for charges and overnight price jumps, and idle cash is credited 6% a year, roughly what a liquid fund earns. The test starts with ₹1 crore.

The sector cap matters. Calm stocks tend to cluster in a few defensive groups such as consumer staples, pharma and IT. Without the cap, a single sector could fill half the portfolio.

How the rules were chosen

The rules were fixed in advance, chosen on the 2015 to 2021 tuning period from a small set of tested variations, and then checked once on each later period. The test period and the sealed year were never used to adjust a setting, so their results show how the fixed rules behaved on data they had not seen.

How the survivorship-bias-free data is managed

A backtest that ranks today’s Nifty 100 members across past years quietly picks the winners in advance. Stocks that shrank, merged or delisted are missing, and stocks that were too small to be in the index back then are treated as if they were. Our Nifty 100 momentum rerun without survivorship bias showed how much that can inflate a result. This strategy uses the same point-in-time universe.

Rebuilding membership from the reconstitution history

The Nifty 100 changes in two ways: at its scheduled semi-annual reviews, and through one-off replacements when a member merges, demerges or delists. The membership file was rebuilt by walking through every one of those changes from January 2015 to the latest review, noting which stock came in, which went out and the date each change took effect.

The membership file layout

The result is a small CSV, nifty100_membership.csv, with three columns:

symbolstartend
ABB2016-04-012019-09-27
ABB2023-03-31
HDFC2015-01-012023-07-13
TATAMTRDVR2016-04-012020-06-26
TATAMTRDVR2023-09-292024-08-30

Each row is one spell in the index. start is the first session the stock was a member. end is the first session it was no longer a member, so the spell runs up to the day before. A blank end means the stock is still in the index. A stock that left and later returned, such as ABB or Tata Motors DVR, simply has two rows. The file holds 230 spells across 187 symbols, with 100 open spells today, exactly one full index.

Keeping prices for stocks that left

Leaving the index does not remove a stock from the backtest. Every symbol in the membership file keeps its full price history, because a stock that left in 2019 still had to compete in the 2016 rankings. Ten former members have since merged or stopped trading, including HDFC, Mindtree, Cairn India, GlaxoSmithKline Consumer and Reliance Capital. Their daily prices are kept as separate CSV files in a past_members folder, one file per symbol with date, open, high, low, close and volume, and the script reads them like any other stock.

The prices also get the usual care before any ranking:

  • Bars from before a stock’s listing date are dropped.
  • Splits and bonuses are back-adjusted using the engine’s own split detection.
  • Piramal Enterprises is adjusted for its 2022 demerger.
  • HDFC and Tata Motors DVR, which stopped trading while in the index, are held at their last close and sold at that price on the next rebalance.

A third small file, nifty100_sectors.csv, gives each symbol one fixed sector label for the 3-per-sector cap. It covers 19 sectors.

How the Python code uses the point-in-time data

The script turns the three files into two tables before the backtest starts.

Who was in the index on each day

The Universe class builds a table with one row per trading session and one column per symbol. A cell is true only when that session falls inside one of the stock’s membership spells, the stock has a price that day, and it has prices for almost every session of the 126-day window. On a rebalance day, the code reads that day’s row and ranks only the symbols marked true. A stock that joined the index in March 2023 cannot be picked in January 2023, and a stock that left in June 2019 cannot be picked in July 2019.

Calmness scores without look-ahead

The calmness score is computed with openalgo ta: the daily percentage change of each stock’s close, then the spread of those changes over the last 126 sessions. The score on a rebalance day uses closes up to and including that day only, and the orders fill at the next morning’s open, so the backtest never trades on a price it could not have seen. The membership table works the same way: a change in the index counts only from the session it took effect.

Exits and delistings

A stock that drops out of the index stays in the portfolio until the next quarterly rebalance, where it is no longer eligible and is sold. That mirrors what a quarterly portfolio would actually do. A stock that merges or delists in the middle of a quarter is valued at its last traded close and sold at that price on the next rebalance, so it never vanishes from the portfolio with its value.

Orders inside the engine

Each period is one bt.backtest run with the engine’s standard cost model and bt.pct(0.1) slippage. On a rebalance day the strategy sends sales first and buys after them, sized to equal weights after the 2% buffer. If a buy is refused because part of the sale proceeds is still blocked for settlement, the code sends it again three sessions later.

Nifty 100 low volatility strategy tear sheet

The script ends by writing a tear sheet with the backtest engine’s own report module. It joins the three periods into one curve and saves each panel as an image. The panels below come straight from that page.

Summary statistics

Nifty 100 low volatility strategy summary statistics table with CAGR, Sharpe and drawdown for each of the three periods
Summary statistics for the strategy and the NIFTY 100 in the tuning, test and sealed-year periods.

The same figures as a plain table, strategy first and NIFTY 100 second:

MetricTuning 2015 to 2021Test 2022 to Nov 2025Sealed year
CAGR18.5% vs 11.4%15.2% vs 11.3%8.4% vs -1.0%
Volatility13.6% vs 17.2%11.4% vs 13.8%13.4% vs 14.8%
Sharpe0.89 vs 0.370.78 vs 0.420.23 vs -0.39
Sortino1.28 vs 0.501.14 vs 0.580.32 vs -0.54
Max drawdown-23.9% vs -38.1%-15.6% vs -17.5%-11.5% vs -15.0%
Calmar0.78 vs 0.300.97 vs 0.640.72 vs -0.07
Months up66.3% vs 59.5%60.9% vs 61.7%54.5% vs 41.7%

The strategy earned more than the index in every period while swinging less. Sortino is like Sharpe but counts only the bad days, and Calmar compares the yearly return with the worst fall. Both favour the strategy throughout. Win rate is the share of months that ended with a gain: about two months in three during the tuning years and three in five in the test. Turnover of about 3 to 4 times a year cost roughly 0.6% to 0.8% of the portfolio each year in charges and slippage.

Equity curve

Equity curve of the Nifty 100 low volatility strategy against the NIFTY 100 from 2015 to November 2026 on a log scale
Cumulative return on a log scale. Red marks the tuning years, purple the test period and green the sealed year.

The colour changes show where each period starts. The lead over the index opened in the 2020 crash, when the calmer stocks fell less and recovered sooner, and it widened again in 2023. During the sealed year, while the index went sideways, the strategy kept edging higher.

Underwater chart

Underwater chart showing how far the Nifty 100 low volatility strategy and the NIFTY 100 fell from their previous peaks
Drop from the previous peak for the strategy and the index, with each period in its own colour.

This chart shows how far each line sat below its last high. In March 2020 the index fell 38% from its peak, while the strategy’s deepest fall was about 24%. The strategy also climbed back to new highs faster after most selloffs, which is what makes a strategy easier to stay with.

Monthly returns heatmap

Monthly returns heatmap of the Nifty 100 low volatility strategy from January 2015 to November 2026
Monthly returns of the strategy, green for gains and red for losses. November 2026 runs to the 27th.

Each cell is one month. The returns are spread across the calendar rather than packed into a few lucky months. The two worst months, March 2020 at -7.8% and March 2026 at -9.1%, were both months when the NIFTY 100 fell harder, by 22.8% and 11.7%.

Yearly returns against the index

Bar chart of calendar-year returns for the Nifty 100 low volatility strategy against the NIFTY 100 from 2015 to 2026
Calendar-year returns, strategy in red and NIFTY 100 in blue. 2026 runs to 27 November.

The strategy was ahead in 10 of the 12 calendar years. It trailed in 2021, when a fast rally favoured riskier stocks, and in 2022 by 2.5 points. Its strongest years relative to the index were 2015, 2020 and 2023.

Rolling 12-month return and volatility

Rolling 12-month return and volatility of the Nifty 100 low volatility strategy against the NIFTY 100
Rolling 12-month return (top) and rolling 12-month volatility (bottom) for the strategy and the index.

The top chart shows the return over every 12-month window. The strategy’s worst 12 months were much milder than the index’s in 2020, and it lagged in the sharp recovery of 2021. The bottom chart shows the strategy’s volatility staying below the index’s almost all the time. That steady difference is the whole idea of the strategy, and it held in the test years and the sealed year too.

Year by year against the NIFTY 100

YearStrategyNIFTY 100Difference (points)
201515.1%-2.4%+17.5
20165.6%3.6%+1.9
201735.0%31.0%+4.0
20184.6%1.1%+3.5
201917.8%10.4%+7.4
202037.4%14.9%+22.6
202118.3%25.0%-6.7
20221.1%3.6%-2.5
202335.4%20.0%+15.4
202412.9%11.8%+1.1
202512.8%9.0%+3.9
2026 (to 27 Nov)7.7%-0.8%+8.6

2025 combines the end of the test period with the first month of the sealed year, and 2026 runs to 27 November.

Turnover and costs of the Nifty 100 low volatility strategy

A quarterly rebalance of 10 stocks replaces only a few names each time, so turnover stays modest: 3.1 times the portfolio a year in the tuning years, 3.5 times in the test and 4.1 times in the sealed year. Charges and slippage together took about 0.64%, 0.71% and 0.76% of the portfolio a year in those periods. The returns above are after all of it. For more on how the engine charges each trade, see our guide to adding realistic costs to an OpenAlgo backtest.

Run the Nifty 100 low volatility strategy backtest yourself

The script needs openalgo 2.4.1 or later, pandas and numpy, and an OpenAlgo server running locally with your API key. playwright with an installed Chrome is optional and only used to save the tear sheet panels as images.

Download the script and the survivorship-bias-free data files (zip)

The zip holds the script, the membership CSV, the sector CSV, the price files for the ten past members and a README. Unzip it, set OPENALGO_API_KEY and run the script from that folder. The first run downloads and caches the daily bars, which takes a few minutes. Later runs finish in seconds.

export OPENALGO_API_KEY="your_key_here"
python nifty100_low_volatility.py

It prints each period’s figures and writes output/tearsheet.html, output/results.json, output/chained_curves.csv and the six panel images. The figures it printed for this article:

Tuning 2015-01-01 to 2021-12-31
  Low volatility 10: CAGR 18.5%  max drawdown -23.9%  Sharpe 0.89  turnover 3.1x
  NIFTY 100: CAGR 11.4%  max drawdown -38.1%  Sharpe 0.37

Test 2022-01-01 to 2025-11-28
  Low volatility 10: CAGR 15.2%  max drawdown -15.6%  Sharpe 0.78  turnover 3.5x
  NIFTY 100: CAGR 11.3%  max drawdown -17.5%  Sharpe 0.42

Sealed year 2025-12-01 to 2026-11-27
  Low volatility 10: CAGR 8.4%  max drawdown -11.5%  Sharpe 0.23  turnover 4.1x
  NIFTY 100: CAGR -1.0%  max drawdown -15.0%  Sharpe -0.39

What each part of the script does

  • Settings: the periods, the 126-session window, 10 stocks, the 3-per-sector cap, the quarterly months, ₹1 crore of capital, the cash buffer, slippage and the cash yield.
  • Data: load_all downloads and caches bars and reads past members from the folder; fix_corporate_events and adjust_splits clean them.
  • Universe: Universe builds the membership table and the calmness scores; picks applies the ranking and the sector cap for one day.
  • Strategy: schedule lists the rebalance days and their picks; make_strategy places the orders inside the engine.
  • Figures: curve_with_yield, stats and turnover_and_costs compute every figure in the tables.
  • Tear sheet: build_tearsheet uses the engine’s report module with a custom layout of six sections, and save_panels saves them as images.

Complete Python script for the low volatility strategy

"""
Nifty 100 Low Volatility Strategy on a Point-in-Time Universe (OpenAlgo backtest engine)
---------------------------------------------------------------------------------------
A Python tutorial, not a trading recommendation.

Rules (fixed before the test periods were run):
  * Rebalance on the first trading session of January, April, July and October.
  * Universe: only the stocks that were in the Nifty 100 on that session
    (point-in-time membership, including stocks that later left or delisted).
  * Rank them by how calm their daily price moves were over the last 126
    sessions (about six months): the calmest come first.
  * Walk down that list and buy the 10 calmest, equal weight, taking at most
    3 stocks from any one sector. Hold until the next rebalance.
  * Orders are decided on the rebalance session's close and fill at the next
    open, with standard Indian delivery charges and 0.1 percent slippage.
    A 2 percent cash buffer is kept; idle cash earns 6 percent a year.

Three periods are reported separately, plus a tear sheet of the chained curve:
  tuning 2015-01-01 to 2021-12-31, test 2022-01-01 to 2025-11-28,
  sealed year 2025-12-01 to 2026-11-27.

Requires: openalgo 2.4.1 or later, pandas, numpy
          (playwright is optional, only for saving PNG panels of the tear sheet)
Files next to this script:
  nifty100_membership.csv      symbol,start,end  one row per spell in the index;
                               start = first session in, end = first session out
                               (blank = still a member)
  nifty100_sectors.csv         symbol,sector     one fixed sector per stock
  PAST_MEMBERS_DIR/SYMBOL.csv  daily bars (date,open,high,low,close,volume) for
                               past members that merged or delisted
Run:
  export OPENALGO_API_KEY="your_key_here"
  python nifty100_low_volatility.py
"""
import os
import time
import json
import pickle
import warnings

import numpy as np
import pandas as pd

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

HOST = "http://127.0.0.1:5000"
API_KEY = os.getenv("OPENALGO_API_KEY", "your_openalgo_api_key")

HISTORY_START = "2014-01-01"     # warm-up for the 126-session window
LAST_DAY = "2026-11-27"
PERIODS = {
    "Tuning": ("2015-01-01", "2021-12-31"),
    "Test": ("2022-01-01", "2025-11-28"),
    "Sealed year": ("2025-12-01", "2026-11-27"),
}

WINDOW = 126           # sessions in the calmness window (about 6 months)
TOP_N = 10             # stocks held
SECTOR_CAP = 3         # at most this many from one sector
REBALANCE_MONTHS = (1, 4, 7, 10)
CAPITAL = 10_000_000   # Rs 1 crore
CASH_BUFFER = 2.0      # percent kept in cash for charges and opening price jumps
SLIPPAGE_PCT = 0.1     # percent per fill
LIQUID_YIELD = 0.06    # yearly yield credited on idle cash
RISK_FREE = 0.06       # for Sharpe and Sortino

MEMBERSHIP_CSV = "nifty100_membership.csv"
SECTORS_CSV = "nifty100_sectors.csv"
PAST_MEMBERS_DIR = os.getenv("PAST_MEMBERS_DIR", "past_members")
CACHE_FILE = os.getenv("PRICE_CACHE", "price_cache.pkl")
OUT_DIR = os.getenv("OUT_DIR", "output")

# Symbols that trade under a new name today
NEW_SYMBOL = {"ICICIPRULI": "ICICILIFE", "L&TFH": "LTF"}
# Listing dates: bars before these are dropped
LISTED_ON = {"MAZDOCK": "2020-10-12", "SBICARD": "2020-03-16"}
# Demerger: older prices are scaled by the ex-date open over the previous close
DEMERGERS = {"PEL": "2022-08-30"}
# Merged or converted while in the index: the position is valued at the last
# traded close and sold at that price on the next rebalance
LAST_CLOSE_UNTIL = {"HDFC": "2023-08-04", "TATAMTRDVR": "2024-09-06"}
# Older bars on a different price basis: multiply them back
RESCALE_BEFORE = {"CGPOWER": ("2015-01-01", 2.93)}


# ---------------------------------------------------------------- data ----
def tidy(df):
    out = df[["open", "high", "low", "close", "volume"]].copy()
    out.index = pd.to_datetime(out.index)
    if getattr(out.index, "tz", None) is not None:
        out.index = out.index.tz_localize(None)
    out.index = out.index.normalize()
    out = out.apply(pd.to_numeric, errors="coerce").astype(float)
    out = out[(out[["open", "high", "low", "close"]] > 0).all(axis=1)]
    return out[~out.index.duplicated(keep="last")].sort_index()


def history(client, symbol, exchange):
    """Daily bars through the OpenAlgo history call, or None for a symbol that no longer trades."""
    for _ in range(3):
        try:
            df = client.history(symbol=symbol, exchange=exchange, interval="D",
                                start_date=HISTORY_START, end_date=LAST_DAY, source="api")
        except Exception:
            df = None
        if isinstance(df, pd.DataFrame) and not df.empty:
            return tidy(df)
        time.sleep(1)
    return None


def read_past_member(symbol):
    path = os.path.join(PAST_MEMBERS_DIR, f"{symbol}.csv")
    if not os.path.exists(path):
        return None
    return tidy(pd.read_csv(path, index_col="date", parse_dates=True))


def load_all(symbols):
    raw = pickle.load(open(CACHE_FILE, "rb")) if os.path.exists(CACHE_FILE) else {}
    client = api(api_key=API_KEY, host=HOST)
    changed = False
    for i, sym in enumerate(symbols, 1):
        if sym in raw:
            continue
        raw[sym] = history(client, NEW_SYMBOL.get(sym, sym), "NSE")
        changed = True
        print(f"[{i}/{len(symbols)}] {sym}: {'ok' if raw[sym] is not None else 'past member file'}")
    for idx in ("NIFTY", "NIFTY100"):
        if raw.get(idx) is None:
            raw[idx] = history(client, idx, "NSE_INDEX")
            changed = True
    if changed:
        pickle.dump(raw, open(CACHE_FILE, "wb"))
    data = {}
    for sym in list(symbols) + ["NIFTY", "NIFTY100"]:
        f = raw.get(sym)
        if f is None:
            f = read_past_member(sym)
        if f is not None and len(f):
            data[sym] = f
    return data


def fix_corporate_events(data, sessions):
    for sym, (day, k) in RESCALE_BEFORE.items():
        if sym in data:
            f = data[sym].copy()
            older = f.index < day
            f.loc[older, ["open", "high", "low", "close"]] *= k
            f.loc[older, "volume"] /= k
            data[sym] = f
    for sym, day in LISTED_ON.items():
        if sym in data:
            data[sym] = data[sym][data[sym].index >= day]
    for sym, day in DEMERGERS.items():
        if sym in data:
            f = data[sym]
            ex = pd.Timestamp(day)
            k = f.loc[ex, "open"] / f.loc[f.index < ex, "close"].iloc[-1]
            f.loc[f.index < ex, ["open", "high", "low", "close"]] *= k
            data[sym] = f
    for sym, until in LAST_CLOSE_UNTIL.items():
        if sym in data:
            f = data[sym]
            last = f.iloc[-1]
            days = sessions[(sessions > f.index[-1]) & (sessions <= until)]
            pad = pd.DataFrame({"open": last.close, "high": last.close, "low": last.close,
                                "close": last.close, "volume": last.volume}, index=days)
            data[sym] = pd.concat([f, pad])
    return data


def adjust_splits(data):
    """Find unadjusted bonuses or splits with the engine's own data check and
    back-adjust older prices."""
    from openalgo.backtest.data import load_bars
    out = {}
    for sym, frame in data.items():
        f = frame.copy()
        if sym in ("NIFTY", "NIFTY100"):
            out[sym] = f
            continue
        for _ in range(10):
            r = load_bars(sym, "NSE", "D", start=HISTORY_START, end=LAST_DAY,
                          data=f, cache=False, strict=False, tz="Asia/Kolkata")
            jumps = [g for g in (r.meta.quality.price_gaps or []) if g.status == "suspected" and g.factor]
            if not jumps:
                break
            g = sorted(jumps, key=lambda x: x.ex_date, reverse=True)[0]
            older = f.index < pd.Timestamp(g.ex_date)
            f.loc[older, ["open", "high", "low", "close"]] /= float(g.factor)
            f.loc[older, "volume"] *= float(g.factor)
        out[sym] = f
    return out


def prepare():
    members = pd.read_csv(MEMBERSHIP_CSV, keep_default_na=False)
    data = load_all(sorted(members.symbol.unique()))
    data = fix_corporate_events(data, data["NIFTY"].index)
    return adjust_splits(data), members


# ------------------------------------------------------ the universe ----
class Universe:
    """Who was in the index on each session, whose prices cover the window,
    and each stock's calmness score from openalgo ta."""

    def __init__(self, data, members, sectors):
        self.data = data
        s = data["NIFTY"].index
        self.sessions = s[s >= HISTORY_START]
        self.symbols = sorted(x for x in members.symbol.unique() if x in data)
        self.sector = sectors
        S = self.sessions
        have = pd.DataFrame({x: S.isin(data[x].index) for x in self.symbols}, index=S)
        inside = pd.DataFrame(False, index=S, columns=self.symbols)
        for row in members.itertuples():
            if row.symbol in inside.columns:
                end = pd.Timestamp(row.end) if row.end else pd.Timestamp("2100-01-01")
                inside.loc[(S >= row.start) & (S < end), row.symbol] = True
        # a member that day, with prices on (almost) every session of the window
        full = have.astype(int).rolling(WINDOW + 1).sum() >= WINDOW - 2
        self.allowed = full & inside & have
        # calmness: the spread of daily percent changes over the window (lower = calmer)
        calm = {}
        for x in self.symbols:
            c = data[x]["close"]
            c = c[c.index >= "2013-01-01"]
            daily_change = ta.roc(c.values, 1)
            calm[x] = pd.Series(np.asarray(ta.stdev(daily_change, WINDOW), float), index=c.index).reindex(S)
        self.calm = pd.DataFrame(calm)
        self.index_close = data["NIFTY100"]["close"].reindex(S).ffill()

    def picks(self, day):
        ok = self.allowed.loc[day]
        score = self.calm.loc[day, ok[ok].index].replace([np.inf, -np.inf], np.nan).dropna()
        ordered = list(score.sort_values(ascending=True, kind="mergesort").index)
        chosen, used = [], {}
        for x in ordered:
            sec = self.sector.get(x, "Unknown")
            if used.get(sec, 0) >= SECTOR_CAP:
                continue
            chosen.append(x)
            used[sec] = used.get(sec, 0) + 1
            if len(chosen) == TOP_N:
                return chosen
        return None


def schedule(uni, start, end):
    """{rebalance session: picks}. The first session of a run and the first session
    of each rebalance month. Scores use closes up to and including that session."""
    s = uni.sessions[(uni.sessions >= start) & (uni.sessions <= end)]
    firsts = pd.Series(s, index=s).groupby([s.year, s.month]).first()
    out = {}
    for i, day in enumerate(firsts):
        if i == 0 or day.month in REBALANCE_MONTHS:
            p = uni.picks(day)
            if p is not None:
                out[day] = p
    return out


# ------------------------------------------------------- the strategy ----
def rebalance_to(strategy, weights):
    """The engine's rebalance (sales first, then buys), sized only over the stocks in
    the target or already held. self.rebalance() also sizes every other symbol of the
    strategy, which fails for a stock that has not listed yet on that date."""
    from openalgo.backtest import _rebalance as R
    ctx = strategy._ctx
    names = tuple(n for n in ctx.names if n in weights or R._held_value(ctx, n) != 0)
    invested = 1.0 - R.cash_buffer_fraction(CASH_BUFFER)
    pv = ctx.account()[0]
    targets = {n: float(weights.get(n, 0.0)) / 100.0 * pv * invested for n in names}
    changes = {n: targets[n] - R._held_value(ctx, n) for n in names}
    for n in R.trade_order(changes):
        ctx.submit_rebalance({"instrument": ctx.instrument_index(n), "product": ctx.product,
                              "kind": "rupees", "amount": targets[n], "leverage": None})


def make_strategy(symbols, sched):
    plan = {pd.Timestamp(k).normalize(): v for k, v in sched.items()}

    class LowVolatility10(bt.Strategy):
        pass
    LowVolatility10.symbols = tuple(symbols)
    LowVolatility10.exchange = "NSE"
    LowVolatility10.interval = "D"
    LowVolatility10.product = "CNC"

    def on_bar(self, bars):
        from openalgo.backtest import _rebalance as R
        t = pd.Timestamp(self.now)
        if t.tzinfo is not None:
            t = t.tz_convert("Asia/Kolkata").tz_localize(None)
        t = t.normalize()
        nbar = getattr(self, "_nbar", 0)
        self._nbar = nbar + 1
        retry, wait = getattr(self, "_retry", None), getattr(self, "_retry_wait", 0)
        if retry and wait > 1:
            self._retry_wait = wait - 1
            retry = None
        else:
            self._retry = None
        if retry:
            # A buy refused for cash (part of a sale's proceeds stays blocked until
            # settlement, and an open can jump past the buffer) is sent again three
            # sessions later, for picks still under half their target.
            ctx = self._ctx
            pv = ctx.account()[0]
            want = {n: w / 100.0 * pv for n, w in retry.items()}
            short = {n: v for n, v in want.items() if n in bars and R._held_value(ctx, n) < 0.5 * v}
            if short:
                free = max(self.cash - CASH_BUFFER / 100.0 * pv, 0)
                k = min(1.0, free / sum(short.values()))
                for n, v in short.items():
                    if k * v > 0:
                        ctx.submit_rebalance({"instrument": ctx.instrument_index(n), "product": ctx.product,
                                              "kind": "rupees", "amount": k * v, "leverage": None})
        if t in plan:
            self._pending = plan[t]
        if nbar == 0 or getattr(self, "_pending", None) is None:
            return  # no sizing price on a run's first bar: act on the second
        picks, self._pending = self._pending, None
        w = (100.0 - CASH_BUFFER) / len(picks)
        rebalance_to(self, {s: w for s in picks})
        self._retry, self._retry_wait = {s: w for s in picks}, 3

    LowVolatility10.on_bar = on_bar
    return LowVolatility10


def run_period(uni, start, end):
    sched = schedule(uni, start, end)
    syms = sorted({s for v in sched.values() for s in v})
    with warnings.catch_warnings():
        warnings.simplefilter("ignore")
        res = bt.backtest(make_strategy(syms, sched), start=start, end=end, capital=CAPITAL,
                          data={s: uni.data[s] for s in syms},
                          costs=bt.costs.CostModel(backfill=True),
                          slippage=bt.pct(SLIPPAGE_PCT))
    return res, sched


# ------------------------------------------------------------ figures ----
def curve_with_yield(res):
    """Equity with the liquid yield credited on idle cash."""
    eq = res.equity.copy()
    idx = eq.index.tz_convert("Asia/Kolkata").tz_localize(None) if eq.index.tz is not None else eq.index
    eq.index = idx.normalize()
    e = eq["equity_rupees"].astype(float)
    cash = (e - eq["exposure_rupees"].astype(float)).clip(lower=0)
    r = e.pct_change().fillna(0.0)
    days = pd.Series(e.index, index=e.index).diff().dt.days.fillna(0)
    carry = (cash.shift(1) / e.shift(1)).fillna(0) * ((1 + LIQUID_YIELD) ** (days / 365.0) - 1)
    return (1 + r + carry).cumprod() * e.iloc[0]


def index_curve(uni, start, end):
    s = uni.index_close
    return pd.concat([s[s.index < start].iloc[-1:], s[(s.index >= start) & (s.index <= end)]])


def stats(curve, start):
    curve = curve.dropna()
    r = curve.pct_change().dropna()
    yrs = (curve.index[-1] - curve.index[0]).days / 365.25
    ppy = len(r) / yrs
    rf = (1 + RISK_FREE) ** (1 / ppy) - 1
    ex = r - rf
    downside = np.sqrt((np.minimum(ex, 0) ** 2).mean())
    cagr = (curve.iloc[-1] / curve.iloc[0]) ** (1 / yrs) - 1
    dd = (curve / curve.cummax() - 1).min()
    monthly = curve.resample("ME").last().pct_change().dropna()
    yearly = curve.groupby(curve.index.year).last()
    base = pd.concat([pd.Series([curve.iloc[0]], index=[curve.index[0].year - 1]), yearly])
    yr = base.pct_change().dropna()
    yr = yr[yr.index >= pd.Timestamp(start).year]
    return {
        "CAGR": cagr,
        "Volatility": r.std() * np.sqrt(ppy),
        "Sharpe": ex.mean() / ex.std() * np.sqrt(ppy),
        "Sortino": ex.mean() / downside * np.sqrt(ppy),
        "Max drawdown": dd,
        "Calmar": cagr / abs(dd),
        "Win rate (months up)": float((monthly > 0).mean()),
        "yearly": {int(k): float(v) for k, v in yr.items()},
    }


def turnover_and_costs(res, yrs):
    m = res.metrics
    eq = res.equity["equity_rupees"].astype(float)
    slip = SLIPPAGE_PCT / 100 * m["turnover"]
    return {"Turnover (x a year)": m["turnover"] / eq.mean() / yrs,
            "Cost drag (a year)": (m["total_costs"] + slip) / eq.mean() / yrs}


def chain(parts):
    out = None
    for p in parts:
        p = p / p.iloc[0] * (100 if out is None else out.iloc[-1])
        out = p if out is None else pd.concat([out, p[p.index > out.index[-1]]])
    return out


# --------------------------------------------------------- tear sheet ----
STRAT, BENCH = "Low volatility 10", "NIFTY 100"
B1, B2 = pd.Timestamp("2022-01-01"), pd.Timestamp("2025-12-01")


def by_period(s):
    """The strategy as three overlapping columns that start at the tuning, test and
    sealed-year boundaries. The tear sheet holds each line at its last value, so every
    later column is drawn over the earlier one and each period shows in its own colour."""
    return pd.DataFrame({
        "Strategy, tuning 2015-21": s,
        "Strategy, test 2022-Nov 2025": s.where(s.index >= B1 - pd.Timedelta(days=4)),
        "Strategy, sealed Dec 2025-Nov 2026": s.where(s.index >= B2 - pd.Timedelta(days=4)),
    })


class TearSheetSubject:
    """What report.tearsheet reads: a Performance plus a name and the benchmark's name."""

    def __init__(self, performance, assumptions):
        self.performance = performance
        self.name = "Nifty 100 low volatility 10 vs NIFTY 100"
        self.benchmark_name = BENCH
        self.assumptions = assumptions


def build_tearsheet(strat, bench, table, path):
    tz = "Asia/Kolkata"
    eq = strat.copy()
    eq.index = (eq.index + pd.Timedelta(hours=15, minutes=30)).tz_localize(tz)
    bm = bench.copy()
    bm.index = (bm.index + pd.Timedelta(hours=15, minutes=30)).tz_localize(tz)
    with warnings.catch_warnings():
        warnings.simplefilter("ignore")
        perf = metrics.analyse(eq * CAPITAL / 100, exchanges="NSE", benchmark=bm, risk_free_rate=RISK_FREE)

    growth = pd.concat([(bench / bench.iloc[0] - 1).rename(BENCH),
                        by_period(strat / strat.iloc[0] - 1)], axis=1, sort=True)
    under = pd.concat([(bench / bench.cummax() - 1).rename(BENCH),
                       by_period(strat / strat.cummax() - 1)], axis=1, sort=True)
    rs, rb = strat.pct_change(), bench.pct_change()
    roll_ret = pd.DataFrame({BENCH: bench.pct_change(252), STRAT: strat.pct_change(252)}).dropna()
    roll_vol = pd.DataFrame({BENCH: rb.rolling(252).std() * np.sqrt(252),
                             STRAT: rs.rolling(252).std() * np.sqrt(252)}).dropna()
    monthly = strat.resample("ME").last().pct_change()
    monthly.iloc[0] = strat.resample("ME").last().iloc[0] / strat.iloc[0] - 1
    heat = monthly.groupby([monthly.index.year, monthly.index.month]).first().unstack()
    heat.columns = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"][:heat.shape[1]]
    heat.index = heat.index.astype(str)
    ys = strat.groupby(strat.index.year).last()
    yb = bench.groupby(bench.index.year).last()
    yearly = pd.DataFrame({
        "_s": pd.concat([pd.Series([strat.iloc[0]], index=[ys.index[0] - 1]), ys]).pct_change().dropna(),
        BENCH: pd.concat([pd.Series([bench.iloc[0]], index=[yb.index[0] - 1]), yb]).pct_change().dropna(),
    })[[BENCH, "_s"]].rename(columns={"_s": STRAT})
    yearly = yearly[yearly.index >= 2015]
    yearly.index = [f"{y}" for y in yearly.index]

    sub = "Tuning Jan 2015 to Dec 2021, test Jan 2022 to Nov 2025, sealed year Dec 2025 to Nov 2026"
    sections = (
        report.section("Summary statistics", report.table(table, title="Summary statistics by period", sortable=False),
                       subtitle="After charges and slippage; idle cash earns 6 percent a year"),
        report.section("Equity curve", report.line(growth, title="Cumulative return (log scale)", log_scale=True,
                                             percent=True),
                       subtitle=sub),
        report.section("Underwater", report.line(under, title="Drop from the previous peak", percent=True), subtitle=sub),
        report.section("Monthly returns", report.heatmap(heat, title="Monthly returns of the strategy", percent=True)),
        report.section("Yearly returns", report.bar(yearly, title="Calendar-year returns", percent=True),
                       subtitle="2025 joins the test and the sealed year; 2026 runs to 27 November"),
        report.section("Rolling 12 months", report.line(roll_ret, title="Rolling 12-month return", percent=True,
                                              zero_line=True),
                       report.line(roll_vol, title="Rolling 12-month volatility", percent=True)),
    )
    builtin = tuple(k for k in report.PARTS)
    theme = report.Theme(series=["#1565C0", "#E53935", "#8E24AA", "#00897B", "#FB8C00", "#43A047"])
    layout = report.Layout(hide=builtin, sections=sections, theme=theme)
    subject = TearSheetSubject(perf, {"costs": "standard Indian delivery charges, 0.1 percent slippage",
                                      "cash": "idle cash earns 6 percent a year"})
    return report.tearsheet(subject, path, layout=layout)


def save_panels(html_path, out_dir):
    """Optional: one PNG per tear sheet section (needs playwright and Chrome)."""
    try:
        from playwright.sync_api import sync_playwright
    except ImportError:
        print("playwright not installed: open the HTML tear sheet in a browser instead")
        return
    wide = {1: 1000, 4: 1000}   # the table and the heatmap need more room than charts
    with sync_playwright() as p:
        b = p.chromium.launch(channel="chrome")
        for i in range(1, 7):
            width = wide.get(i, 660)
            page = b.new_page(viewport={"width": width, "height": 1200},
                              device_scale_factor=1600 / width, color_scheme="light")
            page.goto("file://" + os.path.abspath(html_path))
            page.query_selector_all("section")[i - 1].screenshot(
                path=os.path.join(out_dir, f"panel_{i}.png"))
            page.close()
        b.close()


# --------------------------------------------------------------- main ----
if __name__ == "__main__":
    os.makedirs(OUT_DIR, exist_ok=True)
    data, members = prepare()
    sectors = dict(pd.read_csv(SECTORS_CSV).values[:, :2])
    uni = Universe(data, members, sectors)

    rows, curves, idx_curves, yearly = {}, [], [], {}
    for label, (start, end) in PERIODS.items():
        res, sched = run_period(uni, start, end)
        c = curve_with_yield(res)
        ic = index_curve(uni, start, end)
        s, i = stats(c, start), stats(ic, start)
        yrs = (c.index[-1] - c.index[0]).days / 365.25
        s.update(turnover_and_costs(res, yrs))
        i.update({"Turnover (x a year)": 0.0, "Cost drag (a year)": 0.0})
        rows[(label, STRAT)], rows[(label, BENCH)] = s, i
        curves.append(c)
        idx_curves.append(ic)
        last = max(sched)
        print(f"\n{label} {start} to {end}: last rebalance {last.date()} -> {', '.join(sched[last])}")
        print(f"  {STRAT}: CAGR {s['CAGR']:.1%}  max drawdown {s['Max drawdown']:.1%}  "
              f"Sharpe {s['Sharpe']:.2f}  turnover {s['Turnover (x a year)']:.1f}x")
        print(f"  {BENCH}: CAGR {i['CAGR']:.1%}  max drawdown {i['Max drawdown']:.1%}  Sharpe {i['Sharpe']:.2f}")

    keys = ["CAGR", "Volatility", "Sharpe", "Sortino", "Max drawdown", "Calmar",
            "Win rate (months up)", "Turnover (x a year)"]
    pct = {"CAGR", "Volatility", "Max drawdown", "Win rate (months up)"}
    table = pd.DataFrame({f"{p}: {'Strategy' if n == STRAT else 'Index'}":
                          [f"{rows[(p, n)][k]:.1%}" if k in pct else f"{rows[(p, n)][k]:.2f}" for k in keys]
                          for (p, n) in rows}, index=keys)
    table.index.name = "Metric"
    table = table.reset_index()
    print("\n" + table.to_string(index=False))

    strat, bench = chain(curves), chain(idx_curves)
    pd.DataFrame({STRAT: strat, BENCH: bench}).to_csv(os.path.join(OUT_DIR, "chained_curves.csv"))
    json.dump({f"{p}|{n}": v for (p, n), v in rows.items()}, open(os.path.join(OUT_DIR, "results.json"), "w"),
              indent=1, default=float)
    html = build_tearsheet(strat, bench, table, os.path.join(OUT_DIR, "tearsheet.html"))
    print("\ntear sheet:", html)
    save_panels(html, OUT_DIR)

For a refresher on reading equity curves and drawdowns like the ones above, see how to read your backtest results.

The takeaway

The Nifty 100 low volatility strategy, buying the calmest index members each quarter with a simple sector cap, beat the NIFTY 100 in the years used to choose it, in the untouched test years and in a sealed final year, with smaller drawdowns throughout. The sealed year was a down year for the index, the kind of market where calmer stocks tend to hold up best. What makes the result worth studying is the data underneath it: a universe rebuilt as it stood on each date, with every former member still in the race. Download the files, run the script and check every number yourself.

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