CSCheatsheets
Open Varsity · Expert

Quantitative Trading

The 78-chapter professional course: market structure and costs, statistics and multiple testing, microstructure, execution tech and kill switches, ARIMA, GARCH, OU and cointegration, Black-76, Greeks, VIX and VRP, alpha families, honest backtesting, ML, portfolio risk and production.

11sections
94cards
9diagrams
0%known

00Quantitative trading: atlas and routes

A professional 78-chapter course on one page: careers and Indian market structure, the maths, microstructure, execution technology, time series, derivatives, alpha research, honest backtesting and ML, and running a live system. Condensed from OpenAlgo's free Open Varsity course. Educational, not investment advice.

How to use this sheet#

  1. Trading your own money systematically: Module A costs, Module B multiple testing, Module H backtesting, then Module I production.
  2. Options and volatility: Module F end to end, with Module E's GARCH and realised-volatility cards.
  3. Building execution or market-making code: Modules C and D.
  4. Interviewing for a quant role: Modules A, B and the career card in Module I.
  5. Five ladders help with live decisions: market or limit order, the risk gate, whether a spread is tradable, fade or follow, and whether a backtest is honest.
Educational, not investment advice. Condensed in our own words from OpenAlgo Open Varsity: Quantitative Trading. Figures are the course's mid-2026 runs; regulatory numbers change, so verify current circulars.

Ten numbers worth remembering#

LessonNumber
NIFTY days beyond 4σ: normal vs actual0.18 vs 16
Chance of ≥ 1 false hit in 20 tests≈ 64%
Delivery round trip, all-in cost≈ 0.22%
Retail API median round trip≈ 500 ms (HFT ≈ 0.01 ms)
Look-ahead bug: equity with vs without25.2× vs 1.07×
Square-root law: double the sizeimpact × 1.4
NIFTY GARCH persistence α + β≈ 0.975
India VIX vs later realised (1 year)+1.9 vol points
NIFTY future leverage at exchange margin≈ 8.8×
Capstone Sharpe: in-sample vs out-of-sample0.87 vs 0.23
Check yourself 2 questions
  1. Testing 20 ideas at 5% significance, what's the chance of at least one false hit?

    Show answer

    About 64%.

  2. How many NIFTY days beyond 4 sigma does a normal distribution expect, and how many happened?

    Show answer

    About 0.2 expected, 16 observed.

Takeaway Fat tails, false discoveries, real costs, retail latency and look-ahead bugs: ten numbers that keep quant work honest.

01Module A · Quant careers and Indian market structure

OpenAlgo Open Varsity · Quantitative Trading · chapters 1–8 (what a quant does, roles, firms, market map, participants, plumbing, clearing and settlement, cost of a trade)

What a quant does: measure, then test for luck#

  • A quant measures before trusting a feeling, then asks whether the measurement is skill or luck. "A discretionary trader feels the trend; a quant counts it."
  • Research loop: hunch → falsifiable hypothesis → data → test → edge? Most ideas die here, and that is the filter working.
  • Toolkit: market structure, mathematics, code, and scepticism (assume the backtest is wrong until proven otherwise).
NIFTY, 247 trading daysValue
Up / down days128 (51.8%) / 119
Average up / down day+0.58% / −0.65%
Best / worst day+3.78% / −3.26%
Excess kurtosis≈ 2.55 (normal = 0): fat tails

Direction is close to a coin flip; any edge hides in the shape of the moves. Never assume returns are normal.

Check yourself 2 questions
  1. What's the research loop?

    Show answer

    Hunch, falsifiable hypothesis, data, test, then decide whether there's an edge.

  2. Is it bad that most ideas die?

    Show answer

    No. That's the filter working.

Takeaway A quant measures before trusting a feeling, then tests whether the result is skill or luck; most ideas should die in research.

Researcher, developer, trader#

RoleDeliversNeeds
ResearcherA signal, backed by evidenceStatistics, scepticism
DeveloperA live system: data, gateway, state, logging, recoverySystems thinking
TraderLive risk, sizing, capital and P&LRisk temperament
  • "The researcher finds the edge, the developer makes it run, the trader makes it pay." Fills, slippage and switch-off days flow back into research: a loop, not a relay.
  • Honest read of an edge: NIFTY 20/100 SMA cross, 2,744 test days: next-day hit rate 54.47% vs 53.94% baseline, and the same average return as just holding. At 10 bps a round trip over 14 round trips: gross 2.10×, net 2.07×, against 2.90× for buy-and-hold. Its real value was dodging the 2020 and 2022 falls.
  • "Survives costs", "beats buy-and-hold" and "risk-adjusted alpha" are three different questions.
Check yourself 2 questions
  1. What does the developer deliver?

    Show answer

    A live system: data, gateway, state, logging and recovery.

  2. Which role needs risk temperament most?

    Show answer

    The trader.

Takeaway The researcher finds the edge, the developer builds the live system, the trader runs the risk.

Four business models share one order book#

FirmEarns fromOptimisesHorizon
Buy-side (AMC, PMS, AIF Cat III, hedge fund)Fees on AUM, sometimes performanceRisk-adjusted return at capacity; low turnoverWeeks to years
Sell-side (banks, brokers)Commission and spread on flowExecution quality, inventory, fill rateIntraday to days
PropIts own P&L: keeps 100% of profit and lossNet edge after costsOften intraday
HFTSpread capture, microsecond arbitrageLatency, microstructureMicroseconds to seconds
  • "The revenue model is the master variable": it sets incentives, research priorities and holding period. India's ladder: mutual funds (long-only, most regulated) → PMS (SEBI minimum ticket ₹50 lakh) → AIF Category III (can short and lever within limits).
  • Turnover fingerprint = position changes per year. NIFTY, 5.4 years: daily-direction flipping ≈ 113 flips a year, a 20/100 SMA trend ≈ 3, buy-and-hold 0. Cost exposure scales with flips: if edge per trade is below cost per trade, more volume loses money faster.
  • Six large caps together trade ≈ ₹9,800 crore a day (average close × volume over 250 days). A retail quant can't win the latency game, but medium-horizon systematic trading (days to weeks) is open, and small size dodges the capacity limits big AMCs face.
Check yourself 2 questions
  1. How does the buy-side earn?

    Show answer

    Fees on assets under management, sometimes performance fees.

  2. What does a sell-side desk optimise?

    Show answer

    Execution quality, inventory and fill rate.

Takeaway Buy-side, sell-side, prop and market makers earn differently and optimise different things, yet trade in the same book.

The map: indices, exchanges and codes#

VenueSegments (OpenAlgo codes)
NSECash NSE, derivatives NFO, currency CDS, indices NSE_INDEX
BSECash BSE, derivatives BFO, indices BSE_INDEX
MCXCommodities MCX
  • Benchmarks: Nifty 50, Bank Nifty (heavy weight; the market often follows it), FinNifty, Nifty IT, Sensex (30 stocks), and India VIX, which moves against the market.
  • "The market" is a convenient fiction. Over one year: Nifty −4.1%, Bank Nifty +3.0%, Nifty IT −28.2%. Name the index, and look for edges in the gaps between sectors.
Check yourself 2 questions
  1. OpenAlgo code for NSE derivatives?

    Show answer

    NFO.

  2. Which index does the market often follow?

    Show answer

    Bank Nifty.

Takeaway NSE (NSE, NFO, CDS), BSE (BSE, BFO) and MCX; Bank Nifty often leads the market.

Who moves prices#

ParticipantTypical role
RetailMany small tickets, heavy in options and intraday; mostly uninformed
HNIs, prop desksLarger, leveraged; between noise and signal
FPIsLarge, trend-setting; weeks of net buying or selling move the index
DIIs (funds, insurers)Often absorb FPI selling: the quarter's tug of war
Market makersQuote both sides, earn the spread, end flat
  • Every fill pairs a provider (resting order, earns the spread) with a taker (crosses it, pays). Being filled by someone who knows more is adverse selection.
  • India publishes no participant-tagged ticks; FPI/DII figures, client-category turnover, OI, delivery % and bulk deals are proxies, so triangulate.
  • India VIX vs NIFTY: correlation −0.73; a −1% day lifts VIX ≈ 0.9 points, and fear rises faster than it falls. A volume spike (> 2× the 20-day median) says someone big was active, not who or which way.
Check yourself 2 questions
  1. Which participants set multi-week trends?

    Show answer

    FPIs.

  2. Who often absorbs FPI selling?

    Show answer

    DIIs: funds and insurers.

Takeaway Retail is many small, mostly uninformed tickets; FPIs set trends over weeks; DIIs often absorb FPI selling.

Plumbing: who does what#

InstitutionJob
SEBIWrites rules, licenses, surveils
Exchanges (NSE, BSE)Match orders, discover price; never hold your money
Clearing corps (NSE Clearing, ICCL)Guarantee trades by novation
Depositories (NSDL, CDSL)Hold shares in demat
flowchart TD
  O["Order placed"] --> M["Exchange matches it"]
  M --> N["Clearing corp steps in: novation"]
  N --> T["T+1 pay-in and pay-out"]
  T --> D["Shares in demat, cash in bank"]

An intraday position never settles; a delivery holding does. Same symbol, different risk, cost and funding: handle them separately in code.

Check yourself 2 questions
  1. Do exchanges hold your money?

    Show answer

    No. They match orders and discover price.

  2. Who guarantees trades?

    Show answer

    The clearing corporations, by novation.

Takeaway SEBI regulates, exchanges match, clearing corporations guarantee by novation, depositories hold shares.

Clearing, netting and settlement#

  • Novation: the clearing corp becomes buyer to every seller and seller to every buyer, so anonymous traders never face each other's credit.
  • Multilateral netting: 25 RELIANCE trades worth ₹33.0 lakh gross net to one obligation: deliver 300 shares, receive ₹3.94 lakh, 11.9% of gross.
  • T+1 counts exchange business days (Fri 26 Jun 2026 → Mon 29 Jun); fully in force since January 2023. Optional T+0 runs for a pilot list that keeps changing: check the current circular.
  • A failed short delivery goes to an exchange auction at the defaulter's cost; settlement must complete before a record date to get a dividend or bonus.
  1. Defaulter's own margin and collateral
  2. Settlement Guarantee Fund
  3. Clearing corp's own capital
  4. Non-defaulting members' funds, last

That default waterfall is why margin is locked capital, not a fee.

Check yourself 2 questions
  1. 25 trades worth ₹33 lakh gross netted to what share?

    Show answer

    About 12% of gross.

  2. What is novation?

    Show answer

    The clearing corporation becoming the counterparty to both sides.

Takeaway Novation removes counterparty credit risk; multilateral netting shrinks many trades to one obligation.

The true cost of a trade#

ChargeDeliveryIntradayFuturesOptions
Brokerage₹0₹20 an order or 0.03%, whichever is lower
STT0.1% buy and sell0.025% sell0.05%0.15% on premium sold
Exchange0.00307%0.00307%0.00183%0.03553%
Stamp duty (buy only)0.015%0.003%0.002%0.003%
SEBI · GST₹10 a crore · 18% on brokerage + exchange + SEBI only (not STT or stamp)
All-in, 500 units round trip₹1,112 (₹1,000 stock, ≈ 0.22%)₹225₹330₹166 (₹100 premium)
  • Delivery example, ₹10 lakh turnover: STT ₹1,000, exchange ₹30.70, stamp ₹75, GST ₹5.71, SEBI ₹1 → ₹1,112.41; breakeven ₹2.22 a share. STT dominates almost every segment.
  • Frequency trap: 0.22% × 100 round trips a year ≈ 22% annual drag, enough to erase a 15% gross edge. Net edge = gross edge − costs; an edge that only exists before costs is not an edge.
  • Rates as stated in the course; SEBI and the exchanges revise them, so verify current circulars.

Main card for the charges stack. Also covered in Stock basics · Futures · Options basics · Options basics · Taxation.

Check yourself 2 questions
  1. Delivery STT rate?

    Show answer

    0.1% on both buy and sell.

  2. Which side pays stamp duty?

    Show answer

    The buy side only.

Takeaway STT dominates most cost stacks: 0.1% both sides on delivery, 0.025% sell on intraday, 0.15% of premium sold on options.

02Module B · Maths, statistics and research foundations

OpenAlgo Open Varsity · Quantitative Trading · chapters 9–16 (returns, probability, fat tails, inference, multiple testing, stationarity and EMH, linear algebra and PCA, optimisation)

Simple vs log returns#

simple r = P_t / P_(t−1) − 1 for people ("up 2%")log r = ln(P_t / P_(t−1)) for maths across timeΣ log r = ln(P_end / P_start) exactlyΠ(1 + simple r) − 1 the right way to chain simple returns

NIFTY, one year: summed log returns −0.04169 (exact); summed simple returns −0.03324 (wrong); compounded simple −0.04084 (right). They agree for small moves and drift apart for big ones. Know which one you are holding.

Check yourself 2 questions
  1. What do summed log returns equal?

    Show answer

    ln(P_end / P_start), exactly.

  2. How do you correctly chain simple returns?

    Show answer

    Π(1 + r) − 1.

Takeaway Simple returns are for people; log returns add exactly across time; chain simple returns by multiplying.

Four stylised facts#

FactNIFTY daily since 2021
Fat tailsExcess kurtosis 3.70 (normal = 0)
Volatility clustersCalm and violent stretches come in runs
Returns have no memoryAutocorrelation ≈ 0 at every lag
Size has memory|return| autocorrelation 0.24 at lag 1, decaying slowly

