Most traders I meet have an idea they believe in but have never tested properly. A backtest settles that question. It replays years of real prices through your rules, charges every trade the way the exchange and the government would, and shows what would actually have happened.
In this first part of the series, I will run a Supertrend backtest on SBIN with the OpenAlgo Python SDK and then look at something beginners usually skip: how much to buy on each trade.
I built OpenAlgo, so I am naturally close to this tool. The numbers below are exactly what the run produced.
Backtesting using OpenAlgo Python SDK
1. Your first backtest: Supertrend on SBIN and position sizing (this article)
2. Building signals with OpenAlgo indicators
3. Reading the results: P&L, drawdown, win rate and the equity curve
4. Realistic costs and position sizing in depth
5. Options and multi-leg backtests
What the OpenAlgo Python SDK does
The OpenAlgo Python SDK is one package, pip install openalgo, that brings three things together.
- The OpenAlgo API. The
apiclient talks to your own OpenAlgo server: historical data, quotes, positions and orders, all through one Python object. - 128 technical indicators. The
tamodule ships 128 indicators and helper functions, from moving averages and RSI to Supertrend, with the maths running in a compiled Rust core. - Backtesting with live execution. The
openalgo.backtestmodule runs a strategy on past prices withbt.backtest. The same strategy class can later run on today’s prices withbt.live, which sends its orders through OpenAlgo.
For a beginner, that last point matters most. You write your rules once, as a Python class, and the same class serves both the test and the real thing.
Two honest caveats from the current docs. First, the backtesting engine is marked Preview, so names and arguments may still change in later releases. Second, in openalgo 2.4.1 a live session runs intraday strategies only (one-minute bars and up, MIS product). The daily strategy in this article is for backtesting; moving a strategy live means writing an intraday version of it. Whatever you run live, start in OpenAlgo’s Analyze mode, its paper trading sandbox, where orders are simulated at real prices and nothing reaches your broker.
What event-driven backtesting means
There are two broad ways to build a backtester.
A vectorised backtester computes everything at once on whole columns of data: all the signals, all the positions, all the returns, in a few array operations. It is fast, but it is easy to slip and let a calculation use a price from later in the column. That mistake is called look-ahead bias, and it makes results look far better than anything you could have traded.
OpenAlgo’s backtester is event-driven. The engine walks through the data one bar at a time (a bar is one day’s open, high, low and close here). At each bar’s close it reveals the prices up to that bar, calls your on_bar method, and your code decides using only what was known at that moment. Any order you place is queued and, by default, fills at the open of the next bar, plus a small slippage. So a buy decided at Monday’s close is filled at Tuesday’s open.
I checked this in both the docs and the SDK source. The default is fill="next_open", and you can choose a worse price of that next bar for stress testing ("next_close", "next_mid" or "next_ohlc4") or hold orders back extra bars with delay_entries and delay_exits. Filling at the same bar’s close is not available.
Why this matters for a beginner: an event-driven test cannot cheat by peeking at tomorrow, and it behaves the way live trading does. You see a closing price, decide, and get filled later at a price you could not control.
The rules, stated up front
I fixed these before running anything and did not change them afterwards.
- Instrument: SBIN on NSE, daily bars.
- Indicator: Supertrend 10/3. Supertrend is a trend line drawn a set distance below the price in an uptrend and above it in a downtrend; it flips sides when the price closes through it. The distance is based on ATR (average true range), the size of a typical day’s move. “10/3” means ATR measured over 10 days, and the line sits 3 ATRs away.
- Entry: buy when Supertrend shows an uptrend.
- Exit: go flat when it flips to a downtrend. Long only, no shorts.
- Capital: Rs 1,00,000.
- Period: 1 January 2021 to 23 November 2026, the latest completed daily bar.
- Sizing: four methods on identical signals, explained below.
Install and connect
I ran everything on openalgo 2.4.1 with Python 3.12 or newer.
pip install -U openalgo plotly kaleido
You need your OpenAlgo server running and its API key. The source parameter decides where bars come from: source="db" reads Historify, the market database inside OpenAlgo, and source="api" reads your broker’s history through OpenAlgo. I used Historify.
import os # to read the API key from an environment variable
import openalgo.backtest as bt # the SDK's backtesting engine
from openalgo import api, ta # api talks to your OpenAlgo server, ta has the indicators
# Connect to your own OpenAlgo server (replace your_api_key with the key from its API Key page)
client = api(api_key=os.getenv("OPENALGO_API_KEY", "your_api_key"), host="http://127.0.0.1:5000")
SYMBOL, EXCHANGE = "SBIN", "NSE" # the stock and its exchange
START, END = "2021-01-01", "2026-11-23" # test period; 23 Nov 2026 is the latest completed daily bar
CAPITAL = 100_000 # starting capital, Rs 1,00,000
# Daily bars from Historify; change to source="api" to read your broker's history instead
df = client.history(symbol=SYMBOL, exchange=EXCHANGE, interval="D",
start_date="2020-06-01", end_date=END, source="db")
print(df.tail(3)) # the last three rows, to check the data is current
Supertrend with openalgo ta
The documented signature is ta.supertrend(high, low, close, period=10, multiplier=3.0). It returns two series, the line and its direction. Remember that direction is -1 in an uptrend and 1 in a downtrend; getting that backwards is the most common Supertrend bug I see.
# ta.supertrend returns two series: the line itself and its direction
# direction is -1 in an uptrend and 1 in a downtrend
df["st"], df["st_dir"] = ta.supertrend(df["high"], df["low"], df["close"],
period=10, multiplier=3.0)
# A flip is any day the direction changes from the day before
flips = (df["st_dir"].diff() != 0) & df["st_dir"].shift().notna()
print("Trend flips since 2021:", int(flips.loc[START:].sum()))
Trend flips since 2021: 48
The strategy class
A strategy is a small class. init sets up the indicator once, and on_bar runs at every daily close. Wrapping the indicator in self.I(...) lets the engine warm it up on earlier bars and check that it never uses a future price.
class SupertrendAllEquity(bt.Strategy):
symbol, exchange, interval = SYMBOL, EXCHANGE, "D" # SBIN on NSE, daily bars
period = 10 # ATR period of the Supertrend
multiplier = 3 # how many ATRs away the line sits
def init(self):
# Runs once before the first bar. self.I registers the indicator with the engine,
# so each bar sees only values known at that bar.
self.line, self.direction = self.I(
ta.supertrend, self.high, self.low, self.close, self.period, self.multiplier
)
def enter(self):
self.buy() # default sizing: whole shares for about 98% of current equity
def on_bar(self, bar):
# Runs at the close of every daily bar
uptrend = self.direction[-1] < 0 # [-1] is today's value; -1 means uptrend
if self.position.is_flat and uptrend: # no shares held and the trend is up
self.enter() # buy; fills at the next bar's open
elif self.position.is_long and not uptrend: # holding shares and the trend flipped down
self.exit() # sell everything at the next bar's open
I put the buy in its own enter method so the sizing can be swapped without touching the rules.
Position sizing: four ways to buy the same signal
The signal tells you when to trade. Position sizing decides how much, and it shapes the result just as strongly.
class SupertrendFixed50k(SupertrendAllEquity):
def enter(self):
self.buy(size=bt.size.value(50_000)) # a fixed Rs 50,000 per trade
class SupertrendHalfEquity(SupertrendAllEquity):
def enter(self):
self.buy(size=bt.size.percent(50)) # 50% of current equity per trade
class SupertrendFixedShares(SupertrendAllEquity):
def enter(self):
self.buy(size=bt.size.qty(80)) # a fixed 80 shares per trade
variants = {
"All equity (default buy)": SupertrendAllEquity,
"Fixed Rs 50,000 per trade": SupertrendFixed50k,
"50% of equity per trade": SupertrendHalfEquity,
"Fixed 80 shares per trade": SupertrendFixedShares,
}
results = {}
for name, strategy in variants.items():
# Same rules, dates, capital and data source; only the sizing differs
results[name] = bt.backtest(strategy, client, start=START, end=END,
capital=CAPITAL, source="db")
- All equity, the default
self.buy(): buys as many whole shares as about 98 percent of current equity allows. Equity is your cash plus the market value of the shares you hold, so profits and losses compound. - Fixed amount,
bt.size.value(50_000): every trade gets Rs 50,000, however the account is doing. - Percent of equity,
bt.size.percent(50): each trade gets half of current equity. - Fixed shares,
bt.size.qty(80): every trade buys 80 shares. I first checked 100 shares, a round number that looks reasonable for Rs 1,00,000. At the dearest fill of the test, 21 April 2026 at Rs 1,113.65, 100 shares would have cost Rs 1,11,365, more than the starting capital. 80 shares cost Rs 89,092 at that same price, and they still fit inside Rs 1,00,000 at the period’s highest open of Rs 1,232.00.
How OpenAlgo backtesting handles commissions and charges
Every fill in this backtest is charged the way an Indian trade is charged, and the featured net profit of Rs 50,808.07 is after those costs. On the all-equity run the engine reported Rs 8,339.27 in charges.
Each fill pays the broker’s fee plus the statutory and exchange items:
- Brokerage. The default preset is
"standard". A delivery order pays 2.5 percent of its value or Rs 20, whichever is lower; an intraday order 0.1 percent or Rs 20; a futures order 0.03 percent or Rs 20; an option order Rs 20. - STT, securities transaction tax (commodity transaction tax on MCX).
- Exchange transaction charge and the SEBI fee.
- Stamp duty, on the buy side only.
- GST, 18 percent on the brokerage, the exchange charge and the SEBI fee.
- DP charge, on the first delivery sell of a stock in a day: Rs 13 plus GST.
The rates used are the ones in force on that trade’s date. The account is charged what the day’s contract note would charge, with STT and stamp duty rounded to whole rupees once per day.
Because this strategy uses daily bars on SBIN, the engine traded it as CNC (delivery). Daily equity defaults to CNC; an intraday interval defaults to MIS. That choice changes the bill. Delivery brokerage is 2.5 percent or Rs 20, and a delivery sell also pays the DP charge. Intraday brokerage is 0.1 percent or Rs 20, and there is no DP charge. Every fill in this run was CNC.
Pass costs= to bt.backtest to use a different brokerage. The taxes and exchange charges still apply. costs=None turns every charge off, and the engine then warns that the profit is overstated.
# This run used the default, costs="standard". Other brokerage choices:
# result = bt.backtest(..., costs="zerodha") # no brokerage on delivery
# result = bt.backtest(..., costs=bt.costs.flat(20)) # Rs 20 a fill
# result = bt.backtest(..., costs="zero_brokerage") # taxes and exchange charges only
print(f"Charges : Rs {main.metrics['total_costs']:,.2f}")
print(main.costs[["side", "brokerage", "stt", "exchange_txn", "sebi_fee",
"stamp_duty", "gst", "dp_charge", "charged"]].head(2).round(2))
Charges : Rs 8,339.27
side brokerage stt exchange_txn sebi_fee stamp_duty gst dp_charge charged
BUY 20.0 98.68 3.40 0.05 14.80 4.21 0.00 141.66
SELL 20.0 98.04 3.38 0.05 0.00 4.21 15.34 140.98
The featured result: all equity
main = results["All equity (default buy)"] # the featured run
print(main.summary()) # net profit, return, drawdown and trades
m = main.metrics # a dictionary of 100+ figures
print(f"CAGR : {m['cagr']:.2%}") # growth rate per year
print(f"Win rate : {m['win_rate']:.2%}") # share of closed trades that made money
print(f"Profit factor : {m['profit_factor']:.2f}") # rupees won per rupee lost
print(f"Charges : Rs {m['total_costs']:,.2f}") # brokerage, taxes and fees paid
Net profit : Rs 50,808.07
Return : 50.81%
Max drawdown : -29.98%
Trades : 24 (46% won), 1 still open
Overfitting : too few trades to judge (24 closed, 30 needed)
CAGR : 7.22%
Win rate : 45.83%
Profit factor : 1.44
Charges : Rs 8,339.27
What each line means:
- Net profit is the final account value minus the starting capital, after all costs.
- Max drawdown is the largest fall from a peak in account value to a later low. Here the account was, at its worst, 29.98 percent below its previous high. It is the number that tests your patience.
- CAGR (compound annual growth rate) is the steady yearly growth that would turn Rs 1,00,000 into the final value: 7.22 percent a year.
- Win rate is the share of closed trades that made money: 11 of 24.
- Profit factor is total rupees won divided by total rupees lost: Rs 1.44 won for every rupee lost. Above 1 means the winners outweighed the losers.
- Charges are the Indian trading costs the SDK applies to every fill: brokerage, STT, exchange transaction charges, SEBI fee, stamp duty, GST and the DP charge on delivery sells. Slippage is applied on top, in the fill prices.
The last trade was still open on 23 November, so the split matters. Realised profit is locked in by closed trades. Unrealised profit is the paper gain on a position you still hold, valued at the last close.
trades = main.trade_list() # one row per closed trade
realised = trades["net_pnl"].sum() # profit locked in by closed trades
net = main.equity["equity_rupees"].iloc[-1] - CAPITAL # final account value minus capital
print(f"Realised (closed trades) : Rs {realised:,.2f}")
print(f"Open trade, mark to last close (after its entry charges): Rs {net - realised:,.2f}")
print(main.final_positions[["symbol", "quantity_units", "unrealized_rupees"]].to_string(index=False))
Realised (closed trades) : Rs 33,666.23
Open trade, mark to last close (after its entry charges): Rs 17,141.84
symbol quantity_units unrealized_rupees
SBIN 129.0 17318.25
The open position shows Rs 17,318.25 unrealised; after its entry charges of Rs 176.41 it adds Rs 17,141.84. Together with the realised Rs 33,666.23, that is the Rs 50,808.07 net profit. About a third of it is still on paper.

