This is a Python tutorial that teaches a backtesting technique, the point-in-time universe. It is not a trading strategy or a recommendation.
Survivorship bias did most of the work in our earlier Nifty 100 momentum strategy backtest. That test ranked today’s 100 stocks across 2015 to 2026 and showed a 21.5% CAGR. Rerun with the stocks that were actually in the index on each rebalance date, the same rules return 7.8% a year. That is below the NIFTY 100 index’s 10.2%. The maximum drawdown deepens from 35.8% to 45.4%.
The result side by side
All runs start with Rs 1 crore on 1 January 2015 and end on 27 November 2026, with the same charges and slippage.
| Metric | Original as published | Original on cleaned data | Point-in-time universe | NIFTY 100 index |
|---|---|---|---|---|
| CAGR | 21.6% | 21.5% | 7.8% | 10.2% |
| Total return | 926.5% | 917.3% | 145.4% | 219.2% |
| Max drawdown | -35.8% | -35.8% | -45.4% | -38.1% |
| Sharpe ratio | 1.14 | 1.13 | 0.52 | n/a |
| Turnover per year | 9.6x equity | 9.6x equity | 10.3x equity | n/a |
| Rs 1 crore became | Rs 10.27 crore | Rs 10.17 crore | Rs 2.45 crore | Rs 3.19 crore |
Cleaning the data barely moved the original: CAGR slipped by 0.1 point, and only 2015 changed. Almost the whole 13.7-point fall comes from fixing the stock list.
What survivorship bias means in this backtest
Today’s Nifty 100 list is a list of winners. A stock gets into the index by growing big, so any stock that is in it now has, by definition, done well at some point in the last decade. Rank only those names in 2015 and the backtest quietly knows the future.
The numbers show how big the leak is. In January 2015 only 60 of today’s 100 stocks were in the index. Over the whole period the overlap averaged about 70. Between 2015 and 2026, 187 different stocks passed through the Nifty 100, and 87 of them are not on today’s list. Some merged, some delisted, and many simply shrank and were dropped.
A fair test asks one question at every rebalance: which 100 stocks could a trader have seen in the index on that day? That list is the point-in-time universe.
Same rules as the original
Nothing about the strategy changed:
- Every stock in the universe is ranked by its rate of change over the last 63 sessions, which is simply how far the price has moved, in percent, over about three months.
- On the first trading session of each month, the 20 strongest stocks are bought in equal weight, with 2% kept in cash for charges.
- Stocks that drop out of the top 20 are sold. Orders fill at the next session’s open.
- Standard Indian delivery charges apply, plus 5 basis points of slippage on every fill.
- The backtest runs on the OpenAlgo Python SDK’s backtest engine.
The only change is the list of stocks that may be ranked on each date.
How the point-in-time universe is built
The membership file was rebuilt from the index’s semi-annual reconstitution announcements and the ad hoc replacements for mergers and delistings. It runs from January 2015 to the September 2026 review. Each row holds a symbol, the date it joined and the date it left. The rebuilt list was checked against twelve archived full constituent lists and matched every one.
A stock may be ranked on a rebalance day only if it is a member that day and has prices for the full ranking window. Stocks that later merged or delisted are read from a folder of daily price files, so they compete in the ranking exactly as they did at the time.
Cleaning the data first
Before comparing universes, the price data was cleaned so that both runs see the same prices:
- Mazagon Dock and SBI Card bars from before their listing dates were removed.
- A wrong price basis on CG Power’s pre-2015 bars was fixed. It had created a fake 190% jump on the first day of 2015.
- Piramal Enterprises was adjusted for its 2022 demerger, and splits and bonuses were back-adjusted.
- HDFC and Tata Motors DVR, which left the market while in the index, are held at their last close and sold on the next rebalance.
The CG Power fix is the one that touched the original: its 2015 return fell from 4.1% to 3.1%.
Where survivorship bias came from
The original made most of its money in stocks that were not in the Nifty 100 when it bought them. Of 1,128 trades, 311 were entered while the stock was outside the index. Those trades earned Rs 618 lakh of the Rs 832 lakh closed-trade profit, about three quarters.
The names that mattered most:
- BSE earned Rs 76.4 lakh and joined the index only in September 2026.
- Adani Power earned Rs 59.8 lakh and IRFC Rs 40.8 lakh; both joined in March 2024.
- Mazagon Dock (Rs 40.6 lakh) and Solar Industries (Rs 34.8 lakh) joined in September 2025.
- Hitachi Energy India earned Rs 38.6 lakh and joined in September 2026.
- Adani Green earned Rs 34.3 lakh and joined in September 2020.
These are mid-cap rallies that a Nifty 100 investor could not have held as index stocks at the time. The original effectively bought next decade’s index additions early.
The point-in-time run makes the reverse mistake impossible. It also holds the losers the original never saw. Its 340 trades in names that are no longer in the index lost Rs 22 lakh. United Spirits, Bandhan Bank, Indus Towers, IndusInd Bank and NMDC led the losses.
Drawdowns and turnover
The honest run suffered more and recovered more slowly. Its equity peaked in January 2018, bottomed on 23 March 2020, and did not regain the old high until January 2021. The original bottomed on the same day but was back at its peak by August 2020.
Turnover was slightly higher on the point-in-time universe, about 10.3 times average equity a year against 9.6, because index churn forces extra exits. Year by year, the point-in-time run lost money in 2018, 2019, 2022, 2025 and 2026 so far, while the original lost only in 2026.
For a refresher on reading these curves, see how to read backtest drawdowns and the equity curve.
How the script works
Settings and corporate events
The top of the script holds the lookback, the number of stocks, capital and cash buffer. Small dictionaries record the corporate events from the cleaning step: renamed symbols, listing dates, the demerger, the two last-close exits and the old price basis.
Loading prices
Daily bars come from your OpenAlgo server through the SDK’s history call and are cached in a pickle, so a second run takes seconds. A stock the server does not return is read from PAST_MEMBERS_DIR, a folder you set with an environment variable. Each file is named after the symbol and has date, open, high, low, close and volume columns. The engine’s own data check then finds unadjusted splits and bonuses, as in the original.
The universe table
eligibility builds a table of trading days by stocks, true when a stock may be ranked. For "today" it only asks for a full price window. For "pit" it also requires index membership on that date. This one table is the whole difference between the two backtests.
Strategy and run
The strategy computes the rate of change for every stock once. On the first session of each month it ranks the allowed stocks and calls rebalance with equal weights. The script runs both universes, prints a summary row for each and saves both equity curves with the NIFTY 100 on one chart. Costs and slippage use the engine’s standard charges model, the subject of our guide to adding realistic costs to an OpenAlgo backtest.
Complete Python script
It needs openalgo 2.4.0 or later, pandas, numpy and matplotlib, an OpenAlgo server running locally and nifty100_membership.csv in the same folder. Download the script and the membership CSV (zip).
"""
Nifty 100 Momentum, Rerun Without Survivorship Bias (OpenAlgo backtest engine)
-----------------------------------------------------------------------------
A Python tutorial on backtesting technique, not a trading strategy or advice.
Same rules as the original Nifty 100 momentum tutorial: rank stocks by their
63-session rate of change (ta.roc), hold the top 20 in equal weight after a
2 percent cash buffer, rebalance on the first session of every month, fill at
the next open, standard Indian charges plus 5 basis points of slippage.
Two universes are compared:
"today" : today's Nifty 100 list used for the whole history (the original)
"pit" : point-in-time membership, so each rebalance only ranks stocks that
were in the index on that date, including stocks that later left
Requires: openalgo 2.4.0 or later, pandas, numpy, matplotlib
Files next to this script:
nifty100_membership.csv symbol,start,end (end blank = still a member)
PAST_MEMBERS_DIR/SYMBOL.csv daily bars (date,open,high,low,close,volume)
for past members that OpenAlgo does not serve
Run:
export OPENALGO_API_KEY="your_key_here"
python nifty100_pit_momentum.py
"""
import os
import time
import pickle
import warnings
import numpy as np
import pandas as pd
import openalgo.backtest as bt
from openalgo import api, ta
HOST = "http://127.0.0.1:5000"
API_KEY = os.getenv("OPENALGO_API_KEY", "your_openalgo_api_key")
START = "2015-01-01"
END = "2026-11-27"
LOOKBACK = 63 # sessions in the ranking window (about 3 months)
TOP_N = 20
CAPITAL = 10_000_000 # Rs 1 crore
CASH_BUFFER = 2.0 # percent kept in cash for charges
MEMBERSHIP_CSV = "nifty100_membership.csv"
PAST_MEMBERS_DIR = os.getenv("PAST_MEMBERS_DIR", "past_members")
CACHE_FILE = "openalgo_bars.pkl"
# Symbols that OpenAlgo now serves under a new name
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 served on a different price basis: multiply them back
RESCALE_BEFORE = {"CGPOWER": ("2015-01-01", 2.93)}
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, source="api"):
"""Daily bars from your OpenAlgo server, or None if it does not serve the symbol."""
for _ in range(3):
try:
df = client.history(symbol=symbol, exchange=exchange, interval="D",
start_date="2014-01-01", end_date=END, source=source)
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):
if os.path.exists(CACHE_FILE):
raw = pickle.load(open(CACHE_FILE, "rb"))
else:
raw = {}
client = api(api_key=API_KEY, host=HOST)
changed = False
for i, sym in enumerate(symbols, 1):
if sym in raw:
continue
name = NEW_SYMBOL.get(sym, sym)
f = history(client, name, "NSE", "api")
raw[sym] = f
changed = True
print(f"[{i}/{len(symbols)}] {sym}: {'ok' if f is not None else 'not served'}")
for idx in ("NIFTY", "NIFTY100"):
if idx not in raw:
raw[idx] = history(client, idx, "NSE_INDEX")
changed = True
if changed:
pickle.dump(raw, open(CACHE_FILE, "wb"))
data = {}
for sym in list(raw) + [s for s in symbols if s not in raw]:
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)
prev = f.loc[f.index < ex, "close"].iloc[-1]
k = f.loc[ex, "open"] / prev
older = f.index < ex
f.loc[older, ["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, as in the original tutorial."""
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="2014-01-01", end=END,
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)
print(f" adjusted {sym} {g.ex_date}: factor {float(g.factor):g}")
out[sym] = f
return out
def eligibility(data, members, sessions, universe):
"""A table of rebalance days x symbols: True when the stock may be ranked.
It must be in the universe on that day and have prices for the ranking
window up to that day (allowing for special weekend sessions)."""
syms = sorted(members.symbol.unique()) if universe == "pit" else TODAY_LIST
syms = [s for s in syms if s in data]
have = pd.DataFrame({s: sessions.isin(data[s].index) for s in syms}, index=sessions)
full = have.astype(int).rolling(LOOKBACK + 1).sum() >= LOOKBACK - 2
if universe == "today":
return full, syms
inside = pd.DataFrame(False, index=sessions, columns=syms)
for row in members.itertuples():
if row.symbol not in inside.columns:
continue
end = pd.Timestamp(row.end) if isinstance(row.end, str) and row.end else pd.Timestamp("2100-01-01")
inside.loc[(sessions >= row.start) & (sessions < end), row.symbol] = True
return full & inside, syms
def make_strategy(symbols, allowed):
class Momentum(bt.Strategy):
pass
Momentum.symbols = tuple(symbols)
Momentum.exchange = "NSE"
Momentum.interval = "D"
Momentum.product = "CNC"
def init(self):
self.roc = {s: self.I(ta.roc, self.data[s].close, LOOKBACK) for s in self.symbols}
self.every("month", self.rebalance_now)
def rebalance_now(self):
today = pd.Timestamp(self.now)
if today.tzinfo is not None:
today = today.tz_convert("Asia/Kolkata").tz_localize(None)
today = today.normalize()
if today not in allowed.index:
return
ok = allowed.loc[today]
scores = {}
for s in self.symbols:
if not ok.get(s, False) or len(self.roc[s]) == 0:
continue
v = self.roc[s][-1]
if v == v:
scores[s] = float(v)
if len(scores) < TOP_N:
return
picks = sorted(scores, key=scores.get, reverse=True)[:TOP_N]
weight = (100.0 - CASH_BUFFER) / len(picks)
self.rebalance({s: weight for s in picks}, cash_buffer=CASH_BUFFER)
Momentum.init = init
Momentum.rebalance_now = rebalance_now
return Momentum
def run(data, members, universe):
sessions = data["NIFTY"].index
sessions = sessions[sessions >= "2014-01-01"]
allowed, syms = eligibility(data, members, sessions, universe)
strat = make_strategy(syms, allowed)
with warnings.catch_warnings():
warnings.simplefilter("ignore")
return bt.backtest(strat, start=START, end=END, capital=CAPITAL,
data={s: data[s] for s in syms},
benchmark=data["NIFTY"]["close"],
costs=bt.costs.CostModel(backfill=True),
slippage=bt.slippage.bps(5))
def summary_row(result):
m = result.metrics
years = (pd.Timestamp(END) - pd.Timestamp(START)).days / 365.25
return {
"CAGR %": round(m["cagr"] * 100, 1),
"Max drawdown %": round(m["max_drawdown"] * 100, 1),
"Sharpe": round(m["sharpe"], 2),
"Total return %": round(m["total_return"] * 100, 1),
"Turnover per year (x equity)": round(m["turnover_ratio"] / years, 1),
}
TODAY_LIST = [
"ABB", "ADANIENSOL", "ADANIENT", "ADANIGREEN", "ADANIPORTS", "ADANIPOWER",
"AMBUJACEM", "APOLLOHOSP", "ASIANPAINT", "DMART", "AXISBANK", "BSE",
"BAJAJ-AUTO", "BAJFINANCE", "BAJAJFINSV", "BAJAJHLDNG", "BANKBARODA", "BEL",
"BPCL", "BHARTIARTL", "BOSCHLTD", "BRITANNIA", "CGPOWER", "CANBK",
"CHOLAFIN", "CIPLA", "COALINDIA", "CUMMINSIND", "DLF", "DIVISLAB",
"DRREDDY", "EICHERMOT", "ETERNAL", "GAIL", "GODREJCP", "GRASIM",
"HCLTECH", "HDFCAMC", "HDFCBANK", "HDFCLIFE", "HINDALCO", "HAL",
"HINDUNILVR", "HINDZINC", "POWERINDIA", "HYUNDAI", "ICICIBANK", "ITC",
"IOC", "IRFC", "INFY", "INDIGO", "JSWSTEEL", "JINDALSTEL",
"JIOFIN", "KOTAKBANK", "LTM", "LT", "M&M", "MARUTI",
"MAXHEALTH", "MAZDOCK", "MUTHOOTFIN", "NTPC", "NESTLEIND", "ONGC",
"PIDILITIND", "POLYCAB", "PFC", "POWERGRID", "PNB", "RELIANCE",
"SBILIFE", "MOTHERSON", "SHRIRAMFIN", "ENRIN", "SIEMENS", "SOLARINDS",
"SBIN", "SUNPHARMA", "TVSMOTOR", "TATACAP", "TCS", "TATACONSUM",
"TMCV", "TMPV", "TATAPOWER", "TATASTEEL", "TECHM", "TITAN",
"TORNTPHARM", "TRENT", "ULTRACEMCO", "UNIONBANK", "VBL", "VAML",
"VEDL", "IDEA", "WIPRO", "ZYDUSLIFE",
]
def prepare():
members = pd.read_csv(MEMBERSHIP_CSV, keep_default_na=False)
symbols = sorted(set(members.symbol) | set(TODAY_LIST))
data = load_all(symbols)
sessions = data["NIFTY"].index
data = fix_corporate_events(data, sessions)
data = adjust_splits(data)
return data, members
if __name__ == "__main__":
data, members = prepare()
results = {}
for universe, label in (("today", "Today's list"), ("pit", "Point-in-time")):
results[label] = run(data, members, universe)
print(label, summary_row(results[label]))
pickle.dump({k: (v.equity, dict(v.metrics), v.orders) for k, v in results.items()},
open("results.pkl", "wb"))
# Both equity curves on one chart, as growth of Rs 100 on a log scale
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(16, 9))
for (label, res), colour in zip(results.items(), ("#E53935", "#1565C0")):
eq = res.equity["equity_rupees"]
eq.index = eq.index.tz_localize(None).normalize()
ax.plot(eq.index, eq / eq.iloc[0] * 100, lw=4, color=colour, label=label)
nifty = data["NIFTY100"]["close"].loc[START:END]
ax.plot(nifty.index, nifty / nifty.iloc[0] * 100, lw=3, ls="--", color="#546E7A",
label="NIFTY 100 index")
ax.set_yscale("log")
ax.set_title("Nifty 100 momentum: today's list vs point-in-time", fontsize=26)
ax.legend(fontsize=20)
ax.grid(alpha=0.3)
fig.tight_layout()
fig.savefig("equity_curves.png", dpi=100)
Expected output:
Today's list {'CAGR %': 21.5, 'Max drawdown %': -35.8, 'Sharpe': 1.13, 'Total return %': 917.3, 'Turnover per year (x equity)': 9.6}
Point-in-time {'CAGR %': 7.8, 'Max drawdown %': -45.4, 'Sharpe': 0.52, 'Total return %': 145.4, 'Turnover per year (x equity)': 10.3}
The takeaway
The rules were never the problem; the stock list was. A momentum screen run on today’s index constituents rewards itself for picking stocks that we already know became large. On the list a trader could actually see, the same rules earned 7.8% a year with a deeper drawdown, and trailed the index. Before trusting any stock-selection backtest, build the universe as it stood on each date and rerun it. If the result survives that, it is worth studying further.
Learn by watching: free videos every week
Market Profile, order flow, Python, AI and OpenAlgo tutorials on YouTube.




