A Nifty 100 momentum strategy is one of the simplest systematic ideas you can test. Buy the stocks that have gone up the most in the last three months, and keep swapping out the ones that fall behind. We ran that rule on the Nifty 100 from January 2015 to November 2026 with the OpenAlgo Python SDK backtest engine, version 2.4.1.
Holding the top 20 stocks, rebalancing on the first trading day of each month, and paying the engine’s standard Indian charges plus 5 basis points of slippage, turned ₹100 into ₹1,027. The same ₹100 in the NIFTY 50 grew to ₹309, and in the NIFTY 100 to ₹319. Below you get the rules, the setup, the tuning grid, the results and the complete Python code, so you can run the same test on your own machine.
The Nifty 100 Momentum Strategy in Plain Words
Momentum is the tendency of strong stocks to stay strong for a while. Good news gets priced in slowly, funds buy in late, and trends tend to run longer than most people expect. A momentum strategy simply tries to ride those trends.
Here are the full rules. There are only five.
- Universe: the 100 stocks in the Nifty 100 index.
- Score: each stock’s 63-day rate of change, which is about three months, computed with
ta.roc. - Pick: the 20 stocks with the highest score.
- Weight: equal, after a 2 percent cash buffer, so each stock is 4.9 percent of the account.
- Rebalance: on the first trading day of every month, using
self.every("month", ...)andself.rebalance(...). Stocks that drop out of the top 20 are sold. The orders fill at the next day’s open.
That is the whole system. There are no stop losses, no extra filters and no market timing. The 3-month return is the only thing that decides what you hold. If you want the broader theory first, our guide to momentum trading covers it.
How the Momentum Backtest Is Set Up
The test is a portfolio strategy on the OpenAlgo backtest engine, in the same style as the SDK tutorials on costs and position sizing and a six-stock trend portfolio. You need openalgo 2.4.0 or later.
- Period: 1 January 2015 to 27 November 2026, about 11.9 years.
ta.rocloads the 63 trading days before the start, so the first monthly rebalance already has a full window. - Starting capital: ₹1 crore, so even expensive stocks can be bought in whole shares. The engine trades whole shares only, the way your broker does.
- Product: CNC, delivery, long only.
- Fills: decided at the close of the first session of the month, filled at the next session’s open, which is the engine default.
- Charges: the standard Indian cost model, including brokerage, STT, exchange charges, SEBI fee, stamp duty, GST and the DP charge. Dated rates begin on 1 July 2020; earlier fills use the oldest rates, with
CostModel(backfill=True). - Slippage: 5 basis points on every fill, set with
slippage=bt.slippage.bps(5). A buy fills a little higher and a sell a little lower than the next open. - Cash buffer: 2 percent, as in the engine’s rebalancing examples, so there is room for charges at the next open.
- Bonuses and splits: three unadjusted jumps, in CGPOWER, SIEMENS and VEDL, are back-adjusted so a bonus is not read as a crash.
The test uses today’s Nifty 100 list, so stocks that left the index along the way are missing, and that flatters the numbers.
Tuning the Nifty 100 Momentum Strategy Without Overfitting
The engine’s self.every timer accepts week, month, quarter or year. There is no built-in fortnightly schedule, and no every-N-trading-day timer, so the grid uses weekly and monthly rebalancing only.
We also tried three lookbacks close to three months, 55, 63 and 70 trading days, and a 0 or 5-day skip of the most recent week. That gives 12 combinations, all with the same charges and slippage. The period win rate is the share of rebalance-to-rebalance windows, including the last window to 27 November 2026, that ended in profit.
| Rebalance | Lookback | Skip | CAGR % | Max DD % | Sharpe | Win rate % | Rebalances |
|---|---|---|---|---|---|---|---|
| Weekly | 55 | 0 | 17.7 | -33.6 | 0.98 | 57.5 | 621 |
| Weekly | 55 | 5 | 22.0 | -35.0 | 1.16 | 58.5 | 621 |
| Weekly | 63 | 0 | 19.1 | -38.5 | 1.03 | 58.5 | 621 |
| Weekly | 63 | 5 | 20.0 | -35.3 | 1.07 | 58.4 | 620 |
| Weekly | 70 | 0 | 20.0 | -39.7 | 1.07 | 57.3 | 621 |
| Weekly | 70 | 5 | 19.9 | -40.0 | 1.06 | 57.3 | 621 |
| Monthly | 55 | 0 | 21.5 | -35.7 | 1.14 | 65.7 | 143 |
| Monthly | 55 | 5 | 20.5 | -37.9 | 1.11 | 63.6 | 143 |
| Monthly | 63 | 0 | 21.6 | -35.8 | 1.14 | 65.0 | 143 |
| Monthly | 63 | 5 | 20.2 | -39.3 | 1.08 | 66.9 | 142 |
| Monthly | 70 | 0 | 21.5 | -37.7 | 1.13 | 65.0 | 143 |
| Monthly | 70 | 5 | 22.2 | -36.5 | 1.16 | 65.0 | 143 |
Three things stand out.
- The monthly settings cluster tightly. With no skip, 55, 63 and 70 days all return 21.5% or 21.6% a year, with Sharpe ratios of 1.13 to 1.14. That is a stable neighbourhood, not a single lucky cell.
- Skipping the latest week is mixed. It helps some weekly settings, and it lifts monthly 70 days to 22.2%, the highest cell in the grid. It also raises the drawdown in several other monthly rows. There is no clear reason to make the skip part of the default rule.
- Weekly rebalancing is more sensitive. Weekly CAGRs run from 17.7% to 22.0%, and those runs send more than 600 rebalances, so they pay more charges and slippage.
For the final Nifty 100 momentum strategy we chose monthly rebalancing with a 63-day lookback and no skip. It is the plainest version of the rule: exactly three months, once a month, and it sits in the middle of the tight monthly cluster rather than on the single highest cell.
Results: Nifty 100 Momentum Strategy vs the Index
The chart uses a log scale, so equal slopes mean equal percentage gains. The momentum portfolio pulls away in 2016 and 2017, gives back ground around 2018 and 2020, and then runs hard from mid-2020 to mid-2024.
| Metric | Momentum top 20 | NIFTY 50 | NIFTY 100 |
|---|---|---|---|
| Total return | 926.5% | 209.1% | 219.0% |
| CAGR | 21.6% | 9.9% | 10.2% |
| Volatility (annual) | 18.7% | – | – |
| Sharpe ratio | 1.14 | – | – |
| Maximum drawdown | -35.8% | – | – |
| Rebalances | 143 | – | – |
| Period win rate | 65.0% | – | – |
| Periods beating NIFTY 50 | 57.3% | – | – |
| Closed trades (engine) | 1,127, 49.2% won | – | – |
In rupee terms, ₹1 lakh invested in January 2015 would have grown to about ₹10.27 lakh. The same amount in the NIFTY 50 would be close to ₹3.09 lakh, and in the NIFTY 100 about ₹3.19 lakh.
On the ₹1 crore test account the engine charged ₹55.86 lakh in total costs and ₹32.70 lakh in slippage over the full run. Those are real rupees, but the net profit was still ₹9.27 crore.
The Sharpe ratio is 1.14. The engine annualises volatility with a session count that treats every weekday in 2015 to 2018 as a trading day, because no holiday list is loaded for those years, so that Sharpe is a little conservative.
Win rate needs a clear definition. The useful figure for this strategy is the holding-period win rate: 65.0% of 143 monthly windows, from one rebalance to the next, ended in profit. Against the NIFTY 50 the strategy won 57.3% of those windows, which also means it trailed the index in about four months out of ten. The engine also reports a trade win rate of 49.2% of 1,127 closed trades. That counts every time a stock is sold down or sold out, so one rebalance can close several trades.
Drawdowns: The Part You Have to Sit Through
The worst fall was 35.8%, from 17 January to 23 March 2020, during the Covid crash.
There were other painful stretches too. The portfolio fell 23.4% from August 2015 to February 2016, 14.5% from August to October 2018, and 23.6% from July 2024 to March 2025. After the July 2024 peak it has not made a new high, and as of 27 November 2026 it is about 12% below that peak.
Year by Year
The strategy beat the NIFTY 50 in 9 of the 12 calendar years, counting the partial years 2015 and 2026. The biggest gaps came in 2021 (62.4% against 24.1%) and 2023 (55.1% against 20.0%).
It lagged in 2019 (10.1% against 12.0%), in 2025 (3.5% against 10.5%) and in 2026 so far (down 5.5% against a 2.0% decline in the NIFTY 50). Those were years when market leadership kept rotating, so yesterday’s winners did not stay on top for long.
Quick Worked Example: Rank Stocks by 3-Month Return in Python
Before running the full backtest, try the core idea on ten large stocks. This short script fetches six months of daily prices, works out each stock’s 63-day return and sorts them from strongest to weakest.
import os
import pandas as pd
from openalgo import api
client = api(api_key=os.getenv("OPENALGO_API_KEY"), host="http://127.0.0.1:5000")
symbols = ["RELIANCE", "HDFCBANK", "ICICIBANK", "INFY", "TCS",
"BHARTIARTL", "SBIN", "LT", "ITC", "MARUTI"]
scores = {}
for sym in symbols:
df = client.history(symbol=sym, exchange="NSE", interval="D",
start_date="2026-06-01", end_date="2026-11-27")
close = df["close"]
scores[sym] = (close.iloc[-1] / close.iloc[-64] - 1) * 100 # 63-day return
ranked = pd.Series(scores).sort_values(ascending=False).round(1)
print(ranked)
print("Top 3 by 3-month return:", list(ranked.index[:3]))
close.iloc[-1] is the latest close and close.iloc[-64] is the close 63 trading days earlier. Their ratio, minus one, is the 3-month return. Running it on 28 November 2026 printed:
HDFCBANK 17.9
TCS 13.3
ITC 12.7
ICICIBANK 11.4
BHARTIARTL 8.7
SBIN 6.8
RELIANCE 6.5
INFY 5.2
MARUTI 1.8
LT 1.7
dtype: float64
Top 3 by 3-month return: ['HDFCBANK', 'TCS', 'ITC']
That ranking step is the engine of the strategy. The full backtest repeats it for 100 stocks, every month, for almost twelve years, then hands the target weights to self.rebalance.
Full Python Code for the Nifty 100 Momentum Strategy
This is the complete Nifty 100 momentum strategy script behind every number in this article. It downloads the daily bars, adjusts unadjusted bonuses and splits, runs the backtest on the OpenAlgo engine, prints the metrics and saves the charts. Add --grid to rebuild the tuning table.
To run it:
- Start OpenAlgo on your machine and log in to your broker.
- Install the libraries:
pip install "openalgo>=2.4.0" pandas numpy matplotlib - Set your API key as an environment variable named
OPENALGO_API_KEY. - Run
python nifty100_momentum_backtest.py, or add--gridto rebuild the tuning table.
You can also download the script as a zip file.
"""
Nifty 100 Momentum Backtest with the OpenAlgo Python SDK backtest engine
------------------------------------------------------------------------
Strategy: rank every Nifty 100 stock by its trailing 3-month return
(ta.roc lookback), hold the top 20, rebalance on a calendar schedule.
Requires: openalgo 2.4.0 or later, pandas, numpy, matplotlib
pip install "openalgo>=2.4.0" pandas numpy matplotlib
Before running: start OpenAlgo locally and set your API key:
export OPENALGO_API_KEY="your_key_here"
Run:
python nifty100_momentum_engine.py # chosen settings
python nifty100_momentum_engine.py --grid # also run the parameter grid
"""
import os
import sys
import time
import warnings
import pickle
import numpy as np
import pandas as pd
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
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 # trading days in the ranking window (about 3 months)
SKIP = 0 # recent days to skip before the window (0 = none)
SCHEDULE = "month" # self.every period: "week", "month", "quarter" or "year"
TOP_N = 20
CAPITAL = 10_000_000 # Rs 1 crore, so expensive stocks still get whole shares
CASH_BUFFER = 2.0 # percent kept in cash for charges, as in the docs
DATA_FILE = "nifty100_ohlcv.pkl"
ADJUSTED_FILE = "nifty100_ohlcv_adjusted.pkl"
# Current Nifty 100 constituents (NSE list, November 2026)
NIFTY100 = [
"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 fetch_frame(client, symbol, exchange):
for _ in range(3):
df = client.history(symbol=symbol, exchange=exchange, interval="D",
start_date="2014-01-01", end_date=END)
if isinstance(df, pd.DataFrame) and not df.empty:
out = df[["open", "high", "low", "close", "volume"]].copy()
out.index = pd.to_datetime(out.index).tz_localize(None)
out = out[~out.index.duplicated(keep="last")].sort_index()
return out
time.sleep(1)
print(f" could not fetch {symbol}: {df}")
return None
def _clean(frame):
f = frame.copy()
f.index = pd.to_datetime(f.index).tz_localize(None).normalize()
for c in f.columns:
f[c] = pd.to_numeric(f[c], errors="coerce").astype(float)
f = f[(f[["open", "high", "low", "close"]] > 0).all(axis=1)]
return f[~f.index.duplicated(keep="last")].sort_index()
def adjust_splits(data):
"""Use the engine's data-quality check to find unadjusted bonuses or splits,
then back-adjust older prices so a bonus is not read as a crash."""
from openalgo.backtest.data import load_bars
out = {}
for sym, frame in data.items():
f = _clean(frame)
if sym in ("NIFTY", "NIFTY100"):
out[sym] = f
continue
while True:
r = load_bars(sym, "NSE", "D", start="2014-01-01", end=END,
data=f, cache=False, strict=False, tz="Asia/Kolkata")
splits = [g for g in (r.meta.quality.price_gaps or [])
if g.status == "suspected" and g.factor]
if not splits:
break
g = sorted(splits, key=lambda x: x.ex_date, reverse=True)[0]
mask = f.index < pd.Timestamp(g.ex_date)
factor = float(g.factor)
for c in ("open", "high", "low", "close"):
f.loc[mask, c] = f.loc[mask, c] / factor
f.loc[mask, "volume"] = f.loc[mask, "volume"] * factor
print(f" adjusted {sym} {g.ex_date}: {g.reading}, factor {factor:g}")
out[sym] = f
return out
def load_data():
if os.path.exists(ADJUSTED_FILE):
print(f"Loading adjusted bars from {ADJUSTED_FILE}")
return pickle.load(open(ADJUSTED_FILE, "rb"))
if os.path.exists(DATA_FILE):
print(f"Loading cached bars from {DATA_FILE}")
raw = pickle.load(open(DATA_FILE, "rb"))
else:
client = api(api_key=API_KEY, host=HOST)
raw = {}
for i, sym in enumerate(NIFTY100, 1):
print(f"[{i}/{len(NIFTY100)}] {sym}")
f = fetch_frame(client, sym, "NSE")
if f is not None:
raw[sym] = f
for name, ex in (("NIFTY", "NSE_INDEX"), ("NIFTY100", "NSE_INDEX")):
f = fetch_frame(client, name, ex)
if f is not None:
raw[name] = f
pickle.dump(raw, open(DATA_FILE, "wb"))
data = adjust_splits(raw)
pickle.dump(data, open(ADJUSTED_FILE, "wb"))
return data
def make_strategy(symbols, lookback=LOOKBACK, skip=SKIP, schedule=SCHEDULE, top_n=TOP_N):
class MomentumTop20(bt.Strategy):
# several stocks: "symbols", not "symbol"
pass
MomentumTop20.symbols = tuple(symbols)
MomentumTop20.exchange = "NSE"
MomentumTop20.interval = "D"
MomentumTop20.product = "CNC"
MomentumTop20.lookback = int(lookback)
MomentumTop20.skip = int(skip)
MomentumTop20.schedule = schedule
MomentumTop20.top_n = int(top_n)
def init(self):
# ta.roc also loads the lookback bars before start, so the first
# rebalance already has a full 3-month window.
self.roc = {s: self.I(ta.roc, self.data[s].close, self.lookback)
for s in self.symbols}
self.every(self.schedule, self.rebalance_now)
def rebalance_now(self):
scores = {}
for s in self.symbols:
idx = -1 - self.skip
if len(self.roc[s]) <= self.skip:
continue
v = self.roc[s][idx]
if v == v: # not NaN
scores[s] = float(v)
if len(scores) < self.top_n:
return
picks = sorted(scores, key=scores.get, reverse=True)[: self.top_n]
weight = (100.0 - CASH_BUFFER) / len(picks)
self.rebalance({s: weight for s in picks}, cash_buffer=CASH_BUFFER)
MomentumTop20.init = init
MomentumTop20.rebalance_now = rebalance_now
MomentumTop20.__name__ = f"MomentumTop{top_n}_{schedule}_{lookback}_{skip}"
return MomentumTop20
def run(data, lookback=LOOKBACK, skip=SKIP, schedule=SCHEDULE, top_n=TOP_N,
capital=CAPITAL, start=START, end=END, benchmark="NIFTY"):
symbols = [s for s in NIFTY100 if s in data]
strat = make_strategy(symbols, lookback=lookback, skip=skip,
schedule=schedule, top_n=top_n)
bars = {s: data[s] for s in symbols}
bench = data[benchmark]["close"] if benchmark in data else None
with warnings.catch_warnings(record=True) as caught:
warnings.simplefilter("always")
result = bt.backtest(
strat,
start=start,
end=end,
capital=capital,
data=bars,
benchmark=bench,
costs=bt.costs.CostModel(backfill=True),
slippage=bt.slippage.bps(5),
)
kinds = [type(w.message).__name__ for w in caught]
return result, kinds
def equity_series(result):
eq = result.equity.copy()
eq.index = pd.to_datetime(eq.index).tz_convert(None) if getattr(eq.index, "tz", None) else pd.to_datetime(eq.index)
col = "equity_rupees" if "equity_rupees" in eq.columns else "equity"
s = eq[col].astype(float)
return s[s > 0]
def period_stats(result):
"""Holding-period win rate: share of rebalance-to-rebalance windows with a positive return."""
s = equity_series(result)
orders = result.orders
if orders is None or orders.empty:
return {}
times = pd.to_datetime(orders["time"])
if getattr(times.dt, "tz", None) is not None:
times = times.dt.tz_convert(None)
days = sorted(pd.DatetimeIndex(times).normalize().unique())
pts = []
idx = s.index.normalize()
for t in days:
sl = s[idx >= t]
if len(sl):
pts.append((sl.index[0], float(sl.iloc[0])))
# add the final equity so the last holding period is counted
if not pts or pts[-1][0] != s.index[-1]:
pts.append((s.index[-1], float(s.iloc[-1])))
ser = pd.Series({t: v for t, v in pts}).sort_index()
ret = ser.pct_change().dropna()
return {
"Rebalances": int(len(days)),
"Period win rate %": float((ret > 0).mean() * 100),
"Periods": int(len(ret)),
}
def metrics_row(result, period=None):
m = result.metrics
out = {
"Total return %": m["total_return"] * 100,
"CAGR %": m["cagr"] * 100,
"Volatility %": m["volatility"] * 100,
"Sharpe": m["sharpe"],
"Max drawdown %": m["max_drawdown"] * 100,
"Trade win rate %": m.get("win_rate", float("nan")) * 100 if m.get("win_rate") is not None else float("nan"),
"Closed trades": m.get("trades"),
"Charges Rs": m.get("total_costs"),
"Slippage Rs": m.get("total_slippage"),
}
if period:
out.update(period)
# benchmark
for k in m:
if "benchmark" in k.lower() or k in ("benchmark_return", "benchmark_cagr"):
out[k] = m[k]
return out
def charts(result, path_prefix="engine"):
eq = result.equity.copy()
eq.index = pd.to_datetime(eq.index).tz_localize(None)
col = "equity" if "equity" in eq.columns else [c for c in eq.columns if "equity" in c.lower() or "value" in c.lower()]
if isinstance(col, list):
col = col[0] if col else eq.columns[0]
s = eq[col].astype(float)
# drop leading zeros / pre-start
s = s[s > 0]
curves = pd.DataFrame({"Momentum top 20": s})
# benchmark if present
for name in ("benchmark", "benchmark_equity", "NIFTY"):
if name in eq.columns:
curves[name] = eq[name]
break
curves = curves.dropna(how="all")
curves = curves / curves.iloc[0] * 100
fig, ax = plt.subplots(figsize=(11, 5.5))
for c in curves.columns:
ax.plot(curves.index, curves[c], label=c, lw=1.8)
ax.set_yscale("log")
ax.set_title("Nifty 100 momentum (top 20) vs index, growth of 100")
ax.grid(alpha=0.3)
ax.legend()
fig.tight_layout()
fig.savefig(f"{path_prefix}_equity_curve.png", dpi=110)
fig, ax = plt.subplots(figsize=(11, 4))
for c in curves.columns:
dd = (curves[c] / curves[c].cummax() - 1) * 100
ax.plot(dd.index, dd, label=c, lw=1.4)
ax.set_title("Drawdown from previous peak (%)")
ax.grid(alpha=0.3)
ax.legend(loc="lower left")
fig.tight_layout()
fig.savefig(f"{path_prefix}_drawdown.png", dpi=110)
print(f"Saved {path_prefix}_equity_curve.png and {path_prefix}_drawdown.png")
def run_grid(data):
rows = []
# fortnightly is not a self.every period (only week, month, quarter, year)
for schedule, label in (("week", "Weekly"), ("month", "Monthly")):
for lookback in (55, 63, 70):
for skip in (0, 5):
t0 = time.time()
result, kinds = run(data, lookback=lookback, skip=skip, schedule=schedule)
p = period_stats(result)
m = metrics_row(result, p)
row = {
"Rebalance": label,
"Lookback": lookback,
"Skip": skip,
"CAGR %": round(m["CAGR %"], 1),
"Max DD %": round(m["Max drawdown %"], 1),
"Sharpe": round(m["Sharpe"], 2),
"Period win rate %": round(m.get("Period win rate %", float("nan")), 1),
"Rebalances": m.get("Rebalances"),
"Trade win rate %": round(m["Trade win rate %"], 1) if m["Trade win rate %"] == m["Trade win rate %"] else None,
}
print(row, "in", round(time.time() - t0, 1), "s", "warn", set(kinds))
rows.append(row)
grid = pd.DataFrame(rows)
grid.to_csv("parameter_grid_engine.csv", index=False)
return grid
if __name__ == "__main__":
data = load_data()
print(f"Loaded {len(data)} series (including any index bars)")
if "--grid" in sys.argv:
print(run_grid(data).to_string(index=False))
result, kinds = run(data)
print("warning types:", set(kinds))
try:
print(result.summary())
except Exception as e:
print("summary() skipped:", type(e).__name__, e)
p = period_stats(result)
m = metrics_row(result, p)
print("\nSettings: lookback", LOOKBACK, "skip", SKIP, "schedule", SCHEDULE,
"top", TOP_N, "capital", CAPITAL, "slippage 5 bps, standard costs, backfill=True")
for k, v in m.items():
print(f" {k}: {v}")
print("equity columns:", list(result.equity.columns))
print("metrics benchmark-related:")
for k, v in result.metrics.items():
if "bench" in k.lower() or k in ("alpha", "beta", "information_ratio"):
print(f" {k}: {v}")
if not result.orders.empty:
result.orders.to_csv("engine_rebalance_orders.csv", index=False)
print("orders", len(result.orders), "at", result.orders["time"].nunique(), "dates")
print("last holdings:")
print(result.final_positions.to_string(index=False))
charts(result)
equity_series(result).to_csv("engine_equity.csv", header=["equity"])
pd.Series({k:(float(v) if hasattr(v,"real") else str(v)) for k,v in result.metrics.items()}).to_csv("engine_metrics.csv")
How the Code Works, Step by Step
- Settings: lookback, skip, schedule, top 20, capital, cash buffer and dates sit at the top.
- Download:
client.history()pulls daily bars for each Nifty 100 stock and the two index series, then caches them. - Adjustments:
load_bars(..., strict=False)flags unadjusted bonuses or splits. Older prices are back-adjusted so those jumps are not treated as crashes. - Strategy class:
symbolsholds the universe.self.I(ta.roc, ...)builds the 3-month score and loads the warm-up bars before the start date.self.every("month", ...)callsrebalance_nowon the first session of each month. - Rebalance: the 20 highest scores get equal weight after the 2 percent cash buffer. A stock left out of the dict is sold, which is how the top 20 is enforced. The engine has no built-in “top N of a universe” ranker, so that ranking lives in
rebalance_now. - Costs:
bt.costs.CostModel(backfill=True)applies standard Indian charges, andbt.slippage.bps(5)adds 5 basis points on every fill. - Results:
result.summary(),result.metrics,result.equity,result.ordersandresult.final_positionshold the figures used above.
The first run fetches about 100 symbols and takes a couple of minutes. Later runs use the cache and finish the backtest in under ten seconds. With the default settings the summary looks like this:
Net profit : Rs 9,26,54,293.12
Return : 926.54%
Max drawdown : -35.82%
Trades : 1127 (49% won), 20 still open
Overfitting : quick checks: 3 passed, 1 informational; see result.robustness()
Benchmark : 195.47% return (given closes)
Settings: lookback 63, skip 0, rebalance monthly, top 20
Capital Rs 1,00,00,000; standard charges with backfill; slippage 5 bps
CAGR 21.6% Volatility 18.7% Sharpe 1.14
Period win rate 65.0% of 143 monthly windows Rebalances 143
Your numbers should match closely. Small differences can creep in if a corporate action is adjusted slightly differently, or if a newly listed stock has a shorter history.
Ideas to Test Next
Once the script runs, try changing one setting at a time and see what moves.
- Set
TOP_Nto 10 or 30 to see how concentration changes return and drawdown. - Switch
SCHEDULEto"week", or raise the cash buffer. - Try a 6-month lookback (126 days) or a 12-month one (252 days) and compare the results with the 3-month rule.
The Takeaway
This plain Nifty 100 momentum strategy beat the index over almost twelve years on the OpenAlgo backtest engine: 21.6% a year against 9.9% for the NIFTY 50, after standard Indian charges and 5 basis points of slippage, with a Sharpe of 1.14. Monthly rebalancing with a 63-day lookback sits in a tight cluster of neighbouring settings, all near 21.5%.
The price is real, though. Expect falls of 20% to 36%, long stretches below a previous peak, and roughly four months in ten when the index does better. Run the code, change the settings, and decide for yourself whether you could live with the drawdowns before you rely on the returns.
Learn by watching: free videos every week
Market Profile, order flow, Python, AI and OpenAlgo tutorials on YouTube.