The chart shows the character of the system. In strong trends it stays in for long stretches. In sideways phases it takes small losses, as any trend follower does.
How sizing changed the outcome
rows = []
for name, result in results.items():
mm, tl = result.metrics, result.trade_list()
rows.append({
"Sizing": name,
"Net P&L (Rs)": round(mm["net_profit"], 2),
"CAGR %": round(mm["cagr"] * 100, 2),
"Max DD %": round(mm["max_drawdown"] * 100, 2),
"Avg trade (Rs)": round(tl["net_pnl"].mean(), 2),
"Worst trade (Rs)": round(tl["net_pnl"].min(), 2),
"Profit factor": round(mm["profit_factor"], 2),
})
print(pd.DataFrame(rows).set_index("Sizing").to_string())
| Sizing | Net P&L | CAGR | Max drawdown | Avg trade P&L | Worst trade | Profit factor |
|---|---|---|---|---|---|---|
| All equity (default) | Rs 50,808.07 | 7.22% | -29.98% | Rs 1,402.76 | Rs -14,376.83 | 1.44 |
| Fixed Rs 50,000 | Rs 23,669.88 | 3.67% | -14.38% | Rs 715.54 | Rs -4,979.62 | 1.59 |
| 50% of equity | Rs 24,750.93 | 3.82% | -16.64% | Rs 710.72 | Rs -6,071.41 | 1.50 |
| Fixed 80 shares | Rs 18,191.29 | 2.88% | -19.13% | Rs 315.41 | Rs -8,803.89 | 1.21 |
All four are profitable on the same 24 signals, with the same 11 winning trades. Putting the whole account to work still makes the most money, and it also has the largest drawdown and the worst single trade. The fixed Rs 50,000 version has the best profit factor because its size did not grow after winning streaks, so later losers hurt less.
The fixed 80-share version works the other way around. The share count stays the same, so the rupee size of each trade grew as SBIN rose: Rs 22,556 at the first fill (80 shares at Rs 281.95 on 4 January 2021) and Rs 89,092 at the dearest fill (80 shares at Rs 1,113.65 on 21 April 2026). That is why its worst trade, Rs -8,803.89, and its 19.13 percent drawdown are both larger than on the two smaller rupee-based methods, while its net profit, Rs 18,191.29, is the smallest of the four. Of that profit, Rs 7,569.87 is realised and Rs 10,621.42 is still on paper in the open 80-share position.
The equity curve below plots the account value at every day’s close, one line per sizing method.

