← AITrading.in · Blog

Python Algo Trading: What to Learn Before You Code

Python algo trading means writing a Python program that reads market data, applies rules you have written down, and produces orders, usually through a broker. The code itself is the smaller part of the job. Most of the work is data handling, honest testing, money arithmetic and safety limits, which is why beginners who start from a strategy video often skip the parts that matter.

This article is education, not investment advice. Trading carries a real risk of loss, and nothing here suggests that any rule, indicator or program will make money.

What are the parts of a Python trading script?

A working script, however simple, has five parts. Writing them as separate pieces makes each one testable.

Part What it does Question to ask
Data Loads past or live prices (candles) Where do the timestamps and prices come from, and are they complete?
Signal Turns data into "enter", "exit" or "do nothing" Could this rule be written as plain sentences?
Risk checks Blocks orders that break your limits What is the biggest order and the biggest daily loss you accept?
Execution Sends the order to a broker interface What happens if the order is rejected or only part-filled?
Records Saves every signal, order and result Can you explain any trade a week later?

A candle is one summary row of price data for a fixed period, with the open, high, low and close price. A signal is the output of a rule that says what the program should do next. An API is an interface that lets one program talk to another, for example your script and a broker's order system.

How much Python do I need first?

Less than most people expect, but it needs to be solid. The official Python tutorial describes the interpreter as acting "as a simple calculator," where you can type an expression and it will write the value, with +, -, * and / for arithmetic and parentheses for grouping. It also notes that lists "can be indexed and sliced." If you are comfortable with those basics plus functions, loops and reading a file, you can start on data work.

The tool most trading scripts lean on for data is the pandas library. Its time series documentation says pandas offers "extensive capabilities and features for working with time series data", including parsing dates, generating fixed-frequency date sequences and resampling, which converts a time series to a particular frequency, such as turning one-minute candles into hourly ones. Your data is a series ordered by time, and many common mistakes come from mixing up "before" and "after".

What does a small worked example look like?

The example below is an illustration of how to avoid one mistake, not a trading strategy. It marks candles where the close is above its 20-candle average, then moves that signal forward by one row.

import pandas as pd

candles = pd.read_csv("candles.csv", parse_dates=["timestamp"], index_col="timestamp")

candles["avg_20"] = candles["close"].rolling(20).mean()
candles["above_avg"] = candles["close"] > candles["avg_20"]

# The close of a candle is only known when it ends, so act on the NEXT candle.
candles["signal"] = candles["above_avg"].shift(1, fill_value=False)

The last line is the important one. Without .shift(1), the program would "decide" at a candle's close and also pretend it traded at that same close, using information that did not exist yet. That is look-ahead bias: a test uses data that was not available at the time of the decision. It makes results look better than anything achievable live. For every decision, ask what the program could really have known at that moment.

Why should I not use plain floats for money?

Computers store ordinary decimal numbers in binary, and many simple decimals cannot be stored exactly. Python's decimal module documentation says: "numbers like 1.1 and 2.2 do not have exact representations in binary floating point," and that 1.1 + 2.2 displays as 3.3000000000000003. Its example is 0.1 + 0.1 + 0.1 - 0.3, which gives a tiny non-zero number with floats and exactly zero with Decimal.

For analysis, small float errors rarely matter. For anything that compares prices for equality, adds up charges or checks a limit, use Decimal built from strings (Decimal("0.1")), not from floats. The documentation also says it is "preferred in accounting applications which have strict equality invariants."

Which safety checks should the script have before any order?

Put these in the code itself, so that a bug cannot skip them. The numbers below are examples only; choose your own.

A bug that keeps sending orders is a common way a first script goes wrong, and the cost falls on you.

Is it legal to run my own Python script in India?

Rules apply and they have changed. SEBI's circular of 4 February 2025, "Safer participation of retail investors in Algorithmic trading" (circular number SEBI/HO/MIRSD/MIRSD-PoD/P/CIR/2025/0000013), set out a framework for retail use of algos through stock brokers. A later SEBI circular of 30 September 2025 (SEBI/HO/MIRSD/MIRSD-PoD/P/CIR/2025/132) extended the implementation timeline for it. I could not read the full text of either circular's detailed provisions when this article was written, so it does not state the thresholds, registration steps or dates.

What to do instead: read our plain-English guide, Is Algo Trading Legal in India?, then read the current circulars on the SEBI website and ask your broker in writing what it requires before you connect a script to its API. This is general information and not legal advice.

What can go wrong with a first Python trading project?

What this article does not cover

It does not recommend a strategy, indicator, broker or library, give tax advice, or explain any broker's order interface. It does not replace your broker's terms.

Frequently asked questions

Is Python good for algo trading?

Python is widely used because it is readable and has data libraries such as pandas. It is slower than some other languages, but speed matters mainly for strategies that compete on milliseconds, which is not where beginners start.

Can I learn Python algo trading with no coding background?

Yes, but plan to learn basic Python and data handling first, for example reading a file of candles and calculating an average. Trying to write order-sending code before you can read a table of prices is how costly mistakes happen.

Do I need a paid data feed or broker API to start?

No. You can learn the logic with a saved file of past candles and a dry-run mode that sends nothing. Live data and order access come later, and your broker will set its own terms for them.

Will a Python trading bot make money?

Nobody can promise that, and this site does not. A program only follows its rules faster than a person; it does not make weak rules good. Treat any claim of guaranteed or typical returns as a warning sign.

What should I build first?

A small program that loads candles, calculates one indicator, saves its signals to a file, and logs what it would have done. It sends no orders. When you can explain every line of its output, you are ready to test costs and limits.

Where to go from here

Write your first rule as three plain sentences, then turn only the data-loading and logging parts into code.

Sources

All pages were read on 31 October 2026.