So: you can't reliably predict direction, but you can predict size. Durable strategies target risk. The leverage effect adds that volatility rises more after a fall than after an equal rise, so risk models must be asymmetric.

Check yourself 2 questions
  1. Do daily returns have autocorrelation?

    Show answer

    About zero at every lag.

  2. What does have memory?

    Show answer

    The size of returns (absolute returns), which decays slowly.

Takeaway Fat tails, volatility clustering, no memory in returns, but memory in their size.

Expectation, variance and the footprint of luck#

E = win rate × avg win + (1 − win rate) × avg lossNIFTY, 730 days: 0.508 × 0.61% + 0.492 × (−0.62%) ≈ +0.008% a day
  • Expectation is the edge per bet and must be positive after costs; variance is the quality of the ride. Report both: same expectancy with a smoother path is the better strategy.
  • The law of large numbers only bites over many trades. A handful of winners proves nothing.
  • Monte Carlo: resample real NIFTY daily returns into 500 alternate years (seed fixed): growth of 100 ends at median 111, 5th percentile 87, 95th percentile 138. Same edge, very different lives. Use it for path questions with no clean formula: drawdowns, stops, risk of ruin.
Check yourself 2 questions
  1. Expectation formula?

    Show answer

    Win rate × average win + (1 − win rate) × average loss.

  2. Two strategies with the same expectancy: which is better?

    Show answer

    The one with the smoother path (lower variance).

Takeaway Expectation is the edge per bet and must be positive after costs; variance is the quality of the ride.

Fat tails in numbers#

NIFTY daily since 2015 (2,843 days)Value
σ (typical daily move)1.03%
Days beyond 4σ: normal expects / observed0.18 / 16 (≈ 89×)
Worst day−13.9% (Mar 2020), beyond 13σ
Skew / excess kurtosis−1.31 / 19.6
Fitted Student-t ν≈ 3.7 (variance finite above 2, kurtosis above 4)
  • A normal curve says 3σ once in ≈ 740 days and 4σ once in ≈ 16,000. "Markets take the stairs up and the elevator down." Equity tails follow a power law with index ≈ 3.
  • Size to the worst day in your data and assume a worse one is coming; use half-Kelly or less; scale down when realised volatility rises; hedge the downside. Sample kurtosis is unstable: the next crash revises it upward.
  • Selling naked options for small frequent premiums is exactly the trade fat tails punish.
Check yourself 2 questions
  1. What distribution fits NIFTY returns better than normal?

    Show answer

    A Student-t with about 3.7 degrees of freedom.

  2. Worst NIFTY day since 2015?

    Show answer

    About −13.9% in March 2020.

Takeaway NIFTY's tails are far fatter than normal: 16 days beyond 4 sigma against 0.2 expected; the worst day was beyond 13 sigma.

Hypothesis tests and what p-values mean#

  • Every Sharpe, mean or win rate is an estimate: truth plus luck. Seven heads in ten flips doesn't prove a 70% coin.
  • Null (H0): no edge. p-value: how surprising the result would be if H0 were true. It is not the chance the strategy works, and p < 0.05 is not "95% sure".
  • 1,000 random long/short NIFTY strategies (no edge by construction): mean Sharpe ≈ 0, best +1.36, worst −1.32, and 10 cleared Sharpe 1.0 by chance. The more you try, the more extreme the best one looks.
  • Defences: test once on unseen data; count every try and raise the bar with it; demand an economic reason (risk premium, structural quirk, behavioural bias); prefer fewer, deeper hypotheses.

"The goal of inference isn't to find a winner; it's to avoid being fooled by one."

Check yourself 2 questions
  1. Does p < 0.05 mean 95% sure the strategy works?

    Show answer

    No. It's how surprising the result is under no edge.

  2. What's the null hypothesis for a strategy?

    Show answer

    No edge.

Takeaway A p-value is how surprising the result would be if there were no edge; it isn't the chance the strategy works.

Stationarity, random walks and the EMH#

NIFTY since 2021ADF statpVerdict
Price−1.490.538Non-stationary (random walk)
Daily returns−18.300.000Stationary
  • A random walk is today plus an unpredictable shock: no anchor. Model returns, not price levels; a price-level model breaks when price wanders somewhere new.
  • ADF's null is "unit root". p < 0.05 rejects it; a high p-value does not prove stationarity (statsmodels.tsa.stattools.adfuller).
  • EMH: weak (past prices useless), semi-strong (public news priced in), strong (private too). Cracks: momentum, value and low-vol anomalies, predictable risk, behavioural biases, structural flows (rebalancing, expiry).

Efficient enough that easy edges vanish, not so efficient that none remain.

Check yourself 2 questions
  1. ADF on NIFTY price versus returns?

    Show answer

    Price non-stationary (p about 0.5); returns stationary (p about 0).

  2. Why not model price levels?

    Show answer

    Price wanders with no anchor, so level models break.

Takeaway Prices are random walks, returns are stationary; model returns, not price levels.

Covariance and PCA: the hidden factors#

portfolio return = R @ w portfolio variance = w′ C wcorrelation = cov / (σ₁ σ₂)
  • Eigenvectors of the covariance matrix are uncorrelated risk axes; eigenvalues are the variance along each.
  • Eight Nifty stocks: PC1 explains 41.6% with all-positive loadings (the market), PC2 22.7% is long IT, short banks: a sector found without labels. Mean pairwise correlation 0.31; INFY–TCS 0.78.
  • A long single-stock book is mostly a leveraged Nifty bet; hedging the market factor with index futures is the cheapest risk cut.
  • Structure drifts (PC1 can pass 60% in crashes) and covariance is noisy: use rolling windows and shrinkage, and treat factor labels as interpretations.
Check yourself 2 questions
  1. Portfolio variance formula?

    Show answer

    w′Cw.

  2. What did PC1 represent for eight Nifty stocks?

    Show answer

    The market: all-positive loadings, about 42% of variance.

Takeaway PCA turns a covariance matrix into uncorrelated risk axes; the first is usually the market.

Optimisation: convex is trustworthy#

  • Most quant models are "find the inputs that make one number best". Convex problems have one bowl, so any minimum is the global one; portfolio variance w′Σw is convex.
  • Constraints define the feasible region: weights sum to 1 (equality), long-only and caps (inequalities). A binding constraint costs objective value. Mean-variance is a convex quadratic program.
  • Five stocks, minimum variance: weights 14 / 25 / 17 / 35 / 9%, volatility 13.33% vs 13.87% equal-weight; the closed form Σ⁻¹1 / (1′Σ⁻¹1) matches when no constraint binds.
  • Expected returns are the most fragile input; minimum variance ignores them and is sturdier.
  • Ill-conditioned covariance (near-duplicate assets, too few days) gives huge unstable weights: shrink (Ledoit–Wolf), clean eigenvalues, add a ridge, never invert a rank-deficient matrix. If weights lurch on tiny data changes, fix the inputs, not the solver.
Check yourself 2 questions
  1. Why are convex problems trustworthy?

    Show answer

    Any minimum found is the global minimum.

  2. Give an equality constraint in portfolio optimisation.

    Show answer

    Weights sum to 1.

Takeaway Convex problems have one bowl, so any minimum is global; portfolio variance is convex.

03Module C · Indian market microstructure

OpenAlgo Open Varsity · Quantitative Trading · chapters 17–28 (why it matters, order book, order types, queue priority, trading day, auctions, circuit breakers, bulk and block deals, liquidity, impact and TCA, order flow, short selling and SLB)

The spread is the price of liquidity#

  • A chart shows past last-traded prices, not a price you can trade at. Microstructure is how orders become trades, and what that costs.
  • Measure costs in basis points (1 bp = 0.01%) so they compare across price levels. A spread can never be tighter than one tick.
  • MCX crude, a wide snapshot: spread ≈ ₹6 on ≈ ₹6,570 (other cards here use calmer ₹1–2 books; spreads change minute to minute) ≈ 9.1 bps, so a market-in, market-out round trip costs ≈ ₹91 per ₹1 lakh; ten a day ≈ ₹900–1,000 per lakh before any move.
  • RELIANCE spread proxy through one day: open ≈ 12.2 bps, midday ≈ 5.6, close ≈ 6.4. The U-shape means the open is often the most expensive minute.
  • A strategy netting 2 bps a trade is dead against a 9 bps spread. Backtests on mid or close prices promise edges live markets don't pay.
Check yourself 2 questions
  1. What is 1 basis point?

    Show answer

    0.01%.

  2. What's the minimum possible spread?

    Show answer

    One tick.

Takeaway Charts show past trades; the spread is what you pay to trade now, and it can't be tighter than one tick.

The limit order book#

  • Bids rest below, asks above; nothing trades in the gap until someone crosses it. The next price comes from the book, not the last trade.
  • Crude example: best bid 6820 (2 lots), best ask 6822 (11 lots): a market buy fills at 6822, a market sell at 6820, and the 2-point gap is paid instantly.
  • Matching is price-time priority: best price first, then first-come at the same price. A large order eats several levels.
  • Imbalance = total buy qty ÷ (buy + sell qty): one weak, fast-flipping clue, distorted by hidden (iceberg) size.
  • OpenAlgo depth() returns five levels plus total buy and sell quantity; MCX keeps a live book into the night.
Check yourself 2 questions
  1. Best bid 6820, best ask 6822: where does a market sell fill?

    Show answer

    6820.

  2. Where does the next price come from: the last trade or the book?

    Show answer

    The book.

Takeaway Bids rest below, asks above; a market buy fills at the best ask, and the next price comes from the book.

Order types and the order lifecycle#

TypeBehaviourCatch
MarketFills now at the best priceCertain fill, uncertain price; pays the spread
LimitRests; fills at your price or betterMay never fill
SL (stop-limit)On trigger becomes a limit orderCan be jumped in a gap and not fill
SL-MOn trigger becomes a market orderAlways fires, can fill far past the trigger
IOCFills what it can, cancels the restNever rests
GTTBroker holds a trigger for days, then sends an orderNo queue position while waiting
Iceberg / disclosed qtyShows one slice at a timeEach refreshed slice rejoins at the back
  • Every order trades fill certainty against price certainty while trying to leak little information. RELIANCE at 1318.10 (tick 0.05): limit buy 1314.15, stop trigger 1304.90 with limit 1304.40, target 1344.45 → risk 9.75, reward 30.30, 3.1 : 1.
  • Lifecycle: pending → open → partially filled → complete, or cancelled / rejected. A modify is a controlled resubmit and usually loses queue position. Slippage = fill price − intended price; reconcile every fill every session.
  • Every order maps to a PAN-verified Unique Client Code; SEBI's 4 Feb 2025 retail-algo circular adds registered algo IDs and key and static-IP controls. Products: MIS (intraday, auto squared off), NRML (F&O overnight), CNC (delivery).
Check yourself 2 questions
  1. What's the catch with a market order?

    Show answer

    Certain fill, uncertain price: you pay the spread.

  2. What's the catch with an SL (stop-limit) order?

    Show answer

    It can be jumped in a gap and not fill.

Takeaway Market orders fill now at uncertain prices; limits may never fill; stop-limits can be jumped in a gap.

Queue position is a perishable asset#

queue value per lot = (spread / 2) × lot sizecrude: 1 / 2 × 100 = ₹50 a lot · ₹250 on 5 lotstime to front = depth ahead ÷ rate of sells hitting the bid = 60 lots ÷ 15 a minute = 4.0 min
  • Probability of a full 5-lot fill within 5 minutes ≈ 89% (Poisson arrivals). Counting cancels ahead (≈ 1.2 per sell) the wait drops to ≈ 2.4 minutes: visible depth overstates the queue.
  • Changing price or raising quantity sends you to the back; cutting quantity usually keeps your place.
  • India is FIFO, so early small orders beat big late ones (pro-rata venues reward oversized quotes instead).
  • Passive fills earn half a spread but suffer adverse selection: you tend to be filled just before price moves against you.
Check yourself 2 questions
  1. Queue value per lot formula?

    Show answer

    (Spread ÷ 2) × lot size.

  2. 60 lots ahead, 15 lots a minute hitting the bid: time to front?

    Show answer

    4 minutes.

Takeaway Resting early in the queue earns about half the spread per lot; time to the front = depth ahead ÷ hit rate.

Market or limit order?#

You need to trade
1Must it fill now: a stop, or an exit before news?
yes
Market or SL-Maccept the spread and gap risk
no
2Is the spread wide compared with your edge per trade?
yes
Rest a limit orderjoin the queue early and don't reprice
no
3Is your size large against the displayed depth?
yes
Slice iticeberg, TWAP or VWAP child orders
no
Limit at the touchsaves half a spread at little risk
Check yourself 2 questions
  1. A stop exit before news: market or limit?

    Show answer

    Market or SL-M: accept the spread and gap risk.

  2. The spread is wide relative to your edge. What then?

    Show answer

    Rest a limit order early and don't reprice.

Takeaway Must fill now → market or SL-M; spread wide versus edge → rest a limit; size large versus depth → slice.

The Indian trading-day clock#