My practical takeaway: decide the drawdown you can sit through first, then choose the size.
An honest benchmark
A benchmark is what you compare a strategy against, usually simply holding the index.
vs = main.rerun(benchmark="NIFTY") # the same run, compared with holding NIFTY 50
print(f"Strategy return : {vs.metrics['total_return']:.2%}")
print(f"NIFTY return : {vs.metrics['benchmark_total_return']:.2%}")
Strategy return : 50.81%
NIFTY return : 81.43%
Holding NIFTY 50 returned 81.43 percent over the same dates, about 10.64 percent a year. The strategy spent long periods in cash, and the engine notes that 24 trades are too few to judge overfitting. These are exactly the questions the rest of this series takes up.
What you learned
- The OpenAlgo Python SDK combines the API, 128 indicators and an event-driven backtester whose strategy classes can also run live.
- Orders are decided at a bar’s close and filled at the next bar’s open by default, so there is no look-ahead.
ta.supertrendreturns the line and a direction where -1 means uptrend.self.buy(),bt.size.value(...),bt.size.percent(...)andbt.size.qty(...)give very different risk on the same signals.
In Part 2, I will build richer signals with OpenAlgo indicators.
Full working code
Install the SDK with pip install -U openalgo plotly kaleido, set the OPENALGO_API_KEY environment variable, and have your OpenAlgo server running; then save this file as supertrend_backtest.py and run it.
# Backtesting using OpenAlgo Python SDK, Part 1: Supertrend on SBIN with position sizing
# Data comes from Historify (source="db") on your own OpenAlgo server. No orders are placed.
import warnings
import pandas as pd
import plotly.graph_objects as go
# --- block: connect ---
import os # to read the API key from an environment variable
import openalgo.backtest as bt # the SDK's backtesting engine
from openalgo import api, ta # api talks to your OpenAlgo server, ta has the indicators
# Connect to your own OpenAlgo server (replace your_api_key with the key from its API Key page)
client = api(api_key=os.getenv("OPENALGO_API_KEY", "your_api_key"), host="http://127.0.0.1:5000")
SYMBOL, EXCHANGE = "SBIN", "NSE" # the stock and its exchange
START, END = "2021-01-01", "2026-11-23" # test period; 23 Nov 2026 is the latest completed daily bar
CAPITAL = 100_000 # starting capital, Rs 1,00,000
# Daily bars from Historify; change to source="api" to read your broker's history instead
df = client.history(symbol=SYMBOL, exchange=EXCHANGE, interval="D",
start_date="2020-06-01", end_date=END, source="db")
print(df.tail(3)) # the last three rows, to check the data is current
# --- end ---
warnings.filterwarnings("ignore", category=UserWarning) # tidy console; result.warnings still keeps them
# --- block: supertrend ---
# ta.supertrend returns two series: the line itself and its direction
# direction is -1 in an uptrend and 1 in a downtrend
df["st"], df["st_dir"] = ta.supertrend(df["high"], df["low"], df["close"],
period=10, multiplier=3.0)
# A flip is any day the direction changes from the day before
flips = (df["st_dir"].diff() != 0) & df["st_dir"].shift().notna()
print("Trend flips since 2021:", int(flips.loc[START:].sum()))
# --- end ---
# --- block: strategy ---
class SupertrendAllEquity(bt.Strategy):
symbol, exchange, interval = SYMBOL, EXCHANGE, "D" # SBIN on NSE, daily bars
period = 10 # ATR period of the Supertrend
multiplier = 3 # how many ATRs away the line sits
def init(self):
# Runs once before the first bar. self.I registers the indicator with the engine,
# so each bar sees only values known at that bar.
self.line, self.direction = self.I(
ta.supertrend, self.high, self.low, self.close, self.period, self.multiplier
)
def enter(self):
self.buy() # default sizing: whole shares for about 98% of current equity
def on_bar(self, bar):
# Runs at the close of every daily bar
uptrend = self.direction[-1] < 0 # [-1] is today's value; -1 means uptrend
if self.position.is_flat and uptrend: # no shares held and the trend is up
self.enter() # buy; fills at the next bar's open
elif self.position.is_long and not uptrend: # holding shares and the trend flipped down
self.exit() # sell everything at the next bar's open
# --- end ---
# --- block: sizing ---
class SupertrendFixed50k(SupertrendAllEquity):
def enter(self):
self.buy(size=bt.size.value(50_000)) # a fixed Rs 50,000 per trade
class SupertrendHalfEquity(SupertrendAllEquity):
def enter(self):
self.buy(size=bt.size.percent(50)) # 50% of current equity per trade
class SupertrendFixedShares(SupertrendAllEquity):
def enter(self):
self.buy(size=bt.size.qty(80)) # a fixed 80 shares per trade
variants = {
"All equity (default buy)": SupertrendAllEquity,
"Fixed Rs 50,000 per trade": SupertrendFixed50k,
"50% of equity per trade": SupertrendHalfEquity,
"Fixed 80 shares per trade": SupertrendFixedShares,
}
results = {}
for name, strategy in variants.items():
# Same rules, dates, capital and data source; only the sizing differs
results[name] = bt.backtest(strategy, client, start=START, end=END,
capital=CAPITAL, source="db")
# --- end ---
# --- block: summary ---
main = results["All equity (default buy)"] # the featured run
print(main.summary()) # net profit, return, drawdown and trades
m = main.metrics # a dictionary of 100+ figures
print(f"CAGR : {m['cagr']:.2%}") # growth rate per year
print(f"Win rate : {m['win_rate']:.2%}") # share of closed trades that made money
print(f"Profit factor : {m['profit_factor']:.2f}") # rupees won per rupee lost
print(f"Charges : Rs {m['total_costs']:,.2f}") # brokerage, taxes and fees paid
# --- end ---
# --- block: open trade ---
trades = main.trade_list() # one row per closed trade
realised = trades["net_pnl"].sum() # profit locked in by closed trades
net = main.equity["equity_rupees"].iloc[-1] - CAPITAL # final account value minus capital
print(f"Realised (closed trades) : Rs {realised:,.2f}")
print(f"Open trade, mark to last close (after its entry charges): Rs {net - realised:,.2f}")
print(main.final_positions[["symbol", "quantity_units", "unrealized_rupees"]].to_string(index=False))
# --- end ---
# --- block: table ---
rows = []
for name, result in results.items():
mm, tl = result.metrics, result.trade_list()
rows.append({
"Sizing": name,
"Net P&L (Rs)": round(mm["net_profit"], 2),
"CAGR %": round(mm["cagr"] * 100, 2),
"Max DD %": round(mm["max_drawdown"] * 100, 2),
"Avg trade (Rs)": round(tl["net_pnl"].mean(), 2),
"Worst trade (Rs)": round(tl["net_pnl"].min(), 2),
"Profit factor": round(mm["profit_factor"], 2),
})
print(pd.DataFrame(rows).set_index("Sizing").to_string())
# --- end ---
# --- block: benchmark ---
vs = main.rerun(benchmark="NIFTY") # the same run, compared with holding NIFTY 50
print(f"Strategy return : {vs.metrics['total_return']:.2%}")
print(f"NIFTY return : {vs.metrics['benchmark_total_return']:.2%}")
# --- end ---
# Extra detail for the record (full metrics, best trade, average buy, charges, open P&L)
for name, result in results.items():
tl = result.trade_list()
mm = result.metrics
realised = tl["net_pnl"].sum()
net = result.equity["equity_rupees"].iloc[-1] - CAPITAL
n_open = int(getattr(result, "open_trades", 0) or 0)
if hasattr(result, "final_positions") and result.final_positions is not None and len(result.final_positions):
n_open = int((result.final_positions["quantity_units"] != 0).sum())
skips = getattr(result, "skips", None)
n_skips = len(skips) if skips is not None else "n/a"
print(name,
"| net", round(mm["net_profit"], 2),
"| return", f"{mm['total_return']:.2%}",
"| cagr", f"{mm['cagr']:.2%}",
"| maxdd", f"{mm['max_drawdown']:.2%}",
"| win", f"{mm['win_rate']:.2%}",
"| pf", round(mm["profit_factor"], 2),
"| charges", round(mm["total_costs"], 2),
"| closed", len(tl),
"| open_pos", n_open,
"| realised", round(realised, 2),
"| open_unreal_after_entry_charges", round(net - realised, 2),
"| best", round(tl["net_pnl"].max(), 2),
"| worst", round(tl["net_pnl"].min(), 2),
"| avg trade", round(tl["net_pnl"].mean(), 2),
"| avg buy", round((tl["quantity"] * tl["entry_price"]).mean(), 0),
"| skips", n_skips)
if n_open and hasattr(result, "final_positions"):
print(result.final_positions[["symbol", "quantity_units", "unrealized_rupees"]].to_string(index=False))
# Charts (light editorial theme, small openalgo.in mark)
def mark(fig):
fig.add_annotation(text="openalgo.in", xref="paper", yref="paper", x=0.995, y=0.005,
xanchor="right", yanchor="bottom", showarrow=False,
font=dict(size=11, color="rgba(90,90,90,0.55)"))
def style(fig, title, ytitle):
fig.update_layout(template="plotly_white", title=dict(text=title, font=dict(size=20)),
yaxis_title=ytitle, font=dict(family="Georgia, serif", size=13, color="#222"),
legend=dict(orientation="h", y=1.02, x=0, yanchor="bottom"),
margin=dict(l=70, r=30, t=95, b=50), width=1400, height=760,
paper_bgcolor="#fbfaf7", plot_bgcolor="#fbfaf7")
mark(fig)
p = df.loc[START:END].copy()
up = p["st"].where(p["st_dir"] < 0)
dn = p["st"].where(p["st_dir"] > 0)
fig = go.Figure()
fig.add_trace(go.Scatter(x=p.index, y=p["close"], name="SBIN close", line=dict(color="#263238", width=1.4)))
fig.add_trace(go.Scatter(x=p.index, y=up, name="Supertrend (up)", line=dict(color="#2e7d32", width=1.8)))
fig.add_trace(go.Scatter(x=p.index, y=dn, name="Supertrend (down)", line=dict(color="#c62828", width=1.8)))
et = trades["entry_time"].dt.tz_localize(None).dt.normalize()
xt = trades["exit_time"].dt.tz_localize(None).dt.normalize()
fig.add_trace(go.Scatter(x=et, y=trades["entry_price"], mode="markers", name="Buy (next open)",
marker=dict(symbol="triangle-up", size=12, color="#2e7d32", line=dict(width=1, color="white"))))
fig.add_trace(go.Scatter(x=xt, y=trades["exit_price"], mode="markers", name="Exit (next open)",
marker=dict(symbol="triangle-down", size=12, color="#c62828", line=dict(width=1, color="white"))))
style(fig, "SBIN daily with Supertrend (10, 3) and backtest fills, 2021 to 2026", "Price (Rs)")
fig.write_image("price_supertrend_signals.png")
colors = {
"All equity (default buy)": "#1565c0",
"Fixed Rs 50,000 per trade": "#ef6c00",
"50% of equity per trade": "#6a1b9a",
"Fixed 80 shares per trade": "#00838f",
}
fig2 = go.Figure()
for name, res in results.items():
eq = res.equity["equity_rupees"]
fig2.add_trace(go.Scatter(x=eq.index, y=eq, name=name, line=dict(color=colors[name], width=2)))
fig2.add_hline(y=CAPITAL, line=dict(color="#9e9e9e", dash="dot"))
style(fig2, "Equity curves: same Supertrend rules, four position sizes (after charges)", "Account value (Rs)")
fig2.write_image("equity_by_sizing.png")
Learn by watching: free videos every week
Market Profile, order flow, Python, AI and OpenAlgo tutorials on YouTube.

