Intermediate5-8 min readTopic 5 of 20

    Python for Trading — Getting Started

    Rohit Singh

    Mr. Chartist · SEBI RA

    Module Progress
    0/20
    Module

    Python is the language most systematic traders end up in, and the reason is unglamorous: it has the best free tools for holding a table of prices, doing arithmetic on it, and drawing it. That is nearly the whole job. What Python does not do is supply the idea, clean the data, or make you sit still through a losing run — and those, not the syntax, are the parts that take years. This page covers the small handful of libraries that matter, the one habit that separates working code from subtly broken code, and the four programs a beginner should write before ever writing a strategy.

    Four layers make up a research toolchain — fetch, hold, compute, look. The panel on the right is the part no library ships with.Four stacked layers describe a research toolchain: fetching data, holding it in a table, doing arithmetic on columns, and plotting it. A panel on the right lists three things the toolchain does not supply - an edge, clean data, and the discipline to keep running the system.What the toolchain actually isFour layers. Most beginners try to skip straight past all of them.1Where the data comes fromexchange files, a broker API, a paid vendor, a scraped CSVrequests / csv2Where it is held and shapedone table indexed by timestamp - resample, align, joinpandas3Where the arithmetic happenscolumns of numbers, operated on whole, not row by rownumpy4Where you look at ita chart you drew yourself, so you can see what brokematplotlibNot includedan edgethe idea is still yoursclean datasee the next topicthe discipline to leave it runningLearning the syntax is a few weekends. Everything above and below it is the rest of this module.
    Four layers make up a research toolchain — fetch, hold, compute, look. The panel on the right is the part no library ships with.

    Why Python, and not something else?

    There is no property of Python that makes markets more tractable. Traders use it because the ecosystem around data tables happens to be excellent and free, because the same script that pulls an NSE bhavcopy can plot it and later call a broker's REST API without leaving the language, and because when you get stuck, someone has already asked your question in public.

    Excel and a no-code screener remain perfectly legitimate tools, and the previous topic in this module makes the case that you should be systematic long before you are programmatic. Python earns its place at exactly one point: when your process needs to run over three thousand NSE and BSE symbols, over ten years, the same way every time, and you need to be able to show yourself what it did.

    That is a workflow argument, not a performance argument. Nobody's returns improved because they switched language.

    Note — This page is education, not advice, and nothing here is a recommendation to buy or sell any security. No library, data source, broker or course is being endorsed — where a category of tool is described, choosing inside that category is your own due diligence.

    Which Python libraries actually matter?

    The list is much shorter than most course syllabi suggest. You can do serious research with four things.

    LibraryWhat it is forWhen you first need it
    pandasThe table. Holds OHLCV indexed by timestamp; resamples, aligns, joins, shifts.Day one. This is the library you are really learning.
    numpyThe arithmetic underneath pandas. Arrays and vectorised maths.Quietly, from day one — explicitly once you write your own calculations.
    matplotlibDrawing. Unfashionable, ships everywhere, and enough to see what broke.As soon as you have one series loaded. Look at the data before testing it.
    requestsTalking to an HTTP endpoint — a data source or, much later, a broker API.When your data stops arriving as a file on disk.
    A backtest frameworkReady-made event loop, position tracking and reporting.Later than you think. Write a crude loop yourself first so you know what it hides.
    Machine learning stacksModel fitting on engineered features.Last, if ever. Covered at the end of this module, deliberately.

    What does market data look like once it is in Python?

    Almost everything you will write is a transformation of one shape into another shape. That shape is a table with a timestamp index and, usually, five columns.

    The index is the part beginners under-respect. It is not a row number — it is a real point in time, and it is what makes it possible to align two instruments that did not trade on exactly the same days, to convert a daily series into a weekly one, or to shift a column back by one candle so a decision is only allowed to see the past.

    An OHLCV table with a timestamp index. The values are an illustrative synthetic series, not a real instrument on a real date.A four-row price table with a timestamp index and columns for open, high, low, close and volume, using an illustrative synthetic series. Three notes below explain that the index is a timestamp rather than a row number, that one row is one completed candle, and that volume is the field most often wrong.One table, indexed by timeillustrative seriesdate (index)openhighlowclosevolume2021-04-05412.00419.80409.15417.608,42,1002021-04-06418.00424.50415.30416.056,19,5402021-04-07415.50415.90398.20401.7519,08,7302021-04-08403.00408.60400.10407.907,74,220The index is a timestamp, not a row number. Every join, resample and shift depends on it.One row is one completed candle. A row for today, mid-session, is not the same object.Volume is the field that most often arrives wrong or missing - check it before you trust it.Almost everything you will write is a transformation of this shape into another one.
    An OHLCV table with a timestamp index. The values are an illustrative synthetic series, not a real instrument on a real date.

    What is vectorised thinking, and why does it matter more than speed?

    Every beginner writes their first calculation as a loop: walk the table one row at a time, compute something, append it to a list. It works. It is also the wrong mental model, and the speed argument everyone makes for the alternative is the least important reason to change.

    The better form treats a column as one object. You do not ask 'what is the range of row 47'. You ask for the range of every candle at once, as a single expression.

    df['range'] = df['high'] - df['low']
    • df — the OHLCV table, indexed by timestamp.
    • df['high'], df['low'] — whole columns, not single values.
    • The result is a new column of the same length, aligned to the same index automatically.

    Why is a row loop dangerous rather than just slow?

    Because a loop that has the whole table in scope will happily let you read row 48 while you are pretending to stand at row 47. That is look-ahead bias, it produces beautiful nonsense, and nothing in the language warns you.

    Column operations do not make this impossible, but they make it visible. When the only way to reference yesterday's value is an explicit shift, the shift is right there in the code for you or a reviewer to check. The next topic in this module is entirely about the family of errors this belongs to.

    The same calculation written twice. The second version is not merely shorter — it removes the place where a subtle time-travel bug likes to hide.The same calculation - the range of each candle - written twice. On the left, five lines that walk the table one row at a time. On the right, a single line that subtracts one whole column from another. Below, a note that the second form is not just shorter but harder to get subtly wrong.Stop thinking in rowsBoth blocks compute the same thing: how far price travelled inside each candle.ROW BY ROWrng = []for i in range(len(df)): row = df.iloc[i] rng.append(row.high - row.low)df['range'] = rngWHOLE COLUMNdf['range'] = df['high'] - df['low']Same output. One expression to read,and one place for a bug to hide.Why this matters beyond tidinessA row loop invites you to peek at row i+1 while computing row i. That is look-ahead bias, and it is silent.Column thinking is a habit, not an optimisation. Adopt it before your tables get large.
    The same calculation written twice. The second version is not merely shorter — it removes the place where a subtle time-travel bug likes to hide.

    Where does Indian market data come from?

    Broadly, four categories, and each has a different failure mode. None of them is named here — pick inside a category yourself, and test whatever you pick against the checks in the next topic.

    Exchange files
    The daily files NSE and BSE publish themselves, plus corporate-action and index-membership records. The most authoritative source of what actually happened, and the least convenient — you assemble the history yourself, file by file.
    Your broker's API
    Historical candles and live quotes from the broker you already have an account with. Convenient, tied to that relationship, and usually limited in how far back it will go and how many requests it will serve.
    Paid data vendors
    Sell adjusted history, delisted names and point-in-time index membership as a product. You are paying largely for the corrective work described in the next topic. Evaluate on whether they document their adjustment method, not on price.
    Free scraped sources
    Community libraries and scraped endpoints. Fine for learning the tooling. Frequently unadjusted, frequently missing delisted companies, and they break without notice. The next topic explains precisely what that costs a backtest.

    Watch out — The gap between a free source and a paid one is almost never the price series you can see. It is the corporate actions, the delisted companies and the dated index membership you cannot see missing. Never assume a source is adjusted because the chart looks smooth.

    What should you build first?

    Not a strategy. A strategy written before you can load, check and draw your own data is untestable, because when the output looks strange you will have no way to tell whether the idea is wrong or the data is.

    Build four small programs, in this order. Together they are perhaps a hundred lines and they will teach you more than any tutorial series.

    The build order. None of these four programs predicts anything or places an order — and that is exactly why they are first.Four build steps run left to right: a data loader, a sanity check, a plot, and a counter of how often a condition occurred. A fifth box at the end, drawn with a dashed caution border, is labelled a strategy and marked as not yet.Build in this orderFour small programs. None of them places an order or predicts anything.1A loaderone function: symbol in, tidy table out2A sanity checkgaps, duplicates, zero volume, impossible highs3A plotdraw it yourself and look at every strange bar4A counterhow often did condition X occur - just the countNOT YETA strategyWriting one before the four above exist means you cannot tell a real result from a data fault.If step three shows you a bar that makes no sense, you have already learned more than a backtest would teach.
    The build order. None of these four programs predicts anything or places an order — and that is exactly why they are first.

    How do you build those four, step by step?

    1. 1

      1. Write one loader function

      Symbol in, tidy table out. It reads whatever your source gives you, parses the dates properly, sorts by time, names the columns consistently, and returns a DataFrame. Every later script calls this one function, so when your source changes you edit one place.

    2. 2

      2. Write a sanity check that prints problems

      Duplicate timestamps, missing sessions, rows where the high is below the low, zero-volume days on a liquid name, prices that change by an implausible multiple overnight. Print them; do not silently drop them. The last check is your corporate-action detector.

    3. 3

      3. Draw the chart yourself

      Plot close against date and look at it. Then zoom into every bar the sanity check flagged. This step catches more real problems in an afternoon than a week of testing does, because your eye is better at 'that is wrong' than any assertion you will think to write.

    4. 4

      4. Count something — do not test anything

      Pick one condition from your written rulebook and count how many times it occurred, per year, across your universe. No entries, no exits, no money. If a condition fires four times a decade, you have learned the idea is untestable before you spent a month building an engine for it.

    5. 5

      5. Only now, the crude test

      And even then, expect the first version to be wrong. The backtesting topics later in this module exist because a naive test is far easier to build than a truthful one.

    How much Python do you actually need to know?

    Less than a computer-science course covers, and far less than the volume of Python content aimed at traders implies. A workable floor is genuinely small.

    The floor — learn these and stop

    • Variables, numbers, strings, and how Python handles dates and times.
    • Lists and dictionaries, and enough loops to know when you should not be using one.
    • Functions, and why putting your loader in one matters.
    • Reading and writing a CSV, and installing a package into a virtual environment.
    • pandas: the DataFrame, the index, selecting, filtering, groupby, resample and shift.
    • One plotting call, so you can look at anything at any time.
    • Reading an error message properly — the last line names the problem and the line number.

    Pro tip — If you find yourself learning object-oriented design, decorators or async before you have loaded a single price series, you have drifted into learning software engineering. That is a fine hobby and it is not this task.

    What can go wrong in the code itself?

    A short list of failures that are common, quiet, and specific to market data. Every one of them produces output that looks entirely reasonable.

    • Using today's close to decide today's entry. The single most common bug in retail backtests, and it flatters every result.
    • An index that is text rather than timestamps. Everything appears to work until sorting puts 2 April after 19 March.
    • Silently dropping rows with missing values. You have now deleted precisely the days something unusual happened.
    • Joining two instruments without aligning on the index, so row 300 of one is compared against row 300 of another that has a different trading calendar.
    • Re-running a notebook out of order, so a variable holds a value from an earlier version of the code. Prefer a script you run start to finish.
    • Filling forward across a corporate action or a long trading halt, which invents prices nobody ever traded at.
    • Hard-coding a path, a symbol and a date range into every file, so you can never re-run last month's research the same way.

    What does learning Python NOT get you?

    This is the honest part, and it is why this topic sits fifth in this module rather than first.

    Python gets you a way to ask questions of a large amount of data quickly. It does not get you a question worth asking, and it does not get you the discipline to accept the answer. The topics on either side of this one — the research workflow before it, and data quality, overfitting, costs and risk after it — are where the difficulty actually lives.

    What people expect Python to solveWhat it actually does
    Finding an edgeNothing. It tests an idea you already had.
    Fixing bad dataNothing automatically. You have to know what to correct and do it.
    Removing emotionOnly if you also stop overriding the system, which is a separate habit.
    Knowing whether a result is realNothing. That is validation — a distinct skill, covered later in this module.
    Executing safelyOnly if you build the monitoring and the kill switch, which is its own topic.
    Being fast enough to competeSpeed here is a research convenience. Latency-sensitive strategies are a different business with different infrastructure.

    Note — Learning the language is the small part. Treat any claim that a Python course will make you a profitable trader as a claim about the course's marketing, not about trading.

    What does a sensible first month look like?

    Weeks one and two: the floor list above, applied to one instrument's daily history. Nothing else.

    Weeks three and four: the loader, the sanity check and the plot, run over fifty liquid NSE names instead of one. Fix everything the sanity check screams about — and it will scream, because the next topic explains why raw Indian equity history is full of splits, bonuses and companies that no longer exist.

    Then count one condition. That is the month. Notice that a strategy has not appeared anywhere in it.

    Key points

    Python is chosen for its data tooling and its ecosystem, not because it improves any result.
    Four libraries carry most of the work: pandas, numpy, matplotlib and requests.
    Market data lives in one shape — a table indexed by timestamp, with OHLCV columns.
    Think in columns, not rows. The real benefit is that time-travel bugs become visible.
    Indian data comes from exchange files, broker APIs, paid vendors or free scraped sources — each fails differently.
    Build a loader, a sanity check, a plot and a counter before you build any strategy.
    The most common quiet bug is using a candle's close to decide an entry inside that same candle.
    The floor of Python you need is small; going past it into software engineering is a detour.
    Python supplies no edge, no clean data and no discipline — those are the rest of this module.
    A first month with no strategy in it is a well-spent first month.

    Pro tip — Before any strategy code exists, write one script that loads a symbol, prints every duplicate date, every missing session and every overnight move larger than fifty per cent, and then plots the close. Run it across fifty liquid NSE names. Whatever it prints is the real state of your data — and it is the argument for the next topic in this module.

    Frequently asked questions

    Do I need to know Python to trade algorithmically in India?

    No. A written rulebook you follow manually, a screener with saved conditions, or a spreadsheet is systematic trading, and the earlier topics in this module cover that route. Python becomes worth the effort when your process needs to run identically over thousands of NSE and BSE symbols and many years of history, and when you need a record of exactly what it did.

    How long does it take to learn Python for trading?

    The subset listed on this page — basic syntax, pandas, one plotting call — is a few weeks of consistent evenings for most people. Being able to produce a backtest you would actually trust takes far longer, because the difficulty is in data quality, validation, costs and risk rather than in the language.

    Which Python libraries do I need for stock market analysis?

    pandas for the price table, numpy for the arithmetic beneath it, matplotlib to draw what you loaded, and requests when your data starts arriving over HTTP. A backtesting framework and any machine learning stack should come much later, after you have written a crude test yourself and understood what a framework is doing on your behalf.

    Should I use a notebook or write scripts?

    Notebooks are excellent for looking at data and terrible for anything you need to reproduce, because cells can be run out of order and leave variables holding values from code that no longer exists. A practical split is to explore in a notebook and move anything you will re-run — especially your loader — into a plain script you execute from top to bottom.

    Is vectorised code just about speed?

    No, and speed is the least important part. Operating on whole columns forces you to be explicit about referencing an earlier candle, which makes look-ahead bias visible in the code instead of hidden inside a loop that could read any row it likes. The correctness benefit outlasts the performance one.

    What should my first Python trading project be?

    A data loader, a sanity check that prints problems rather than hiding them, a chart you drew yourself, and a program that counts how often one condition occurred. No entries, no exits and no money. Building a strategy before these exist means that when the output looks odd you cannot tell whether the idea is wrong or the data is.

    Can Python place live orders with an Indian broker?

    Several Indian brokers expose APIs that allow it, and SEBI's algo trading framework governs how retail participants may use them — both are covered in their own topics in this module. Treat live execution as a late-stage engineering problem with its own monitoring and shutdown requirements, not as the natural next step after your first working script.