Window (IST)SessionDetail
09:00–09:15Pre-open call auctionOrders collected until ≈ 09:08; the equilibrium price becomes the 09:15 open
09:15–15:30Continuous tradingPrice-time priority; stocks without a closing auction trade to 15:30 and close on the 15:00–15:30 VWAP
09:15–15:15Continuous, F&O-eligible stocksFrom 3 Aug 2026
15:15–15:35Closing Auction Session (CAS)Reference = 15:00–15:15 VWAP; market and limit orders 15:20–15:25, then limit-only to a random end between 15:28 and 15:30; close = equilibrium price within ≈ ±3%, else the VWAP
15:10–15:40Equity derivativesF&O closing price stays a VWAP
From 7 Dec 2026Revised scheduleContinuous to 15:30; CAS 15:30–15:40, matching to 15:45, reference = 15:15–15:30 VWAP; derivatives to 15:45 (expiring index contracts stop 15:30)
15:50–16:00Post-closeTrades at the official close (the course also cites 15:40–16:00; check the circular)
09:00–17:00 · 09:00–≈ 23:30Currency (CDS) · commodities (MCX)Overnight risk keeps being priced after equities shut

The open and close are auction prints, not ordinary fills, and the last tick need not equal the official close. RELIANCE volume per minute averaged ≈ 331,000 shares at 09:15, ≈ 26,000 at noon and ≈ 56,000 at 15:29: schedule big executions near the open and close, not in the thin middle. NIFTY on 25 Jun 2026: open 24,125.85, high 24,261.60, low 24,039.00, close 24,052.95.

Main card on market hours and the closing auction: Stock basics → Also in this sheet.

Check yourself 2 questions
  1. What decides the 9:15 open?

    Show answer

    The pre-open call auction's equilibrium price.

  2. How is the close set for stocks without a closing auction?

    Show answer

    The 3:00–3:30 pm VWAP.

Takeaway Pre-open call auction 9:00–9:15, continuous trading 9:15 to 3:30 pm with price-time priority.

Auctions and tick size#

  • Continuous trading is a double auction that always leaves a gap between bids and asks. A call auction collects orders without matching, then picks the single price that maximises matched quantity, and everyone gets that uniform price.
  • The official close drives index values, fund NAVs and benchmark-tracking trades.
  • Tick size sets the minimum spread and a cost floor: RELIANCE 0.1, MRF 5.0 (a share over ₹1 lakh), MCX crude 1.0. Too small a tick fragments the book; too large forces a wide spread. Ticks are not equal in percentage terms.

Main card on market hours and the closing auction: Stock basics → Also in this sheet.

Check yourself 2 questions
  1. How does a call auction set its price?

    Show answer

    The single price that maximises matched quantity; everyone gets it.

  2. Why does tick size matter for costs?

    Show answer

    It sets the minimum spread.

Takeaway A call auction picks the price that maximises matched quantity; tick size sets the minimum spread and a cost floor.

Circuit breakers, bands and surveillance#

ControlRule
Index circuit breaker10% (45-minute halt), 15% (longer halt), 20% (rest of day), either direction; the whole market stops
Stock price bandUsually 2%, 5%, 10% or 20% a day, set per stock
ASM / GSM listsHigher margins, tighter bands or trade-for-trade settlement
F&O banOI above 95% of the market-wide limit: square-off only
  • 23 Mar 2020: NIFTY −12.98% tripped the 10% breaker; only one of 1,853 days since 2019 went beyond ±10%.
  • A stock locked at its lower circuit has zero liquidity, not thin liquidity: stops can't fill, high = low = close breaks range indicators, and a gap follows at the next open.
  • Track ASM, GSM and ban status by date in your universe; orders in banned names are rejected live.
Check yourself 2 questions
  1. What happens at a 20% index move?

    Show answer

    Trading halts for the rest of the day.

  2. What do ASM/GSM lists bring?

    Show answer

    Higher margins, tighter bands or trade-for-trade settlement.

Takeaway Index breakers at 10, 15 and 20% halt the market; stock bands of 2–20% cap daily moves; ASM/GSM lists tighten rules.

Bulk and block deals#

Bulk dealBlock deal
Defined byOne client > 0.5% of listed shares in a dayLarge pre-negotiated trade, minimum ≈ ₹10 crore
WhereNormal continuous marketSeparate windows: ≈ 08:45–09:00 (±1% of previous close) and ≈ 14:05–14:20 (tight band around 13:45–14:00 VWAP)
DisclosureIntraday or end of day≈ 30 minutes after the window

SBIN, 494 sessions: only 7 days had volume above 3× the 60-day median; the 5-day return after them averaged +0.66% vs +0.27% baseline. Seven cases is a lead, not a signal. Use a median baseline, confirm against the exchange's deal reports, and remember volume has no direction.

Check yourself 2 questions
  1. What defines a bulk deal?

    Show answer

    One client trading more than 0.5% of listed shares in a day.

  2. Minimum size of a block deal?

    Show answer

    About ₹10 crore.

Takeaway Bulk deals are big trades in the normal market; block deals are large pre-negotiated trades in special windows.

Liquidity: spread, depth and resilience#

StockAmihud (×1e9)Turnover ₹ cr/day
HDFCBANK0.00042,324
RELIANCE0.00051,894
INFY0.00091,461
TATASTEEL0.0025520
BANKBARODA0.0049270
YESBANK0.0062219
  • Liquidity has three faces: spread (cost to cross), depth (size before price moves) and resilience (how fast the book refills).
  • Buying 30 crude lots with 11 at the best ask walks the book to an average 6822.9: that 0.9 is impact. Kyle's λ is price move per unit of flow, the price of size; Amihud = mean |return| ÷ rupee turnover ranks illiquidity.
  • Spread and charges are fixed per trade; impact grows with size, so a 1-lot winner can be a 100-lot loser. Rough ceiling: a single order no bigger than daily turnover ÷ 100.
Check yourself 2 questions
  1. Name the three faces of liquidity.

    Show answer

    Spread, depth and resilience.

  2. Higher Amihud means more or less liquid?

    Show answer

    Less liquid.

Takeaway Liquidity has three faces: spread, depth and resilience; Amihud measures price impact per rupee traded.

Impact, slippage and TCA#

impact ≈ Y · σ · √(order / ADV) Y ≈ 0.5RELIANCE (σ 131 bps, ADV 18.2 mn): ₹10 lakh ≈ 0.4 bps · 5% of ADV ≈ 15 bpsdoubling size → impact × 1.4, not × 2
  • Temporary impact is the cost of hurry and fades: trade slower. Permanent impact is information leakage and stays: trade quieter.
  • Measure slippage against the arrival (decision) mid, not VWAP. Implementation shortfall compares the real portfolio with a paper one filled instantly at arrival: spread, impact, drift and the cost of unfilled quantity.
  • Book walk, 40 crude lots: average 6572.70 vs mid 6570 = 4.1 bps (1.5 half-spread + 2.6 walking). Five visible levels understate big-order impact: a walk is a floor.
  • NSE's impact cost (≤ 0.50% for a set basket value) is a Nifty 50 eligibility test. Report TCA net of all charges, and never drop the bad days.
Check yourself 2 questions
  1. Square-root impact formula?

    Show answer

    Impact ≈ Y · σ · √(order ÷ ADV).

  2. Temporary versus permanent impact: which fades?

    Show answer

    Temporary: the cost of hurry.

Takeaway Impact grows with the square root of size relative to volume; doubling size raises impact about 1.4×, not 2×.

Open interest, volume and order flow#

PriceOIRegime
UpUpLong build-up: fresh bulls
DownUpShort build-up: fresh bears
UpDownShort covering: weak rally
DownDownLong unwinding: weak fall
  • Volume is activity; OI is conviction. Informed flow carries a view; uninformed flow meets a need (rebalancing, paying a bill). Adverse selection is trading against the informed.
  • OI builds through the month and deflates near expiry as traders roll: in the NIFTY June future it fell from ≈ 17.8 mn to 15.4 mn in the final week, which is rollover, not lost conviction.
  • India publishes daily FII/FPI and DII cash flows and participant-wise index-futures OI. FII selling can be currency-driven; a huge print may be one leg of a spread. Flow describes a move's character; it is not a trigger.

Main card on price and open interest: Futures → Also in Options basics.

Check yourself 2 questions
  1. Price down, OI up?

    Show answer

    Short build-up: fresh bears.

  2. Informed versus uninformed flow?

    Show answer

    Informed flow carries a view; uninformed flow meets a need such as rebalancing.

Takeaway Volume is activity, OI is conviction; price and OI together give build-up, covering and unwinding.

Short selling, SLB and borrowing#

RouteBorrow?HoldingKey risk
Intraday shortNoSame sessionForced flat at the close
Delivery shortYes, via SLBOvernightFailed delivery → exchange auction at a penalty price
Synthetic (futures, options)NoTo expiryBasis and carry; F&O names only
annualised carry = ln(F / S) / TRELIANCE: spot 1,318.1, Jul future 1,323.6, 33 days → basis +5.5 (0.42%) ≈ +4.6% a year
  • Naked shorting is banned: every overnight cash short needs an arranged borrow. SLB is exchange-run with the clearing corp as counterparty; lenders keep dividends (passed through) and can recall.
  • Borrow fees float: near zero for easy large caps, double-digit annualised for hard-to-borrow names, or nothing at any price. Total short cost = fee + dividends passed on + financing drag.
  • Contango (future above spot) pays a futures short as it converges; backwardation costs it.
  • Short losses are unbounded; squeezes feed on forced covering just as lenders recall. Size for the tail, keep a hard stop and a recall plan. Borrow availability caps what a market-neutral book can hold.
Check yourself 2 questions
  1. What happens if a delivery short isn't borrowed?

    Show answer

    Failed delivery: an exchange auction at a penalty price.

  2. How do you short a non-F&O stock overnight?

    Show answer

    Borrow through SLB.

Takeaway Intraday shorts need no borrow but must close; delivery shorts need SLB; synthetic shorts use F&O.

04Module D · HFT, execution and trading technology

OpenAlgo Open Varsity · Quantitative Trading · chapters 29–40 (algo foundations, HFT vs algo vs systematic, DMA and latency, data feeds, book reconstruction, HFT families, order-to-trade ratio, smart order routing, execution algorithms, market making, retail API framework, kill switches)

The algo loop#

  1. Data → signal → sizing → order → risk, then repeat each bar or poll.
  2. Keep stages separate and testable: the signal never knows account size; sizing never knows the broker.
  3. "The signal proposes; risk disposes."
  • Polling (on a timer) is simple and fits minute-to-day edges; event-driven (each tick) is fast but brings reconnects, bursts and out-of-order messages. Pick the slowest clock your edge tolerates.
  • A bot is a state machine (flat, long, short): act only when the desired state changes, make orders idempotent so a retry can't double up, and treat the broker's book as the source of truth.
  • Sizing example: qty = min(₹1,00,000 ÷ price, 60): at ₹1,321.8 the budget allows 75 but risk caps it at 60. A 9/21 EMA cross on 1-minute RELIANCE made 21 decisions in one day: costs would eat it.
  • OpenAlgo's analyzer runs the identical code path without sending orders; go live by flipping a setting after a clean sandbox session, not by rewriting.
Check yourself 2 questions
  1. Should the signal know account size?

    Show answer

    No; sizing is a separate stage.

  2. When is polling enough?

    Show answer

    For minute-to-day edges.

Takeaway Data, signal, sizing, order, risk: separate testable stages; the signal proposes, risk disposes.

Algo, systematic and HFT are different questions#

