Advanced8-12 min readTopic 20 of 20

    Machine Learning in Trading — A Reality Check

    Rohit Singh

    Mr. Chartist · SEBI RA

    Module Progress
    0/20
    Module

    Machine learning is a method for finding structure in features you chose, mapped to a label you defined. That is the whole of it. It is not a price oracle, it does not read charts, and it has no view on anything you did not put in the columns. Most retail machine-learning trading fails long before the model is fitted — not because the algorithm was weak, but because the problem was framed in a way that could not have worked: a label nobody thought about, features that quietly knew the future, a validation scheme borrowed from a domain where the rows are interchangeable, and costs left out of the arithmetic. This closing topic is about that framing, because the framing is where the outcome is decided.

    The fitting step is the small box. The universe, the features, the label, the validation design and the costs are where a study is won or lost — and all of them happen before the model runs.Five large blocks carry the real work: building a point-in-time universe, choosing features that are knowable at the decision moment, defining the label, designing walk-forward validation, and subtracting realistic costs. A single small block, drawn a fraction of the size, is the step of fitting the model itself. An arrow notes that swapping the model changes only the small block.The model is the small boxblock size drawn to match where the work is1Universepoint-in-time, delisted names kept2Featureschosen by you, knowable at the decision moment3Labelthe question you decided to ask4Validationwalk-forward, purged, embargoed5Costsbrokerage, STT, impact, taxesFit the modelan afternoonswap the model class-> only this box changesA study that fails does not usually fail in the small box. It fails in blocks one to five, before the fitting starts.No model class is being recommended here, and none of these blocks makes a strategy work.
    The fitting step is the small box. The universe, the features, the label, the validation design and the costs are where a study is won or lost — and all of them happen before the model runs.

    What is machine learning in a trading context?

    Supervised learning has three parts. A feature is an input column, one value per row. A label is the outcome you are asking the model to predict, and it must be computable for past data. Training is the fitting process: the algorithm adjusts its internal numbers until its output on the training rows sits as close as it can to the labels you supplied.

    That is all it does. It has no concept of a market, no idea what a stock is, and no interest in whether the relationship it found makes any economic sense. It reduces error on the rows you handed it, using whatever in the columns helps — including things that should never have been in there.

    The AI module builds this vocabulary properly, including the difference between a supervised model and a language model, and the three defects that ruin studies. This topic assumes those and asks the systematic-trading question instead: given that machine learning is this and not something grander, where does it actually earn its place in a trading process?

    What machine learning is not

    • It is not a forecaster of price. Ask it for tomorrow's close and you have asked a question whose answer is dominated by things nobody knows today.
    • It is not a substitute for a hypothesis. A model handed columns with no reason to be there will find a relationship anyway, because searching hard enough over noise always finds something.
    • It is not a chart reader. It sees the numbers you engineered from the chart, in the form you engineered them. The picture never reaches it.
    • It is not more objective than you. Every choice that matters — universe, features, label, horizon, validation split — was made by a human, and the model inherits all of them.
    • It is not an upgrade over a simple rule. A rule you can state in one sentence has a property no fitted model has: you can tell, from the outside, why it did what it did.
    • It is not exempt from costs. A relationship that exists before brokerage, STT, exchange charges, GST, stamp duty and impact is not a relationship you can trade.

    Where does machine learning genuinely fit?

    There is a narrow set of jobs where it earns its keep, and none of them is prediction of a price. Note the framing throughout: these are places the tool is appropriate, not places it is claimed to work. Whether any of them produces something tradeable is a question only your own validated study can answer, and for most people the answer will be no.

    JobWhy the shape suits itWhat still has to be true
    Ranking a large universeOrdering 1,800 listed names by a score is a task humans do badly and consistentlyThe score must survive out-of-sample, and the names at the top must be liquid enough to exit in one order
    Classifying a condition you already defined'Did this resolve up before it resolved down' is a checkable historical questionThe definition must come from the rulebook, not from whatever the data made easy
    Flagging anomalies in your own dataStale prices, missing rows, unadjusted corporate actions have a detectable shapeNothing — this is the one use with no market assumption in it, and it is the most useful
    Estimating your own execution costYour fills are your data, they are plentiful, and the target is not adversarialEnough of your own live orders to fit on, which most retail traders do not have
    Labelling market conditionsA compact description of the environment can feed a rule you wrote separatelyThe labels must be defined in advance, or you have built a very expensive way to describe the past
    Predicting tomorrow's priceNothing about the shape suits itThis is not a job on the list, and treating it as one is where most projects die

    Why is feature engineering the real work?

    The model class is a small decision. The columns are the whole study, because a model can only find structure that is present in what you gave it.

    A feature is not merely a measurement. It is a claim: 'this quantity, computed this way, at this moment, plausibly carries information about the outcome I defined.' Every column should be traceable to a sentence of that form, written down before the column exists. Columns added because they were easy to compute are how a feature set becomes a search over noise.

    The timing property
    The defining property of a feature is not what it measures but when it becomes knowable. For every column, you must be able to state the exact moment its value exists in final form, and confirm that moment is before the decision moment. Anything else is look-ahead, and look-ahead produces a beautiful study and a live account that behaves nothing like it.
    Stationarity of the column itself
    A raw price level is a poor feature: ₹180 meant something different five years ago than it means now, and the model has no way to know that. Quantities expressed as ratios, distances relative to a recent range, or normalised against the instrument's own recent behaviour travel better across time — though normalising against statistics drawn from the whole sample reintroduces the future through the back door.
    Redundancy
    Twenty columns that are all rearrangements of the same recent price give you one feature and nineteen opportunities to overfit. Effective information, not column count, is what limits how complex a model your data can support.
    Economic reason
    For each feature, why would this carry information about the outcome? If the honest answer is 'the search picked it', you have a correlation with no reason to persist — and relationships without a reason are exactly the ones that disappear first.

    Why does the label decide everything?

    Two studies with the same universe, the same features and the same model can reach opposite conclusions because they labelled the outcome differently. The label is not a formality applied at the end. It is the question, and the question decides the answer.

    A return over the next twenty candles is a hard label: it is dominated by noise, one enormous move can carry an entire study, and the model spends its capacity fitting outliers. A categorical label is usually more honest, because it asks something the data can answer cleanly.

    Consider a label defined as: from the signal candle, did price first close above a level a fixed distance above entry, or first close below a level a fixed distance below it, within a fixed number of candles — and if neither, the outcome is recorded as neither. That definition has three parameters hidden inside it. Move the upper distance and the balance of the classes changes. Move the horizon and a different set of situations resolves. Each choice produces a different question, and therefore a different study.

    Watch out — Once you start adjusting the label because the results were disappointing, you are searching over label definitions — an unlogged search, invisible in the final study, and the most efficient way to overfit that exists. Fix the label from the rulebook before you fit anything, and record every alternative you tried.

    How small is the signal really?

    This is the part that separates market work from the domains where machine learning looked miraculous. Signal is the portion of a future move genuinely related to something knowable now. Noise is everything else — a fund rebalancing on a schedule you cannot see, order flow, a headline nobody could have anticipated.

    In handwriting recognition, almost all the information needed is in the image. In market data the noise dominates heavily, and weak signal has a direct consequence: you need far more independent examples to separate a real relationship from a coincidence. Market data supplies far fewer independent examples than the row count suggests, because consecutive rows on the same stock share most of their story.

    Schematic, with no scale on anything. Two problems that look alike to the algorithm and are nothing alike in practice — a wide signal against a still target, versus a sliver of signal against a target that moves because you aimed at it.Two panels compared schematically with no numeric scale. In the domains machine learning transformed, a wide signal segment fills most of the bar and the remainder is noise, and the target is stationary. In market data the signal segment is a thin sliver at the left of the bar and noise fills the rest, and the target itself moves in response to being studied.The same method, two very different problemsWhere ML transformed the fieldhandwriting, speech, imagessignalnoiseDoes the target stay still?The target sits still - a written seven is a seven next yearIndian equity and derivative dataNSE / BSE prices, one row per stock per weeksignalnoiseDoes the target stay still?The target moves, and it moves because you aimed at itWeak signal means you need far more independent examples - and consecutive rows on one stock are not independent.Twenty years of daily bars is a few thousand rows and a handful of genuinely distinct market conditions.
    Schematic, with no scale on anything. Two problems that look alike to the algorithm and are nothing alike in practice — a wide signal against a still target, versus a sliver of signal against a target that moves because you aimed at it.

    What does non-stationarity do to a fitted model?

    Supervised learning rests on an assumption that is invisible in most fields because it is simply true there: the relationship fitted on past data still holds on future data. Markets violate it routinely. Volatility clusters and subsides. Leadership rotates. A relationship that held across one long stretch inverts. A change in market mechanics quietly rewrites the thing your model spent its training fitting.

    And unlike a handwritten digit, the subject responds to being studied. A market is made of participants, some with better data and lower costs than you, and a simple findable pattern that pays reliably gets traded until it stops paying. The relationship is adversarial, and adversarial relationships decay — which is why the previous topic in this module exists, and why a market model is never finished.

    The operational consequence is uncomfortable: the shelf life is real, it is unknown in advance, and nothing errors when it expires. The code runs exactly as it always did and the results simply get worse.

    Why is cross-validation as taught wrong for market data?

    Standard k-fold cross-validation shuffles the rows, splits them into folds, and rotates which fold is held out. It is correct, and it is correct because it assumes the rows are independent and interchangeable. Market rows are neither.

    Shuffle a time series and you fit on later blocks while scoring on earlier ones — the model is told the future and graded on the past. Worse, a label that resolves over the following candles overlaps in time with rows placed in the test fold, so information leaks across the boundary even when the split looks clean.

    Above, folds assigned as though the rows were interchangeable — several test blocks sit earlier in time than the training blocks. Below, an expanding walk-forward with a purge-and-embargo gap so an overlapping label cannot cross the boundary.The upper strip shows ten time-ordered blocks with test blocks scattered among training blocks, as standard cross-validation for independent data would assign them. Several test blocks sit earlier in time than training blocks, so the model is fitted on the future and scored on the past. The lower diagram shows four walk-forward rounds instead: each fits on an expanding block of history, leaves a purge and embargo gap, and scores on the block that comes immediately after.Cross-validation as taught assumes the rows are interchangeableSHUFFLED K-FOLD - WRONG HEREtrainTESTtraintrainTESTtrainTESTtraintrainTESTtime runs left to rightfitted on later blocks, scored on earlier onesWALK-FORWARD, PURGED AND EMBARGOEDfit on history to hereTESTfit on history to hereTESTfit on history to hereTESTfit on history to hereTESTDASHED GAP = PURGE + EMBARGOa label that resolves over thenext N candles overlaps thetest block unless you cut it outIndependent rows may be shuffled. Market rows carry the next row inside them, so shuffling scores the model on its own training data.
    Above, folds assigned as though the rows were interchangeable — several test blocks sit earlier in time than the training blocks. Below, an expanding walk-forward with a purge-and-embargo gap so an overlapping label cannot cross the boundary.

    What does a defensible validation design look like?

    1. 1

      Split by time, never by row

      Every fold boundary is a date. The training block always ends before the test block begins, on every round, without exception.

    2. 2

      Purge the overlap

      If your label resolves over the next N candles, drop the training rows whose labels extend into the test block. Without this, the model has seen the outcome period it is about to be graded on.

    3. 3

      Add an embargo after the test block

      Leave a gap before training resumes, so serial dependence across the boundary cannot carry information back. The gap costs you data and buys you a result that means something.

    4. 4

      Walk the windows forward

      Fit, test on the block immediately after, roll forward, repeat. This mirrors how the strategy would really have been run — refitted periodically, always applied to data that came later — instead of assuming one fit held across two decades.

    5. 5

      Build the universe point-in-time

      The list as it stood on each historical date, including the names that later delisted or left the index. Testing on today's constituents embeds years of knowledge about which companies survived, and it flatters exactly the strategies that lean on the weakest names.

    6. 6

      Subtract costs inside the loop

      Brokerage, exchange transaction charges, STT, stamp duty, GST and a realistic impact assumption, applied per decision — not deducted from the total at the end, where they quietly stop interacting with the trading frequency that generated them.

    7. 7

      Open the final held-out block once

      Choices belong to the validation windows. The moment you use the final block to select anything, you have become the optimiser and it has become training data by proxy.

    8. 8

      Log the attempt count

      Every variant tried is a hidden test. The one you kept is the best of everything you tried, and the best of many noisy results is flattering by construction. The attempt count is part of the result.

    How do costs change the arithmetic?

    A relationship that exists gross and vanishes net is not a finding. The frequency of the model's decisions is what decides whether costs are a rounding error or the entire story, and a machine-learning model producing a score for every name every day can be pushed into very high turnover without anyone noticing.

    Net edge per decision = gross edge per decision − (round-trip cost + impact)
    • Gross edge per decision — the average result the study produces before any deduction.
    • Round-trip cost — brokerage both ways, exchange transaction charges, STT, stamp duty and GST on the applicable components.
    • Impact — the distance between the price your study assumed and the price you actually get, which widens with size and in less liquid names.
    • If this is negative, no amount of model tuning fixes it. The frequency has to fall, or the idea stops.

    Example — Illustrative arithmetic with round numbers, not a real result. On a ₹1,00,000 position, assume round-trip costs and impact together consume ₹250. A model producing four decisions a week on that position must clear roughly ₹52,000 of gross edge across a year before a single rupee reaches you. The same gross edge at four decisions a month faces about a twelfth of that. Turnover, not model quality, is often the binding constraint.

    Why does interpretability matter more here than elsewhere?

    In most applications, a model that performs is enough — nobody demands an explanation from a spam filter. In systematic trading the explanation is load-bearing, and the reason is the previous topic in this module.

    When a strategy enters a bad stretch, you have to decide whether the conditions it depends on are currently present. For a rule you can state in one sentence, that is a checkable question: you named the conditions when you wrote the rule. For a fitted model with hundreds of interacting parameters, there may be no sentence to check. You cannot say what the method needs, so you cannot ask whether it is there, so the only evidence available is the recent result — which is precisely the evidence you already know not to act on.

    That is a real cost and it belongs in the decision about whether to use a model at all. A slightly weaker approach whose behaviour you can articulate is often the more usable one, because it survives contact with a drawdown. The opaque one leaves you with nothing to do but watch and hope, and hoping is not a maintenance procedure.

    Note — Before fitting anything, write down what conditions the approach needs in order to have a chance. If the model class you are considering makes that sentence impossible to write, you have chosen a method you will not be able to diagnose later. That is a legitimate reason to choose differently.

    What is different about doing this on Indian markets?

    • Point-in-time constituent history for NSE indices is genuinely hard for a retail researcher to obtain. When you cannot get it, shrink the claim rather than ignoring the problem: record in your notes that the universe is survivorship-affected and treat the result as an upper bound.
    • Corporate actions — splits, bonuses, rights, demergers — change the raw price series. An unadjusted series produces features that are pure artefact, and the artefact is largest on exactly the dates that matter.
    • Daily price bands can freeze a stock for the session. A model that assumes a fill at any price it likes has assumed a market that was not open to it.
    • Derivative contract specifications are revised. Lot sizes, expiry days and available strikes change, so a study spanning a revision is measuring two different instruments under one name.
    • Liquidity thins sharply below the large-cap band. A ranking model will happily place illiquid names at the top of its list, where the impact cost is largest and your exit is a multi-order problem.
    • SEBI's framework for how retail algorithms reach the exchange, covered earlier in this module, governs what you may actually deploy. A model that validates cleanly and cannot be deployed compliantly is a research exercise, and should be labelled as one.

    Why does most retail machine-learning trading fail before it starts?

    Not because the model was weak. The models are commodities now — the same libraries a fund uses are a free download, and the difference in fitted quality between a well-known model class and a clever one is small next to everything else in this article.

    It fails because the problem was framed in a way that could not have worked. The label was never defined from a rulebook, so the study answered a question nobody asked. A feature knew the future by a few hours. The universe was assembled this morning. The validation shuffled rows that carry each other inside them. Costs were subtracted at the end, or not at all. The variant kept was the survivor of a search nobody counted. Each of those is fatal on its own, and the study will not error on any of them — it will produce a number, in the right format, with a chart attached.

    The honest summary is that machine learning does not lower the bar for a trading idea. It raises it, because it adds several new ways to be confidently wrong on top of every way that already existed. If you cannot state your hypothesis in one sentence that names a cause, a model will not supply the sentence for you. It will only fit whatever you gave it, and report back with complete confidence.

    What would invalidate a machine-learning study?

    State the kill conditions before running anything, in the same document as the hypothesis.

    • Any feature that cannot be shown to be knowable at the stated decision moment, in final form, without later revision.
    • A result that survives only at one narrow parameter setting and degrades sharply on either side — a fitted peak in the noise rather than a plateau.
    • A result that disappears when the largest few outcomes are removed, meaning the study rests on a handful of situations rather than a tendency.
    • A result that does not survive realistic costs applied per decision at the model's actual turnover.
    • A validation scheme with no purge or embargo where the label resolves over multiple candles.
    • A universe assembled from today's listings, when the claim being made is about a historical period.
    • An unlogged number of attempts. If you cannot say how many variants preceded this one, the result has no denominator.
    • No stated economic reason for any feature that the model leaned on. A relationship without a reason has nothing making it persist.

    The pre-flight checklist

    Answer all of these before fitting anything

    • What is the hypothesis, in one sentence, naming a cause?
    • What is the exact decision moment, and is every feature knowable at it?
    • What is the label, why that definition, and what alternatives did you consider?
    • How was the universe built, and does it include names that delisted or left the index?
    • Are corporate actions adjusted, and did you verify three of them by hand?
    • Does the validation split by time, purge overlapping labels and embargo after each test block?
    • Are costs applied per decision, inside the loop, at the model's real turnover?
    • How many variants have you tried, and is that number written down?
    • What result would make you abandon this idea, stated before you see any result?
    • If this validates, can it be deployed compliantly — and if not, is it labelled as research only?

    Note — This page is education, not advice. It recommends no model class, no library, no data vendor and no strategy, and nothing in it is a claim that any approach described here produces a result.

    Key points

    Machine learning finds structure in features you chose, mapped to a label you defined. It is not a price oracle.
    The model class is the small decision; the universe, features, label, validation and costs are the study.
    A feature's defining property is when it becomes knowable, not what it measures.
    The label is the question, and changing it changes the answer — fix it from the rulebook before fitting.
    Signal in market data is small and noise dominates, so far more independent examples are needed than the row count implies.
    Markets are non-stationary and adversarial: a findable pattern that pays gets traded until it stops paying.
    Shuffled k-fold assumes interchangeable rows and leaks the future — split by time, purge and embargo instead.
    Build the universe point-in-time, including names that delisted or left the index.
    Costs go inside the loop, per decision. Turnover is often the binding constraint, not model quality.
    Every variant tried is a hidden test; the kept variant is the best of them, and the attempt count is part of the result.
    Anomaly detection in your own data is the one use with no market assumption in it, and often the most useful.
    Most retail machine-learning trading fails on problem framing, before the model is ever fitted.

    Pro tip — Write the one-sentence hypothesis, the label definition and the kill conditions in a file, and date it, before you load any data. If you cannot write that sentence — if the plan is to give the model some columns and see what it finds — then you do not have a study, and the model will not give you one. It will fit whatever you handed it and report back with total confidence, which is the one thing it is guaranteed to do well. This closes the module. Nothing in it is investment advice, and none of it makes a strategy work; it only makes the ways of being wrong visible earlier and more cheaply.

    Frequently asked questions

    Does machine learning work for stock market prediction?

    Not as a price oracle, and framing it that way is where most projects fail. It is a method for finding structure in features you chose, mapped to a label you defined. Whether a particular study finds something that survives out-of-sample testing and realistic costs is a question only that study can answer — and the honest position is that most retail attempts do not, because the framing was wrong before the model was fitted.

    Why do machine learning trading models fail?

    Almost always in the framing rather than the algorithm: a label defined after the fact, a feature that quietly knew the future, a universe assembled today and tested on a decade ago, validation that shuffled rows which carry each other inside them, costs subtracted at the end, and an uncounted number of variants tried. Each of those is fatal on its own, and none of them produces an error message.

    What is feature engineering in trading?

    It is choosing and constructing the input columns a model sees. Each column should be traceable to a written claim that this quantity, computed this way, at this moment, plausibly carries information about the outcome you defined. The defining property of a feature is not what it measures but when its value becomes knowable — which must be before the decision moment.

    Why is cross-validation wrong for time series data?

    Standard k-fold assumes rows are independent and interchangeable, so it shuffles them. Market rows are neither. Shuffling fits the model on later blocks and scores it on earlier ones, and a label that resolves over the following candles overlaps rows in the test fold. The alternative is a walk-forward that splits by date, purges training rows whose labels extend into the test block, and embargoes a gap after it.

    How much data do I need for a machine learning trading model?

    More than the row count suggests, because consecutive rows on the same stock are not independent events. Twenty years of daily bars on one name is a few thousand rows containing a handful of genuinely distinct market conditions. Weak signal raises the requirement further — the weaker the relationship, the more independent examples are needed to separate it from coincidence.

    Is deep learning better than simple models for trading?

    Model capacity is rarely the binding constraint. With weak signal and few genuinely independent examples, extra flexibility mostly buys extra ways to memorise noise. A simple rule also has a property no fitted model has: you can tell from the outside why it did what it did, which matters enormously when you are deciding whether a bad stretch is normal or terminal.

    Can I use machine learning for trading on NSE and BSE?

    The methods are not country-specific, but the data problems are. Point-in-time index constituent history is hard to obtain, corporate actions must be adjusted or your features are artefacts, daily price bands can freeze a stock so an assumed fill never existed, and derivative contract specifications get revised mid-history. SEBI's framework also governs what may actually be deployed, so a validated model is not automatically a deployable one.