HFTIntraday algoSystematic
Latency that mattersMicrosecondsTens of msIrrelevant
Holding periodms to secondsMinutes to hoursDays to months
Trades a dayTens of thousandsTensA fraction
KitColocation, tick feed, FPGAsCloud server, fast APILaptop, daily data
EdgeBeing firstShort-term signalResearch depth, patience
  • Algo = no human placing orders; systematic = pre-defined testable rules (the opposite of discretionary); HFT = a speed-defined subset of algo.
  • NIFTY: median 1-minute move 1.4 bps vs 0.50% a day (daily ≈ 36× minute; a pure random walk would give √375 ≈ 19×, and medians of a fat-tailed series don't scale cleanly). A 9/21 EMA fires ≈ 16 times a day on 1-minute bars (≈ 23-minute holds) vs once in ≈ 23 days on daily bars.
  • Speed buys frequency; horizon buys size. First question for any idea: what is the holding period? Seconds: drop it. Days: home ground.
Check yourself 2 questions
  1. What kit does HFT need?

    Show answer

    Colocation, tick feeds and FPGAs.

  2. Does latency matter for a systematic daily strategy?

    Show answer

    No.

Takeaway HFT competes on microseconds, intraday algos on tens of milliseconds, systematic strategies on ideas rather than speed.

Latency: physics sets the gap#

PlayerRound trip
Colocated HFT≈ 0.01 ms
Prop desk≈ 1 ms
Retail API algoHundreds of ms
HumanSeconds
  • Measured RELIANCE quotes() round trips: fastest 32 ms, median ≈ 500 ms, p95 ≈ 2,190 ms: ≈ 50,000× a colocated machine. Report median and p95, never the best call, and space calls to respect rate limits.
  • Colocation rents a rack metres from the matching engine (NSE and BSE both offer it) with a tick-by-tick feed; entry costs run to crores.
  • If profit depends on being first, retail loses. Compete on horizon, research depth and niches HFT ignores.
Check yourself 2 questions
  1. Median retail quotes() round trip measured?

    Show answer

    About 500 ms.

  2. Which latency numbers should you report?

    Show answer

    Median and p95, never the best call.

Takeaway Retail API round trips run hundreds of milliseconds, about 50,000× a colocated machine; report median and p95.

Market data feeds: L1, L2, L3#

LevelShowsFits
L1Best bid/ask, sizes, last tradePosition and swing trading on snapshots
L2Aggregated ladder of 5–20 levels a sideIntraday systematic (snapshot or conflated)
L3Every individual order in arrival sequence: queue position visibleMarket making, HFT queue racing (tick-by-tick, colocated)
  • A tick feed sends every add, modify, cancel and trade, so the book can be rebuilt exactly; a snapshot freezes the state every ≈ 200 ms or on request; conflation merges updates and erases the path. OpenAlgo depth() is a 5-level snapshot.
  • MCX crude: L1 showed 3 lots at the best bid while the L2 bid side held 89. RELIANCE's first hour: the close-only path travelled 37.9 points, the intra-bar path 151.6 (≈ 4×): conflated bars understate range, slippage and stop touches.
  • Feed handlers apply events by exchange sequence number; a gap means the book is suspect: take a fresh snapshot, then replay. Buy the resolution your holding period needs and no more.
Check yourself 2 questions
  1. Which feed shows queue position?

    Show answer

    L3.

  2. Which feed suits swing trading?

    Show answer

    L1 snapshots.

Takeaway L1 is top of book, L2 a ladder of levels, L3 every order with queue position.

Rebuilding the book from events#

  • "An order book is not a thing the exchange sends you": it is state computed from an ordered tape, deterministically.
  • Add joins the back of its price; modify keeps place only for a size cut (price change or size increase goes to the back); cancel removes and may move the best level; trade consumes best price first, then FIFO.
  • Store arrival sequence numbers. After every event check: no crossed or locked book, no negative sizes, trades reconcile with the venue's tape.
  • Features (spread, depth per level, imbalance, microprice, trade sign) must use only events up to time t.
  • Replay answers queue and cost questions well, but cannot show how your own large order would have changed the future.
Check yourself 2 questions
  1. Does a size reduction keep queue priority?

    Show answer

    Yes; a price change or size increase goes to the back.

  2. Does the exchange send you 'the book'?

    Show answer

    No. You compute it from an ordered tape of events.

Takeaway An order book is state computed deterministically from an ordered event tape.

HFT strategy families#

FamilyHow it earnsWhat kills it
Passive market makingThe spreadAdverse selection, inventory drift
Latency arbitrageSame asset, two prices (venues, future vs basket, ETF vs stocks)Someone faster; closed to retail
Statistical arb at speedz-score of A − β·B beyond ±2Unstable relationships
Event reactionReading RBI, results, index news firstFalse signals, crowd fading the spike
Liquidity detectionProbing for hidden sizeCrossing into manipulation

HDFCBANK vs ICICIBANK, 1-minute bars: |z| ≥ 2 on 14.6% of bars vs ≈ 5% for a clean mean-reverting series: a weak, drifting pair fires constantly. Signals are cheap; proving stability is the work. Borrow the HFT habits without the speed: inventory caps, loss limits, volatility triggers.

Check yourself 2 questions
  1. What kills passive market making?

    Show answer

    Adverse selection and inventory drift.

  2. Why is latency arbitrage closed to retail?

    Show answer

    Someone faster always gets there first.

Takeaway Market making earns the spread, latency arbitrage needs speed, and statistical arb at speed trades spreads; each has a killer.

Order-to-trade ratio and manipulation#

OTR = (new + modify + cancel messages) ÷ trades, per symbol per dayhonest maker: 2 × 1,006 quote refreshes ÷ 311 fills ≈ 6.5 : 1stuffing profile, same fills: ≈ 76 : 1
  • Exchanges charge slab-based fees above a free band (≈ 50 : 1 in the course's illustration; take real slabs from current circulars). Registered market makers get relief.
  • Quote stuffing floods and cancels; spoofing shows bait size then cancels after filling the other side; layering fakes depth across levels. These are manipulation under SEBI's PFUTP rules, separate from any OTR fee, and every message is logged against client code and algo ID.
  • Budget messages per symbol, cancel only for real reasons (fair value or inventory changed), and watch OTR in sandbox sessions before going live.
Check yourself 2 questions
  1. OTR formula?

    Show answer

    (New + modify + cancel messages) ÷ trades.

  2. Why do exchanges charge above a free band?

    Show answer

    To discourage quote stuffing.

Takeaway OTR = messages ÷ trades; honest makers run single digits, stuffing profiles run far higher and draw fees.

Smart order routing across NSE and BSE#

StockNSEBSEGapBuy on
RELIANCE1318.101318.25−1.1 bpsNSE
TCS2094.702095.60−4.3 bpsNSE
HDFCBANK796.30796.05+3.1 bpsBSE
  • Two independent books kept close by arbitrage, never merged. A router splits a parent order: buy 5,000 RELIANCE → 3,000 on NSE at 1318.10, sweep 2,000 on BSE at 1318.25.
  • RELIANCE over 118 days: mean gap 2.9 bps, max 19 bps; NSE dearer on 58 days, BSE on 57. No venue is permanently best.
  • India has a broker best-execution duty but no consolidated tape and no order-protection rule (unlike US Reg NMS). For retail the value is defensive: avoid the worse venue; depth matters more than a slightly better last price.
Check yourself 2 questions
  1. Are NSE and BSE order books merged?

    Show answer

    No. Two independent books.

  2. What does a smart router do?

    Show answer

    Splits a parent order across venues by price and depth.

Takeaway NSE and BSE are separate books kept close by arbitrage; a router splits orders to the better price.

Execution algorithms: slice, don't dump#

AlgoSlices byBenchmarkBest when
TWAPEqual pieces over timeMean of bar pricesNo volume forecast; a steady footprint
VWAPExpected volume curve (heavy open and close)Day's VWAPFull-session orders judged against VWAP
POVFixed share of live volume (e.g. 10%)ParticipationImpact proportional to flow; finish time can float
Implementation shortfallSchedule solved from urgencyDecision priceWhen delay costs as much as impact
typical price = (H + L + C) / 3 · VWAP = Σ(typical × volume) ÷ Σ volumeRELIANCE 5-min, 24 Jun 2026: VWAP 1,312.30 vs TWAP 1,313.22

Total cost = explicit (brokerage, STT, fees, stamp) + implicit (spread, impact, delay drift). Almgren–Chriss: trading faster raises impact and cuts timing risk; one risk-aversion knob picks the point: urgent traders front-load, patient ones stretch. POV may never finish in a quiet market, so don't use it against a hard deadline. Run TCA on every execution.

Check yourself 2 questions
  1. Which algo uses a fixed share of live volume?

    Show answer

    POV (percentage of volume).

  2. Which benchmark does VWAP target?

    Show answer

    The day's VWAP.

Takeaway TWAP slices evenly in time, VWAP by the volume curve, POV as a share of live volume.

Market making and inventory risk#

reservation price r = mid − q · γ · σ² · (T − t)skewed quotes: bid = mid − half − k·q, ask = mid + half − k·qP&L = spread captured + inventory mark-to-market
RELIANCE 1-min sim (±₹0.20, 100-share clips)Skewed (k = 0.01)Naive
Spread captured+₹10,285+₹10,940
Inventory mark-to-market−₹14,110−₹42,680
Net−₹3,825−₹31,740
Ending inventory500 shares5,700 shares

On a trending day a symmetric quoter ends up short the trend. Lean quotes against inventory (k is the risk dial), widen when volatility rises, hedge residual risk, and always split P&L into spread vs inventory.

Check yourself 2 questions
  1. Why skew quotes when long inventory?

    Show answer

    Lower both quotes to encourage selling and reduce inventory.

  2. Market maker P&L components?

    Show answer

    Spread captured plus inventory mark-to-market.

Takeaway Skew quotes against inventory: P&L is spread captured plus inventory mark-to-market.

SEBI's retail API algo framework#

  • SEBI circular of 4 Feb 2025 lets brokers offer retail algos via APIs and third-party platforms, with the broker as principal: every algo order must trace to an approved, owned algorithm.
  • Controls: a unique vendor-specific API key, a whitelisted static IP, and an exchange-issued algo ID on every order. Crossing the exchange's orders-per-second threshold is what makes traffic "algo"; the number is exchange-set and revised (the course's 10 a second is only an illustration).
White-boxBlack-box
LogicDisclosed, reproducibleNot disclosed or replicable
RegimeStandard registration, tagged IDExtra documentation and provider duties; re-register on logic changes

Exchanges register algos, set thresholds and surveil; brokers approve, tag and supervise; you trade from the static IP, guard the key, respect rate limits and never bypass controls.

Check yourself 2 questions
  1. Name two controls in SEBI's retail algo framework.

    Show answer

    Any two of: a vendor-specific API key, a whitelisted static IP, an exchange-issued algo ID.

  2. Who is principal for retail API algos?

    Show answer

    The broker.

Takeaway Since February 2025, retail algos run via brokers as principals, with vendor API keys, static IPs and exchange algo IDs.

Kill switches and fail-safe design#

  • Every order passes a serial pre-trade gate independent of the signal: kill switch → daily loss → position cap → rate limit → exchange. Any gate can veto; rejections are logged and alerted.
  • Limits in rupees off the live price, not share counts. Example: cap ₹20 lakh, loss limit ₹25,000, 4 orders per 10 s: 8 orders proposed, 4 passed (a BUY 600 would have made 1,600 shares ≈ ₹21.1 lakh).
  • A kill switch latches until a deliberate manual reset and logs who tripped it; auto re-arming is worse than none. Fail closed (missing quote = reject), add a dead-man heartbeat, and test the failure paths.
  • Runaway strategy: −₹5.67 lakh unmanaged vs −₹56,468 with a ₹50,000 switch: it caps losses but can overshoot. In 2012 one firm lost ≈ $440 million in ≈ 45 minutes. Exchanges require members to keep kill-switch capability.
Check yourself 2 questions
  1. Order of the pre-trade gates?

    Show answer

    Kill switch, daily loss, position cap, rate limit, then the exchange.

  2. Why set limits in rupees, not share counts?

    Show answer

    So they track live exposure regardless of price.

Takeaway Every order passes a serial gate (kill switch, daily loss, position cap, rate limit) independent of the signal.

Does this order pass the risk gate?#

The strategy proposes an order
1Is the kill switch clear, not latched?
no
Reject: switch trippedstays blocked until a manual reset
yes
2Is today's loss inside the rupee limit?
no
Reject: loss limit hitno new risk-increasing orders today
yes
3Would the position stay under the rupee cap at the live price?
no
Reject: position capresize or skip
yes
4Is the order rate under the throttle?
no
Reject: rate limitwait for the window to clear
yes
Send to the exchangetagged with the algo ID, then reconcile the fill
Check yourself 2 questions
  1. The kill switch tripped yesterday. Can orders flow today?

    Show answer

    No; it stays latched until a manual reset.

  2. Today's loss limit is hit. What's allowed?

    Show answer

    No new risk-increasing orders today.

Takeaway A tripped switch, a hit loss limit, or a breached position or rate limit rejects the order.

05Module E · Time series, econometrics and forecasting

OpenAlgo Open Varsity · Quantitative Trading · chapters 41–48 (ARIMA, EWMA and GARCH, realised volatility, mean reversion and OU, cointegration, regimes and breaks, forecast evaluation, capacity and half-life)

AR, MA and ARIMA: pick the right target#

  • AR(p): today depends on past values (φ); MA(q): on past shocks (θ); I(d): difference d times to reach stationarity. On returns (d = 0): y_t = φ·y_(t−1) + θ·ε_(t−1) + ε_t.
  • NIFTY daily returns, ARIMA(1,0,1): AR +0.002, MA +0.002, and the 5-day forecast collapses to the 0.044% mean after one step. Lag-1 autocorrelation 0.004, well inside the ±2/√n band. Near-zero coefficients are the right answer, not a bug.
  • Returns are close to white noise; piling on terms (ARIMA(5,0,5)) only fits noise. Check ACF/PACF before choosing p and q.
  • Where these models earn their keep: volatility (it has memory), cointegrated spreads, macro series. "Time-series models aren't a way to predict tomorrow's price."
Check yourself 2 questions
  1. What does I(d) mean in ARIMA?

    Show answer

    Difference d times to reach stationarity.

  2. What happened to NIFTY's 5-day ARIMA return forecast?

    Show answer

    It collapsed to the mean: no useful signal.

Takeaway ARIMA on returns finds almost nothing: forecasts collapse to the mean; model what has memory, such as volatility.

Volatility has memory: EWMA and GARCH#

GARCH(1,1): σ²_t = ω + α·ε²_(t−1) + β·σ²_(t−1)persistence = α + β annualise volatility × √252 (not × 252)
  • EWMA weights recent squared returns more, with one decay parameter and nothing to fit. GARCH adds a long-run anchor ω: α is the reaction to yesterday's shock, β the memory.
  • NIFTY since 2021: α ≈ 0.103, β ≈ 0.872, persistence ≈ 0.975 (our arithmetic: a shock's half-life ≈ 27 trading days). Next-day forecast 0.83% ≈ 13.2% annualised; history ranged 9–37%.
  • Multi-step forecasts drift back to the long-run level. Use them to size (smaller when volatility is high), price options, run VaR and stress tests, and flag regime shifts. Compare with India VIX, the market's implied view.
  • Scale returns to percent and drop the first NaN before fitting.
Check yourself 2 questions
  1. How do you annualise daily volatility?

    Show answer

    Multiply by √252, not 252.

  2. What does β capture in GARCH?

    Show answer

    Memory: how much of yesterday's variance persists.

Takeaway GARCH σ² = ω + α·shock² + β·last σ²; persistence = α + β; annualise volatility with √252.

Realised and intraday volatility#

realised variance (day) = Σ (intraday log returns)²realised vol = √RV × √252full-day variance = intraday RV + overnight return²
  • NIFTY, 77 sessions of 5-minute bars: intraday realised vol 11.2% vs close-to-close 18.7%. The 7.5-point gap is overnight risk the intraday measure leaves out, and gaps can't be traded through.
  • Five-minute bars are the standard compromise for liquid Indian names; below ≈ 1–5 minutes bid-ask bounce inflates the estimate (check with a signature plot).
  • RELIANCE intraday is U-shaped: mean |1-minute move| 9.3 bps at the open, 3.7 at midday, 4.5 at the close. Even schedules over-trade the costly open.
  • Realised looks back, implied (India VIX) looks forward; implied usually sits above later realised, and that gap is the variance risk premium paid to option sellers.
Check yourself 2 questions
  1. Why was NIFTY's intraday realised vol (11%) below close-to-close (19%)?

    Show answer

    It excludes overnight gaps.

  2. Realised variance for a day?

    Show answer

    The sum of squared intraday log returns.

Takeaway Intraday realised volatility misses overnight risk; add the overnight return squared for the full day.

Mean reversion and Ornstein–Uhlenbeck#

dx = κ(θ − x)dt + σ dW "a random walk on a leash"half-life = ln 2 / κ AR(1): φ = 1 − κestimate: regress Δx on lagged x → slope = −κ
  • Prices rarely revert; constructed series do: distance from a moving average, ratios, spreads, cash-futures basis, volatility.
  • RELIANCE log(price ÷ 20-day SMA): ADF p ≈ 0.000, κ = 0.086 a day, θ ≈ 0, half-life 8.0 days: a swing-trading horizon.
  • Trade the z-score: fade extremes, exit near the mean, hold about one half-life, and time-stop after 2–3 half-lives. A moving-average distance passes ADF partly by construction, so it is not proof of an edge: check costs, sub-periods, a second test and regime breaks.
Check yourself 2 questions
  1. Do raw prices usually mean-revert?

    Show answer

    Rarely; constructed series such as spreads, ratios and basis do.

  2. Half-life formula?

    Show answer

    ln 2 ÷ κ.

Takeaway OU is a random walk on a leash; half-life = ln 2 ÷ κ, estimated by regressing changes on lagged levels.

Cointegration and pairs#

Pair (NSE daily since 2021)CorrelationCoint pHedge βVerdict
KOTAKBANK / HDFCBANK0.720.0010.22Cointegrated
HDFCBANK / ICICIBANK0.780.1420.26Not cointegrated
TCS / INFY0.800.4771.94Not cointegrated
  • Correlation is about day-to-day steps; cointegration means a fixed combination A − β·B of two random walks is stationary. The most correlated pair here fails the test.
  • Engle–Granger: regress A on B for β, then ADF the residual (p < 0.05 passes). Johansen handles baskets of three or more.
  • KOTAK − 0.22 × HDFC: short the spread above z +2, buy below −2, exit at 0, hard stop at ≈ 3.5–4σ. Latest z +1.92; ±2σ was breached on 73 days.
  • Indian ideas: private banks, oil marketers, cement, a stock vs its sector index, group companies. The short leg needs an SLB borrow; match rupee exposure then round to shares or lots; you pay two spreads.
  • Re-test on a schedule with a rolling β; a rising half-life warns of a breaking link; never average down into a merger or regulatory break.

Main card on cointegration: Stat arb → Also in Algo trading · Stat arb.

Check yourself 2 questions
  1. TCS/INFY had 0.80 correlation. Cointegrated?

    Show answer

    No (p about 0.48).

  2. Which NSE pair was cointegrated in the example?

    Show answer

    Kotak Bank / HDFC Bank.

Takeaway Correlation is about daily steps; cointegration means the hedged levels stay tied.

Is this spread tradable?#

A candidate pair or spread
1Is there an economic reason the two should stay linked?
no
Skip: no economic storya data-mined pair will break
yes
2Does Engle-Granger pass, residual ADF p below 0.05?
no
Not cointegratedhigh correlation alone is not enough
yes
3Is the half-life short enough to beat two spreads and borrow costs?
no
Too slow for its costsfew round trips a year, thin net edge
yes
4Does it still pass in sub-periods and on a rolling re-test?
no
Unstable linkshelve it and re-test later
yes
Trade the z-score±2 entries, exit near 0, hard stop near 4σ
Check yourself 2 questions
  1. No economic reason the pair should stay linked. Verdict?

    Show answer

    Skip: a data-mined pair will break.

  2. What ADF p-value must the residual pass?

    Show answer

    Below 0.05.

Takeaway Economic story, Engle-Granger pass, a usable half-life, and an edge that survives costs.

Regimes and structural breaks#

NIFTY since 2019DaysAvg daily return
Bull / calm762+0.059%
Bull / turbulent528+0.123%
Bear / calm66+0.002%
Bear / turbulent299−0.089%
  • Bull/bear = close above/below the 200-day SMA; turbulent = 20-day volatility above its median (taken over the full sample, which itself peeks ahead). One index behaves like four assets.
  • A regime is a persistent mood with its own statistics; a flip reverts; a structural break changes the rules for good. Markov-switching models treat the regime as a sticky hidden state, so today's regime is informative about tomorrow's.
  • Trend-following bleeds in chop; volatility selling dies when turbulence returns. Ask which regime an edge needs, size with volatility forecasts, mix strategy types, and keep re-testing the assumptions an edge rests on.
Check yourself 2 questions
  1. How did the course define bull versus bear?

    Show answer

    Close above or below the 200-day SMA.

  2. Which NIFTY regime had the worst average daily return?

    Show answer

    Bear and turbulent.

Takeaway Label regimes by trend (200-day SMA) and turbulence (volatility versus median); returns differ sharply by regime, and breaks change models.

Forecast evaluation and model decay#

NIFTY 20/50 momentum signIn-sampleOut-of-sample
Directional accuracy53.19%51.53%
z vs a coin flip2.720.96
One-sided p0.0030.169
Annualised signed return11.7%3.9%
z = (hit rate − 0.5) / √(0.25 / n)
  • Score only out of sample, beat a naive forecast (zero or the mean), and attach a significance test. MSE punishes big misses, MAE is robust; use direction metrics when the payoff is directional. Diebold–Mariano tests whether two forecasts' loss gap is real.
  • The rolling one-year hit rate peaked at 65.1% and was 42.5% recently: decay is the default as edges get arbitraged and regimes shift.
  • Set retirement triggers before launch: edge no longer significant, live drawdown beyond the worst backtest, a broken premise, or an edge too small for costs at size.
Check yourself 2 questions
  1. NIFTY momentum sign: in-sample versus out-of-sample hit rate?

    Show answer

    About 53.2% (significant) versus 51.5% (not significant).

  2. z-score of a hit rate against a coin flip?

    Show answer

    (hit rate − 0.5) ÷ √(0.25 ÷ n).

Takeaway Score only out of sample against a naive forecast; a significant in-sample edge often decays to noise.

Capacity, turnover and signal half-life#

half-life = −ln 2 / β (β from Δspread on lagged spread)round-trip impact ≈ 2 · Y · σ · √(order / ADV), Y ≈ 0.5annual profit = AUM × trades a year × net bps / 10,000
  • HDFCBANK vs KOTAKBANK spread: half-life 35.8 trading days, so only ≈ 7 round trips a year before costs dominate. Rebalance no faster than about one half-life.
  • RELIANCE signal with 12 bps gross edge, 120 trades a year: capacity ≈ ₹9 crore (0.37% of ADV a trade), where impact eats 8 of the 12 bps; peak net ≈ ₹0.43 crore a year; beyond ≈ ₹20 crore it loses money.
  • Capacity sits where impact eats about two-thirds of the gross edge; past it, more AUM earns fewer rupees. Scale through breadth (many independent bets), run well below capacity, and remember crowding (the August 2007 quant unwind) shrinks edge and capacity together.
Check yourself 2 questions
  1. A 36-day half-life allows about how many round trips a year?

    Show answer

    About 7.

  2. Annual profit formula?

    Show answer

    AUM × trades a year × net bps ÷ 10,000.

Takeaway Half-life sets turnover, impact grows with size, and capacity sits where impact eats most of the edge.

06Module F · Derivatives, volatility and arbitrage

OpenAlgo Open Varsity · Quantitative Trading · chapters 49–58 (futures and carry, basis and index arb, Black-76, Greeks, volatility surface, India VIX and VRP, gamma scalping, derivatives microstructure, currency and rates, margins and limits)

Futures, forwards and cost of carry#

fair future = spot + financing − income (dividends)basis = future − spot → 0 at expirysynthetic future = K + C(K) − P(K) (put-call parity at one strike)
  • A forward is a bespoke OTC deal settled once; a future is the exchange-listed, daily-marked, novated version. Same value, different credit and liquidity.
  • NIFTY: spot 24,021.65, June future 24,053.60 (basis +31.95, 0.13%), synthetic from options 24,058.30: three routes to the same forward within a few points.
  • Indian carry is usually positive (financing beats dividends). Around a big ex-dividend date spot drops but the future barely moves, so the basis narrows: that is not "cheap". Rolling pays carry again each month.
  • Always annualise basis; raw points shrink mechanically toward expiry.
Check yourself 2 questions
  1. Synthetic future from options at strike K?

    Show answer

    K + C(K) − P(K).

  2. Forward versus future?

    Show answer

    A forward is a bespoke OTC deal settled once; a future is exchange-listed, marked daily and novated.

Takeaway Fair future = spot + financing − income; basis converges to zero; put-call parity builds a synthetic future.

Basis and index arbitrage#

F = S · e^(carry · T) carry = ln(F / S) / T, T = days / 365NIFTY Jul: 24,170.50 vs 24,056 → +114.5 pts (0.48%), 30 days → 5.78% a year
StateFuture vs fair valueTrade
RichAbove (implied carry well over the money rate)Cash-and-carry: sell future, buy basket
CheapBelowReverse: buy future, sell (borrowed) basket
  • Convergence is forced: the June NIFTY basis fell from +398 points on 1 Apr to +46 on 25 Jun.
  • You can't buy NIFTY itself: replicate 50 stocks at index weights, or use a subset or ETF and accept tracking error.
  • Risks: the basis can widen before expiry (mark-to-market pain), dividend surprises, legging and execution, STT and funding, and borrowing for the reverse trade. For most desks the basis is more valuable as a signal than as a trade.
Check yourself 2 questions
  1. NIFTY future 24,170.5 versus spot 24,056 over 30 days: annual carry?

    Show answer

    About 5.8%.

  2. Future is rich versus fair value. Trade?

    Show answer

    Cash-and-carry: sell the future, buy the basket.

Takeaway Implied carry = ln(F/S) ÷ T; a rich future invites cash-and-carry, a cheap one reverse cash-and-carry.

Black-76, not Black–Scholes#

C − P = e^(−rT) (F − K) → F = K + e^(rT) (C − P)C = e^(−rT) [F·N(d1) − K·N(d2)]d1 = [ln(F/K) + σ²T/2] / (σ√T), d2 = d1 − σ√T
Black–ScholesBlack-76
Underlying inputSpotForward (synthetic future)
CarryRebuilt from rates and dividendsAlready inside F
IndiaWrong tool for NFO/BFORight for NFO, BFO, MCX, CDS

Indian options settle against the future/forward, so pricing off spot mis-states every output by the carry. NIFTY 24000 call at 166.75 with F 24,058.30 → IV ≈ 11.14%, delta +0.571, theta −11.36 a day. Compare options in IV, not price; the model is "wrong but useful", a common language for quoting and hedging.

Check yourself 2 questions
  1. Why use Black-76 for NIFTY options?

    Show answer

    It takes the forward as input, so carry and dividends needn't be rebuilt.

  2. How do you get F from option prices?

    Show answer

    F = K + e^(rT)(C − P) at one strike.

Takeaway Price index options on the forward with Black-76; carry is already inside F, recovered by put-call parity.

From option chain to hedge#

flowchart TD
  CH["Option chain: calls and puts by strike"] --> PCP["Put-call parity at the ATM strike"]
  PCP --> F["Forward F (synthetic future)"]
  F --> B76["Black-76 per strike"]
  B76 --> IV["Implied vol per strike and expiry"]
  IV --> SURF["Volatility surface: skew and term structure"]
  IV --> GR["Greeks: delta, gamma, vega, theta, rho"]
  GR --> H["Sum across the book, hedge what you don't want"]

One wrong forward corrupts price, IV and every Greek at once.

Check yourself 2 questions
  1. What comes right after put-call parity in the pipeline?

    Show answer

    The forward F, then Black-76 per strike.

  2. What do you build from implied vols across strikes and expiries?

    Show answer

    A volatility surface.

Takeaway Chain, parity forward, Black-76 per strike, implied vols, a volatility surface, then Greeks to hedge.

The Greeks: the gradient of a price#

NIFTY Jul 24200 (F 24,180.70)PriceIVDeltaGammaVegaTheta / dayRho
Call342.9512.72%+0.4990.000452+27.70−5.85−0.283
Put361.7512.70%−0.5010.000452+27.70−5.85−0.298
Short 1 straddleCredit+0.003−0.000904−55.40+11.70 (≈ ₹760 a lot)
  • Delta ∂V/∂F: hedge ratio and rough in-the-money odds. Gamma ∂²V/∂F²: how fast delta moves, identical for call and put at a strike, peaking at the money. Vega: per 1 vol point. Theta: per calendar day. Rho: per 1 rate point, tiny for 30-day Indian options.
  • Greeks add across legs, so a whole book collapses to a few numbers. Long gamma pays theta and wants moves; short gamma collects theta and wants stillness, then loses sharply on gaps, especially near expiry. Delta-hedging leaves a pure volatility bet.
  • Delta across NIFTY strikes ran from 0.92 deep in the money to 0.04 far out. Choose strikes for the Greek you want, not the price.
Check yourself 2 questions
  1. Delta of an ATM call is about?

    Show answer

    +0.5.

  2. Short one straddle: sign of gamma, vega and theta?

    Show answer

    Negative gamma, negative vega, positive theta.

Takeaway Greeks are the price's sensitivities; a short straddle is short gamma and vega and collects theta.

The volatility surface#

NIFTY Jun call strikeIV
23,40014.59%
23,70012.10%
24,00011.15%
24,30010.72% (trough)
24,70011.77%
  • Each strike quotes its own IV: a smile, tilted into a skew because downside strikes carry crash insurance (fat tails, Module B). Across expiries it is a term structure; strike × expiry is the surface.
  • Skew is an insurance premium, not a directional forecast. Weekly expiries dominate Indian index volume, and a 6-day option's skew behaves nothing like a 3-month one's.
Check yourself 2 questions
  1. Why are downside strikes' IVs higher?

    Show answer

    They carry crash insurance against fat-tailed falls.

  2. Where was the trough of NIFTY's June smile?

    Show answer

    Slightly above ATM, about 24,300.

Takeaway Each strike has its own IV: a smile tilted into a skew because downside strikes carry crash insurance.

India VIX and the variance risk premium#

1-day 1σ move ≈ S × VIX/100 ÷ √25230-day 1σ move ≈ S × VIX/100 ÷ √12VIX 13.05, NIFTY 24,056 → ≈ 198 pts a day · ≈ 906 pts a month
  • India VIX is a model-free 30-day expected volatility from the OTM chain (weights ΔK/K², near and next weekly expiries interpolated to 30 days).
  • One year: mean IV 13.77% vs later realised 11.84%, so a VRP of ≈ +1.9 points; IV beat RV on 82% of days. NIFTY return vs VIX change correlation −0.75; VIX peaked at 27.89 on 30 Mar 2026 in a sell-off. Calm sits in the low teens.
  • Ways to use it: sell it (delta-hedged straddles, purest and most tail-exposed), read it as a regime signal (cut size when high and rising), or trade the near vs far term structure. VRP is pay for crash risk, not free money: size for the spike.
Check yourself 2 questions
  1. VIX 13, NIFTY 24,056: roughly the 1-day 1σ move?

    Show answer

    About 198 points.

  2. What is the variance risk premium?

    Show answer

    Implied volatility typically exceeding realised volatility.

Takeaway One-day 1σ ≈ spot × VIX/100 ÷ √252; implied usually exceeds realised, which pays option sellers on average.

Gamma scalping and volatility trading#

Long vol (buy straddle)Short vol (sell straddle)
Gamma / theta+ / − (pays daily)− / + (collects daily)
Wins whenRealised beats impliedCalm: realised below implied
Worst caseThe premiumLarge, possibly unlimited
  • NIFTY 24000 straddle: 166.75 + 108.45 = 275 → breakevens 23,725 / 24,275; expiry payoff |S − 24,000| − 275.
  • Gamma scalping: hold long gamma and keep re-hedging delta (buy dips, sell rallies). The scalps harvest realised volatility; theta charges you the implied you paid. Live check: VIX 13.39 vs 30-session realised 11.76, a +1.6-point VRP in the seller's favour.
  • Indian specifics: weekly expiries crush theta into expiry day, heavy premium selling can pin the index to popular strikes, and sudden moves do damage in minutes. Defined risk and position limits are the strategy, not an add-on.
Check yourself 2 questions
  1. When does a long straddle with gamma scalping win?

    Show answer

    When realised volatility beats implied.

  2. Worst case of selling a straddle?

    Show answer

    Large, possibly unlimited loss.

Takeaway Long vol wins when realised beats implied; short vol collects theta and risks large losses.

Derivatives microstructure in India#

  • Liquidity concentrates on three axes and thins along each: index over stock, front expiry over deferred, round strikes near the money over the rest.
  • NIFTY Jul chain: 8.7 mn OI at 24,000 vs 0.22 mn at the 24,050 ATM half-strike; five 500-multiple strikes held 62% of OI across ≈ 45 strikes. Prefer round strikes for fills and exits.
  • Options tick in 5 paise; for far-OTM options one tick can be 20%+ of the premium. Backtests at mid or last price assume a two-sided book that often isn't there.
  • NSE derivatives settle Tuesdays, BSE Thursdays. Index F&O cash-settles; stock F&O delivers (one RELIANCE lot = 500 shares), so close or roll before expiry day.
Check yourself 2 questions
  1. Where does option liquidity concentrate?

    Show answer

    Index options, the front expiry, round strikes near the money.

  2. Why did 24,000 have far more OI than 24,050?

    Show answer

    Round (500-multiple) strikes attract liquidity.

Takeaway Liquidity concentrates in index over stock, front expiry over deferred, and round strikes near the money.

Currency and interest-rate derivatives#

covered interest parity: F = S × (1 + i_INR·t) / (1 + i_USD·t)rate hedge: contracts ≈ book DV01 ÷ future DV01
  • CDS segment (SEBI + RBI): USD-INR futures and options, 1,000 USD a contract, tick 0.0025, trading till 5 pm; plus cross pairs. Interest-rate futures on the 10-year GoI bond and 91-day T-bill; liquidity clusters around RBI meetings and auctions.
  • USD-INR volatility 5.54% vs NIFTY 13.14%; over the year the rupee weakened 88.77 → 94.70 while NIFTY fell 3.1%; daily correlation −0.13. Low volatility makes the rupee a hedging variable more than an alpha source.
  • Size rate hedges by DV01, not notional; estimate FX hedge ratios on rolling windows; most FX hedging happens OTC, so exchange volume understates the market.
Check yourself 2 questions
  1. Covered interest parity for USD-INR?

    Show answer

    F = S × (1 + i_INR·t) ÷ (1 + i_USD·t).

  2. How many rate futures hedge a bond book?

    Show answer

    Book DV01 ÷ future DV01.

Takeaway Covered interest parity prices currency forwards; rate hedges size by DV01.

Margins, position limits and settlement#

1 lotLotLeverage (notional ÷ SPAN + exposure)
NIFTY future658.82× (₹15.71 lakh notional; SPAN ₹1,46,626 + exposure ₹31,422 = ₹1,78,047, 11.3%)
BANKNIFTY future308.73×
SBIN future7505.68×
RELIANCE future5005.65×
  • SPAN shocks price and volatility across a grid and charges the worst loss on the whole portfolio; exposure margin adds a flat buffer for gaps. Hedges and spreads cut SPAN through cross-margining. Stocks are more volatile, so they get less leverage than indices.
  • Peak margin is sampled at random intraday snapshots: over-leverage between legs is penalised even if flat by the close.
  • MWPL: above 95% of the market-wide limit a stock enters the F&O ban (reduce-only), lifting below 80%. Client-level limits apply too.
  • Collateral counts after haircuts (₹10 lakh of shares might support ₹8 lakh of margin), about half must be cash-like for daily MTM. SPAN rises with volatility, so size to stressed margin, use the broker's calculator rather than an eyeballed percentage, and treat ban lists as hard edges in code.
Check yourself 2 questions
  1. Approximate leverage of one NIFTY future?

    Show answer

    About 8.8×.

  2. What does SPAN shock?

    Show answer

    Price and volatility, to estimate a worst-case day.

Takeaway Index futures carry about 9× leverage on SPAN plus exposure margin; stock futures about 5–6×.

07Module G · Alpha research and strategy families

OpenAlgo Open Varsity · Quantitative Trading · chapters 59–66 (research process, cross-sectional momentum, factors, stat arb, event-driven, flow-based, intraday reversion and breakout, alt data and NLP)

The alpha research process#

  1. Hypothesis with a number, universe and horizon: "NSE stocks in the top 12-month return quintile beat the bottom quintile next month, after costs."
  2. Fair test: no look-ahead, no survivorship, realistic costs; fix the success metric before looking.
  3. Split: search in-sample, test the final idea once out of sample.
  4. Economic reason: who pays the edge, and why? "It works but I don't know why" is a warning.
  5. Decay and capacity: crowding weakens edges; impact caps the money they can hold.

NIFTY "long above SMA(n)", searched over n = 10…120: best in-sample SMA 35 with Sharpe 1.23, the same rule out of sample 0.57. Most of the in-sample shine was fitting the past. The process exists to kill ideas; trade what survives.

Check yourself 2 questions
  1. What makes a good alpha hypothesis?

    Show answer

    A number, a universe and a horizon, stated so it can fail.

  2. When must the success metric be fixed?

    Show answer

    Before looking at results.

Takeaway A numeric, falsifiable hypothesis; a fair test with costs and a fixed metric; then split and validate.

Cross-sectional momentum#

HorizonTypical behaviour
Days to weeksReversal
3 to 12 monthsMomentum
3 to 5 yearsReversal (value)
  • Rank stocks against each other, long the strongest, short the weakest: a market-neutral spread bet (unlike time-series momentum on one asset's own trend). Classic formation: 12-1 (12 months, skipping the latest).
  • 16 NSE stocks, 6-month signal, monthly rebalance, top vs bottom third: −0.94% a month, Sharpe −0.67: reversal in this window. Momentum is conditional, not fake.
  • Crashes: the short book holds beaten-down high-beta names that rebound hardest (2009, 2020): small steady gains, rare severe drawdowns. Scale by volatility.
  • India: no overnight cash shorts without SLB, so the short leg runs through stock futures (F&O names only) or costly, patchy borrow. Value usually offsets momentum: hold both.
Check yourself 2 questions
  1. Over which horizon does momentum work?

    Show answer

    About 3 to 12 months.

  2. Cross-sectional versus time-series momentum?

    Show answer

    Cross-sectional ranks stocks against each other; time-series uses one asset's own trend.

Takeaway Days-to-weeks reverse, 3–12 months persist, 3–5 years reverse; cross-sectional momentum ranks stocks against each other.

Factors: beta, value, quality, size, low-vol#

StockBeta to NIFTY (2 years)
ADANIENT1.62
TATASTEEL1.27
HDFCBANK1.05
ITC0.61
HINDUNILVR0.55
  • Most returns come from a few market-wide factors. Beta = cov(stock, market) ÷ var(market) is the first and largest exposure.
  • Survivors of scrutiny: value (cheap beats dear), momentum, quality (profitable, stable), low volatility (better risk-adjusted), size (small-cap premium for extra risk).
  • A 12-stock, 2-year test: last year's losers made +24.2%, winners −11.3%. Factors are long-run tendencies that can fail for years: diversify across several, combine ranks into one score, and distrust the "factor zoo" of multiple-testing artefacts.
Check yourself 2 questions
  1. Beta formula?

    Show answer

    cov(stock, market) ÷ var(market).

  2. Which of ADANIENT and HINDUNILVR has the higher beta?

    Show answer

    ADANIENT (about 1.6 versus 0.55).

Takeaway Most returns come from a few factors; beta is the first and largest exposure.

Statistical arbitrage books#

hedge β from OLS of A on B · spread = A − β·Bz = (spread − rolling mean) / rolling std (60-day)z > +2 short · z < −2 long · |z| < 0.5 flat
  • RELIANCE–ONGC from 2021: 46 trades, +446 spread points, Sharpe 0.47 and correlation 0.00 to a market that rose 71%.
  • A modest Sharpe with zero market correlation is valuable in a portfolio, and many uncorrelated pairs smooth each other: "statistical arbitrage is a team sport".
  • Beyond pairs: basket vs index or future, and cash-futures basis trades: low risk, high capacity, common on Indian prop desks.
  • Risks: broken cointegration, crowding, costs eating thin spreads. The course fits β on the full sample, which leaks the future: refit it on a rolling window, and add costs before trusting gross P&L.
Check yourself 2 questions
  1. Entry and exit z-scores used?

    Show answer

    Enter beyond ±2, flatten inside ±0.5.

  2. What was notable about RELIANCE–ONGC's returns?

    Show answer

    Roughly zero correlation to a market that rose 71%.

Takeaway Hedge with OLS beta, trade z-score extremes of the spread, flatten near zero; returns can be uncorrelated with the market.

Event-driven strategies#

NIFTY weekday (2019 on)Avg returnVolatility
Mon−0.073%1.41%
Tue+0.172%1.02%
Wed+0.112%0.95%
Thu+0.002%1.03%
Fri+0.039%1.04%
  • Event study: align many past events at day 0 and average the following days' returns (abnormal return = actual − expected; CAR = their sum).
  • PEAD: surprise beats keep drifting up and misses down for weeks; needs point-in-time results and consensus data. Index reconstitution: index funds must buy additions and sell deletions on the effective date: trade the run-up, exit into forced demand.
  • Corporate actions: unadjusted splits look like crashes; prices drop by about the dividend at ex-date; tender buybacks depend on the acceptance ratio.
  • Events are binary and earnings gaps can exceed 15%: size for the worst plausible move, cap exposure per name and per date. Trade forced or predictable behaviour, not clever prediction.
Check yourself 2 questions
  1. What is abnormal return?

    Show answer

    Actual return minus expected (market-model) return.

  2. Best average NIFTY weekday since 2019?

    Show answer

    Tuesday.

Takeaway Event studies align events at day 0 and average abnormal returns; weekday effects were small and noisy.

Flow-based strategies: FII/DII, OI and expiry#

  • Price + OI quadrants: long and short build-ups are fresh money (fuel); covering and unwinding are exhaustion. RELIANCE Jul future, 37 sessions: 14 long and 22 short build-up days (a young contract only shows build-ups; use the front month or all expiries for unwinds).
  • FPIs move large caps with global risk appetite; DIIs, fed by SIP inflows, often absorb their selling. Exchanges publish provisional cash flows each evening and participant-wise F&O OI; they are not in the price API, are revised, and work as multi-week streaks, not single days.
  • Ban list: OI ≥ 95% of MWPL bans new positions next day, lifting below 80%: a crowding and liquidity warning, not a directional bet.
  • Expiry sets the clock: pinning toward heavy-OI strikes, and rollover (RELIANCE's next-month OI +823% into June expiry). High rollover suggests conviction; roll cost is part of carry.
  • Score each flow as a signed input and act only on confluence that price confirms.
Check yourself 2 questions
  1. Why can a young contract mislead OI reads?

    Show answer

    It only shows build-ups; use the front month or all expiries.

  2. Short covering is fuel or exhaustion?

    Show answer

    Exhaustion.

Takeaway Build-ups are fresh money, covering and unwinding are exhaustion; use the front month for OI reads.

Intraday mean reversion and breakout#

ORB: range = first 15 min (09:15, 09:20, 09:25 bars)enter on a 5-min close beyond it · stop: far side · target: 1 range (1R)NIFTY 25 Jun: range 61.9 pts, gross ₹4,024 a lot → costs 16.3 pts → net ₹2,964
  • Breakout and reversion are bets on different regimes: trending, news-driven days reward the break; quiet rangebound days reward fading back to VWAP. Classifying the day is the hard part.
  • NIFTY future round trip ≈ ₹930 fees (≈ 14.3 points) + ≈ 2 points slippage → breakeven ≈ 16.3 points: an average +12-point trade is a guaranteed loser; costs ate 26% of the winning example.
  • RELIANCE the same day: broke up at 09:50, failed back below VWAP at 11:25 and closed at the bottom of the range: break → fail → fade.
  • Scale stops to the morning range or ATR, not fixed points, and be flat by the close unless overnight risk is intended.
Check yourself 2 questions
  1. How is the opening range defined in the ORB example?

    Show answer

    The first 15 minutes (three 5-minute bars).

  2. Gross ₹4,024 on one NIFTY lot: net after costs?

    Show answer

    About ₹2,964.

Takeaway Breakouts and reversion bet on different regimes; costs take a big slice of intraday edges.

Alternative data and NLP#

  • Sources in India: exchange announcements (precisely timestamped), SEBI orders, RBI statements, results filings, shareholding and insider disclosures, bulk/block deals, ban list, FII/DII figures; exotic: satellite, shipping, app ranks, card panels.
  • Pipeline: tokenise → score (lexicon: (pos − neg) ÷ max(pos + neg, 1)) → align and lag (where leakage happens) → size and risk-gate.
  • Six hand-picked headlines correlated +0.87 with same-day NIFTY returns: an illusion of author-chosen wording and six points.
  • SBIN overnight gaps > 2%, 33 events since 2021: day-0 move +3.17% (happens at the open, untradable), drift to day +10 only +0.68% with an error band straddling zero.
  • Ask: when did I know this, and how many independent observations do I have? Prefer structured disclosures over free text, and treat every text signal as guilty until proven innocent.
Check yourself 2 questions
  1. Name two Indian alternative-data sources.

    Show answer

    Any two of: exchange announcements, SEBI orders, RBI statements, results filings, insider disclosures, bulk and block deals, FII/DII flows.

  2. Why do precise timestamps matter?

    Show answer

    To avoid look-ahead: you can trade only after the information appeared.

Takeaway India's alternative data includes timestamped announcements and filings; NLP pipelines score text into signals.

Fade or follow today?#

An intraday setup on a liquid index or large cap
1Is it the first hour with a clean 5-min close beyond the opening range?
yes
Follow the breakoutstop at the far side, target one range width
no
2Is it the quiet midday on a rangebound, news-free day?
yes
Fade stretches back to VWAPsmall size, quick exits
no
3Did an earlier breakout fail back through VWAP?
yes
Fade the failed breaktoward the other side of the range
no
Stand asideno clean regime, and costs need about 16 NIFTY points
Check yourself 2 questions
  1. First hour, clean 5-minute close beyond the opening range: fade or follow?

    Show answer

    Follow, stop at the far side, target one range width.

  2. Quiet, news-free midday range: fade or follow?

    Show answer

    Fade.

Takeaway Follow clean opening-range breaks in the first hour; fade stretches in a quiet, rangebound midday.

08Module H · Backtesting, machine learning and portfolio construction

OpenAlgo Open Varsity · Quantitative Trading · chapters 67–72 (backtesting rigour, look-ahead, survivorship, corporate actions, walk-forward, purged CV, deflated Sharpe, ML in quant, features and labels, portfolio construction and risk)

Backtesting without fooling yourself#

  • A backtest is a measuring instrument that can be miscalibrated: data → signal → fills → costs → P&L → metrics, and one leak anywhere makes the metrics fiction.
  • Fills: never at the close that generated the signal; default to the next bar's open, pay at least half the spread, and model unfilled limit orders.
  • Costs: STT, stamp, exchange, SEBI, GST, brokerage plus spread and impact. "A frictionless backtest is a fantasy."
  • One missing .shift(1): NIFTY 20-day SMA sign rule shows Sharpe +4.51 and 25.2× with look-ahead, +0.16 and 1.07× lagged.
  • Red flags: too-good Sharpe, a curve without real drawdowns. Sharpe 2 after 1,000 trials is worth less than Sharpe 1 on the first honest try. Try to disprove the strategy.

Main card for honest backtesting. Also covered in Algo trading · Algo trading · Technical · this sheet · AmiBroker AFL.

Check yourself 2 questions
  1. Where should a signal from today's close fill?

    Show answer

    At the next bar's open, never the generating close.

  2. Minimum spread cost to charge per fill?

    Show answer

    At least half the spread.

Takeaway A backtest is a measuring instrument: fill at the next open, pay at least half the spread, and count every cost.

Three data biases#

BiasHow it sneaks inFix
Look-aheadSame-bar scoring, full-sample z-scores, intrabar high/low triggers, restated fundamentals, report date instead of filing dateEvery input strictly left of "now"
Corporate actions1:1 bonus reads as −50%, 1:5 split as −80%; full-history adjustment embeds future splitsBack-adjust point-in-time; total-return adjust dividends
Survivorship and reconstitutionRunning today's NIFTY 50 or 500 back ten years skips the failures and front-runs additionsPoint-in-time universe including delisted names

NIFTY 10-day momentum since 2018: scored on the same bar 61.1% hits, +22.3 bp a day, 94.8×; lagged 53.0%, +2.1 bp, 1.37×. Audit data first: flag close-to-close gaps over 15%, frozen prices, zero-volume rows, duplicate timestamps, and know whether prices are raw, adjusted, and point-in-time.

Check yourself 2 questions
  1. How does an unadjusted 1:1 bonus distort a backtest?

    Show answer

    It reads as a −50% crash.

  2. Fix for survivorship bias?

    Show answer

    A point-in-time universe including delisted names.

Takeaway Look-ahead, corporate-action errors and survivorship each quietly inflate backtests.

Walk-forward, purged CV and the deflated Sharpe#

NIFTY fold (expanding train)OOS periodFitted SMAOOS Sharpe
12019-08 → 2020-0910−0.07
22020-09 → 2021-1150+0.70
32021-11 → 2023-01100−0.77
42023-01 → 2024-0350+1.64
52024-03 → 2025-0550+0.25
62025-05 → 2026-0650−0.71
  • Mean fold Sharpe +0.17, stitched out-of-sample +0.06: a coin flip. Funding it on fold 4 alone would have been the lucky-split mistake.
  • Purging drops training rows whose label windows overlap the test block; an embargo drops rows just after it (serial correlation). Example: 2,101 bars, 420-bar test folds, purge 35, embargo 23. Never use shuffled k-fold on prices.
  • Combinatorial purged CV produces many backtest paths; from them, the probability of backtest overfitting is the chance the in-sample best lands below median out of sample. The deflated Sharpe adjusts for trials, their spread, skew and kurtosis. Leakage control and deflation are both required: neither substitutes for the other.
Check yourself 2 questions
  1. What did NIFTY's walk-forward folds show?

    Show answer

    Out-of-sample Sharpe swinging from about −0.8 to +1.6: unstable.

  2. What does purging remove?

    Show answer

    Training samples whose labels overlap the test period.

Takeaway Walk-forward folds show how unstable out-of-sample results are; the deflated Sharpe corrects for trials.

Machine learning: promise and peril#

NIFTY next-day directionTrainTest
Random forest, depth 569.1%50.1%
Depth 20100%49%
Always guess the majority51.2% (the bar to beat)
  • More capacity raises training accuracy while test stays at chance: model power is usually a liability in markets.
  • Helps: combining many weak signals, nonlinear interactions, volatility forecasting, alt data, meta-labeling. Hurts: raw direction in low signal-to-noise data, leakage, regime change.
  • Start with a regularised linear baseline; use gradient-boosted trees only if they win out of sample. Trust permutation importance on held-out data, not training-set MDI; importance is not causation.
  • If out-of-sample looks too good, suspect a leak first.
Check yourself 2 questions
  1. Depth-20 random forest: train versus test accuracy?

    Show answer

    100% versus about 49%.

  2. What baseline must a direction model beat?

    Show answer

    Always guessing the majority (about 51%).

Takeaway More model capacity raised training accuracy to 100% while test accuracy stayed at chance.

Features, labels and leakage#

  • Features must be point-in-time (shift a bar before joining labels) and roughly stationary: returns, rolling volatility, RSI, spreads, z-scores; fractional differencing keeps some price memory.
  • Triple-barrier labels: +1 if a volatility-scaled profit-take is hit first, −1 for the stop, 0 at the time limit. RELIANCE, 2× vol barriers, 10-bar horizon, 1,329 events: 48.2% / 42.7% / 9.2%, a tilt reflecting drift, not an edge.
  • Meta-labeling: a simple rule picks the side; a second model decides whether, and how big, to take it.
LeakFix
Overlapping labels share future daysUniqueness weights, purged CV
Scaler or selector fit on all dataFit on the training fold only
Feature built from the label window or restated fieldsTreat suspiciously strong features as leaks until proven otherwise

If a one-bar shift destroys the edge, it was look-ahead. "Garbage in, confident garbage out."

Check yourself 2 questions
  1. How do you make a feature point-in-time?

    Show answer

    Shift it a bar before joining it to labels.

  2. What is a triple-barrier label?

    Show answer

    +1 if a profit-take is hit first, −1 if a stop-loss, 0 if time runs out.

Takeaway Point-in-time, roughly stationary features; triple-barrier labels; and no leakage between them.

Portfolio construction, VaR and stress#

inverse-vol (risk parity) weight: w_i = (1/σ_i) / Σ(1/σ_j)Kelly fraction ≈ edge / variance → bet half or a quarter of itfactor risk model: Σ ≈ B·F·Bᵀ + DVaR: loss not exceeded at a confidence · CVaR (expected shortfall): average loss beyond VaR
  • Portfolio risk depends on covariance, not the average of individual risks; diversification is "the only free lunch". Five NSE stocks (RELIANCE 21%, HDFCBANK 22%, INFY 17%, ITC 23%, TATASTEEL 16%): volatility 14.1%, below every member's. One-day 95% VaR −1.42%, CVaR −2.04%, worst day −5.24%.
  • Raw Markowitz amplifies noisy return guesses. Robustness order: equal weight → risk parity → shrunk, constrained mean-variance (Ledoit–Wolf, caps, Black–Litterman) → raw Markowitz.
  • Volatility targeting (e.g. 12% a year) scales exposure inversely to realised volatility. Full Kelly on an overestimated edge is really 2–3× Kelly: growth falls and ruin follows.
  • History may not contain the worst shock (COVID: ≈ −13% in a day, ≈ −38% drawdown): stress-test gap-downs and volatility tripling, size for CVaR and drawdown, and look for hidden factor bets behind "diversified" names.
Check yourself 2 questions
  1. Inverse-volatility weight formula?

    Show answer

    (1/σ_i) ÷ Σ(1/σ_j).

  2. CVaR versus VaR?

    Show answer

    VaR is the loss not exceeded at a confidence; CVaR is the average loss beyond it.

Takeaway Inverse-vol weights, a fraction of Kelly, factor risk models, and VaR plus CVaR with stress tests.

Is this backtest honest?#

A strategy with a good-looking equity curve
1Is every signal lagged and every price adjustment point-in-time?
no
Leak found: fix the data firsta one-bar shift can turn 25x into 1.07x
yes
2Is the universe point-in-time, delisted names included?
no
Survivorship: rebuild the universetoday's index members flatter the past
yes
3Is it net of the full Indian cost stack, spread and impact?
no
Add costs and re-runfills at the next open, half a spread at least
yes
4Does it survive purged walk-forward with a deflated Sharpe above zero?
no
Overfit: discard itjudge the whole fold distribution, not the best fold
yes
Candidate: paper trade itthen go live small, with a kill switch

Main card on honest backtesting: this sheet → Also in Algo trading · Algo trading · Technical · AmiBroker AFL.

Check yourself 2 questions
  1. What did a one-bar shift do to the look-ahead example?

    Show answer

    Turned 25× into 1.07×.

  2. Universe excludes delisted names. Verdict?

    Show answer

    Survivorship bias: fix the universe.

Takeaway Lagged signals, point-in-time data, survivors included, full costs and out-of-sample stability, or it isn't honest.

09Module I · Production, compliance and career

OpenAlgo Open Varsity · Quantitative Trading · chapters 73–78 (data infrastructure, research to production, live system design, monitoring and reconciliation, compliance and ethics, capstone)

Data and research infrastructure#

RELIANCE resolutionBars a day
Daily / 1h / 15m1 / 7 / 25
5m / 1m75 / 375
TickThousands
  • Depth adds another axis (L1 → L2 → L3); tick plus L2 across a market runs to gigabytes a day, which needs a columnar time-series store, not CSVs.
  • Quality check on 1,853 RELIANCE daily rows: 108 missing business days, all NSE holidays; zero duplicate, zero-volume, NaN or > 20% rows. Use a real holiday calendar: weekdays are not trading days.
  • Store point-in-time (membership and earnings as first known) and adjust corporate actions; revised data leaks like look-ahead.
  • Pipeline: raw → clean → point-in-time store → research → production. Same code + same data = same result: version both. "Infrastructure is invisible until it fails, and then it fails your money."
Check yourself 2 questions
  1. Bars a day at 1-minute for NSE?

    Show answer

    375.

  2. Why not store tick and L2 data in CSVs?

    Show answer

    Gigabytes a day need a columnar time-series store.

Takeaway Bars per day multiply with resolution; tick plus depth needs a columnar time-series store, not CSVs.

Research to production: one signal, two callers#

  • The research-production gap comes from re-implementing the signal, different warm-up, hand-typed parameters, bar-open vs bar-close timestamps, full-series vs last-bar maths.
  • "There is exactly one implementation of the signal, and everything else calls it." Backtest calls signal(df) on history; live calls it on a trailing window and takes the last value. Parameters live in one config both read.
  • Parity test: NIFTY 20/50 SMA cross on 862 bars: 14 flips, and the live path on a 250-bar window gave the same SHORT decision and matched the last 120 overlapping bars. Re-run it daily; divergence usually means a data revision, library upgrade or timezone change.
  • Version code (commit), parameters (config) and data window, so every live trade traces to them and rollback to the last known-good is one step.
  1. Research: most ideas die
  2. Backtest: shared signal, point-in-time data, honest costs
  3. Sandbox: live data, simulated broker (analyzer mode)
  4. Paper-to-small: real orders, tiny size, real slippage
  5. Full size: only when live matches the backtest within tolerance
Check yourself 2 questions
  1. Name two causes of the research-production gap.

    Show answer

    Any two of: re-implemented signals, different warm-up, hand-typed parameters, bar-open versus bar-close timestamps, full-series versus last-bar maths.

  2. What's the fix?

    Show answer

    One shared signal implementation that everything calls.

Takeaway Exactly one implementation of the signal, called by both research and production, with a daily parity test.

Live system design: OMS, PMS and recovery#

FillSideQtyPricePositionAvg costRealised
1BUY1001328.101001328.100
2BUY1001309.502001318.800
3SELL1501326.50501318.80₹1,155
4SELL501309.500–₹690
5BUY2001313.602001313.60₹690
6SELL2001318.100–₹1,590
  • The OMS owns each order's life; the PMS owns positions (signed qty, average cost, realised P&L); a fill is the only event crossing between them. Pre-trade risk and the kill switch sit in front of the gateway; an append-only event log is the recovery store.
  • Average-cost accounting: same-side fills re-weight the average; opposite-side fills realise P&L at the average; a flip closes the old lot and opens the rest at the fill price. After fill 2 the book showed ≈ ₹1,860 unrealised loss with nothing realised, so apply risk limits to realised + unrealised.
  • Process events serially through one consumer (deterministic, backtest-like) with bounded queues. Give every order a unique client order ID so a resend is a no-op; on a timeout, query status, never blindly resend.
  • On restart, replay the log, then reconcile with the broker before trading: the broker wins on fills, your log on intent. Standby process, heartbeats, kill switch: whenever the system is unsure, stop trading.
Check yourself 2 questions
  1. Buy 100 at 1328.10 and 100 at 1309.50: average cost?

    Show answer

    1318.80.

  2. Does selling part of a position change average cost?

    Show answer

    No; it realises P&L on the part sold.

Takeaway The OMS tracks orders, the PMS tracks positions, average cost and realised P&L; recovery replays the event log.

The order state machine#

flowchart TD
  P["Pending"] --> SU["Submitted"]
  SU --> O["Open"]
  SU --> RJ["Rejected"]
  O --> PF["Partially filled"]
  O --> C["Complete"]
  PF --> C
  O --> CX["Cancelled"]
  PF --> CX
  O --> EX["Expired"]

Complete, cancelled, rejected and expired are terminal: nothing may happen after them. A fill arriving on a cancelled order is a race or a bug: detect and investigate it, don't apply it. Persist every transition.

Check yourself 2 questions
  1. Name the four terminal states.

    Show answer

    Complete, cancelled, rejected, expired.

  2. Can a rejected order become open?

    Show answer

    No. Terminal states don't move.

Takeaway Pending, submitted, open, partially filled; complete, cancelled, rejected and expired are terminal.

Monitoring, reconciliation and incidents#

  • Live monitor every few seconds: net P&L (realised + MTM), positions, exposure vs limits, fills and rejects, feed staleness, strategy heartbeat, shown beside the broker's view. Divergence is the danger signal.
  • "A limit you do not alert on is a comment, not a control." RELIANCE long 500 with a −₹2,500 day limit: breached at 14:40 (low −₹2,800) → alert and halt new orders.
  • Reconcile trades, positions and cash: intraday every few minutes, end of day against contract notes. A break example: internal +1,000 shares vs broker +1,500 (₹6.6 lakh): one fill lost by the feed handler.
  1. Stabilise: halt; flatten or hedge to the broker's position
  2. Diagnose: rebuild the timeline from logs
  3. Fix the root cause
  4. Resume only after a clean reconciliation

Blameless post-mortems end in a specific new control, never "be more careful". Every good control is a scar from a past incident.

Check yourself 2 questions
  1. What's the key danger signal in monitoring?

    Show answer

    Divergence between your view and the broker's.

  2. What should every limit have?

    Show answer

    An alert.

Takeaway Monitor P&L, positions, limits, feeds and heartbeats beside the broker's view; a limit you don't alert on is a comment.

SEBI compliance, ethics and the quant career#

  • SEBI governs algo trading: algos route through registered brokers with approvals, unique strategy IDs and mandatory controls (price and quantity limits, kill switches). The retail framework keeps evolving: read the latest circulars.
  • Red lines: spoofing, layering, pump-and-dump, front-running, and reckless strategies that destabilise thin stocks. "I can" is not "I should".
  • Homes: sell-side, buy-side, prop, HFT. Roles: researcher, developer, trader. Interview pillars: probability puzzles, coding, statistics and ML, markets and products.
  • Puzzle habit: break a stick at two random points; the chance the pieces form a triangle is 1/4, and 500,000 simulations give ≈ 0.2497. Expected flips until two heads in a row: 6. When maths is hard, simulate; then verify.
  • Break in with an honest strategy, a clean out-of-sample record, sandbox history and open-source work: intellectual honesty is the credential.
Check yourself 2 questions
  1. Name two red lines.

    Show answer

    Any two of: spoofing, layering, front-running, insider trading.

  2. Why read the latest SEBI circulars?

    Show answer

    The retail algo framework keeps evolving.

Takeaway Algos route through registered brokers with approvals, IDs and kill switches; spoofing and layering are red lines.

Capstone: one idea, judged honestly#

NIFTY above its 50-day SMA, vol-targeted to 12%, 2 bps costsSharpeCAGRMax drawdown
Strategy, in-sample (first 60%)+0.87+11.2%−20.1%
Strategy, out-of-sample (last 40%)+0.23+2.3%−13.6%
Buy and hold, out-of-sample+0.71+8.9%−15.8%
  • Pipeline: falsifiable hypothesis (trends persist) → clean point-in-time data → signal sign(close − SMA50) lagged a day → size = (0.12 / √252) ÷ 20-day std, capped at 2×, lagged → costs on every change → out-of-sample verdict.
  • Full period: strategy 1.67× vs buy-and-hold 2.20×. After costs it lost to simply holding the index, and the in-sample 0.87 → 0.23 drop says overfit or decay.
  • "The out-of-sample line, net of costs, is the only verdict that counts." Killing an idea cheaply is a success; durable edges usually come from market-neutral, multi-factor, event and volatility strategies combined into a diversified book.
Check yourself 2 questions
  1. Out-of-sample Sharpe: strategy versus buy-and-hold?

    Show answer

    About 0.23 versus 0.71.

  2. What's the honest verdict?

    Show answer

    Not worth trading: it lost to buy-and-hold out of sample.

Takeaway The 50-day SMA strategy looked good in sample but lost to buy-and-hold out of sample.

10Checklists and quick reference

The whole course compressed into checks you can run.

Research checklist#

  1. Hypothesis is precise and falsifiable, with an economic reason (who pays, and why).
  2. Data is point-in-time, survivorship-free and corporate-action adjusted.
  3. Every signal is lagged; fills at the next open, paying at least half the spread.
  4. Full Indian cost stack plus impact, sized at the capital you intend to run.
  5. Every trial logged; Sharpe deflated or corrected (Holm / BH) for the search.
  6. Purged walk-forward, judged on the whole fold distribution vs a benchmark.
  7. Enough trades; a curve with real drawdowns; capacity and half-life estimated.
Check yourself 2 questions
  1. What economic question should a hypothesis answer?

    Show answer

    Who pays, and why.

  2. Where do fills happen in the checklist?

    Show answer

    At the next open, paying at least half the spread.

Takeaway Falsifiable hypothesis with an economic reason, point-in-time data, lagged signals, full costs, corrected for multiple tests.

Production checklist#

  1. One shared signal module and one config; a daily parity test.
  2. Pre-trade gate: latched kill switch, rupee loss and position limits, rate throttle.
  3. Unique client order IDs; query on timeout, never resend blindly.
  4. Append-only event log; replay then reconcile with the broker on restart.
  5. Live monitor with alerts wired to every limit; intraday and end-of-day reconciliation.
  6. Registered algo ID, static IP, guarded API key; OTR within budget.
  7. Sandbox → paper-to-small → full size, with versioned rollback.
Check yourself 2 questions
  1. On a timeout, should you resend the order?

    Show answer

    No: query with the unique client order ID first.

  2. How does recovery work?

    Show answer

    Replay the append-only event log, then reconcile with the broker.

Takeaway One signal module and config, a pre-trade gate, unique order IDs, an append-only log, and reconciliation.

Formulas to keep#

log return = ln(P_t / P_(t−1)) Sharpe = mean / std × √252P(any false hit) = 1 − 0.95^N Bonferroni: α / Nimpact ≈ 0.5 · σ · √(order / ADV) half-life = ln 2 / κGARCH: σ²_t = ω + α·ε²_(t−1) + β·σ²_(t−1)fair future = spot + financing − income · carry = ln(F/S) / TF = K + e^(rT)(C − P) 1-day move ≈ S·VIX/100/√252OTR = messages ÷ trades inverse-vol w_i ∝ 1/σ_iVaR: loss not exceeded · CVaR: mean loss beyond VaR
Check yourself 2 questions
  1. Probability of any false hit in N tests at 5%?

    Show answer

    1 − 0.95^N.

  2. Annualised Sharpe from daily returns?

    Show answer

    Mean ÷ std × √252.

Takeaway Log returns, Sharpe, false-hit probability, Bonferroni, square-root impact, half-life, GARCH and carry.

About this sheet#

This sheet condenses the free 78-chapter course Quantitative Trading from OpenAlgo Open Varsity (9 modules) into reference cards in our own words. Numbers come from the course's live runs on mid-2026 NSE, NFO and MCX data via OpenAlgo; rates, thresholds and rules cited are the course's and change over time, so check current SEBI and exchange circulars. Each section links back to its chapters. Educational, not investment advice.

Numbers that expire#

Every figure on this sheet that a regulator, exchange or budget can change, with when it last changed. Last checked 15 Nov 2026; verify before trading.

WhatCurrent valueAs of
NIFTY lot size65 (was 75)from the Jan 2026 expiries · source
BANKNIFTY lot size30 (was 35)from the Jan 2026 expiries · source
Index option expiry dayNSE: Tuesday (weekly NIFTY, monthly last Tuesday) · BSE: Thursdaysince Sep 2025 · source
STTdelivery 0.1% both sides · intraday 0.025% sell · futures 0.05% sell · options 0.15% of premium sold, 0.15% of intrinsic on exercisefrom 1 Apr 2026 (Budget 2026) · source
Equity tick size for stocks priced ₹1,000–5,000₹0.10 (price-band ticks)from 15 Apr 2025 · source
Closing auction (F&O stocks) and derivatives hours3 Aug–6 Dec 2026: continuous trading to 15:15, auction to 15:35, derivatives to 15:40 · from 7 Dec 2026: continuous to 15:30, auction 15:30–15:40 (matching to 15:45), derivatives to 15:45 (expiring index contracts stop 15:30)SEBI circular of 15 Oct 2026 · source
Market-wide circuit breakers10%, 15% and 20% index movesunchanged since 2001 · source
Retail algo frameworkMandatory from 1 Apr 2026: whitelisted static IP, daily 2FA, algo ID for strategies at 10+ orders per second per segmentSEBI circular 4 Feb 2025, deadline 1 Apr 2026 · source
No cards match. Try fewer or different words, or press Esc to clear.