HomeTechnical Basics
Algorithmic Trading with Python: A Practical Guide

Algorithmic Trading with Python: A Practical Guide

Algorithmic trading with Python means using Python code to analyse market data and apply defined trading rules. A complete system also checks risk, sends orders through a broker’s API and monitors what happens afterwards. We can start with a simple question: what exactly should our program do when a trading condition appears? Answering that clearly…

Algorithmic Trading with Python: A Practical Guide

Algorithmic trading with Python means using Python code to analyse market data and apply defined trading rules. A complete system also checks risk, sends orders through a broker’s API and monitors what happens afterwards.

We can start with a simple question: what exactly should our program do when a trading condition appears? Answering that clearly matters more than adding indicators or writing a longer script.

In this guide, we work through the stages from an initial rule to a tested system, with examples relevant to Indian markets. The aim is to understand the process and its limitations, rather than assume automation produces better returns.

What Does an Algorithmic Trading System Do?

An algorithm is a sequence of instructions. In trading, those instructions might compare prices, check a time window or decide whether an existing position needs attention.

Suppose we want to study a rule based on two moving averages. The program calculates both averages, checks whether they have crossed and records a signal. Before that signal becomes an order, we still need to check the instrument, permitted quantity, existing exposure and available funds.

A signal, an order and a completed trade are different events. An order can be rejected, partly filled or remain pending. Our software must track the actual outcome before making its next decision.

For a broader introduction, our guide to the basics of algorithmic trading explains how rules, market data and order handling fit together.

Algorithmic Trading with Python

Why Use Python for Algorithmic Trading?

Python lets us express trading rules in readable code and work with structured datasets. We can explore an idea in a notebook, inspect intermediate calculations and turn the tested logic into reusable functions.

Different libraries serve different purposes:

  • pandas: organising time-series data and calculating rolling statistics.
  • NumPy: working with numerical arrays and calculations.
  • Matplotlib: plotting prices, signals and research results.
  • A backtesting engine: simulating orders, positions and portfolio behaviour under specified assumptions.
  • A broker SDK or API client: connecting the program to supported market-data and trading services.

We do not need every library on day one. A small, understandable setup makes it easier to identify whether a problem comes from the data, the trading rule or the execution code.

Python is useful for research and many automated trading tasks. However, using it does not turn an ordinary script into a high-frequency trading system. Workflows that depend on extremely low latency require specialised infrastructure and engineering.

How We Build an Algorithmic Trading System with Python

1. Write the Rules Before Writing the Code

Our specification should explain the instrument, observation interval, entry condition, exit condition and position limit. It should also state when the program must stop opening new positions.

For example, “follow the trend” is too vague. “Record a long-entry signal when the 20-period moving average crosses above the 50-period average on a completed candle” gives us something testable. These periods are illustrative choices, not recommended settings.

We also decide how to handle repeated signals. If a condition remains true across several updates, it should not create several orders unless the specification explicitly allows that behaviour.

2. Set Up a Reproducible Environment

We begin with a supported Python version and a separate virtual environment for the project. A notebook can help us explore data, while an editor such as Visual Studio Code helps us organise scripts and review changes.

We record package versions so that another machine can reproduce the research. Keeping data loading, strategy calculations and execution in separate functions also makes changes easier to check.

Credentials belong outside the source code, with access restricted to the people and services that need them. We should avoid exposing account details or authentication information in notebooks, shared files and logs.

3. Obtain and Check Market Data

A strategy can produce convincing results from unsuitable data. Before calculating an indicator, we check timestamps, missing observations, duplicate records and the meaning of each field.

For Indian equities, corporate actions can affect historical price comparisons. For futures and options, we need the correct contract, expiry and lot size for the period being studied. Joining different contracts without a defined method can distort the result.

We also match the data to the question. Daily closing prices cannot show whether an intraday stop would have triggered before a target. Options research may need historical contract prices and quotes, rather than just the underlying index.

If our strategy depends on option-chain information, our option chain guide explains the fields we need to understand before turning them into conditions.

4. Calculate a Signal in Python

The following example creates moving-average crossover signals from a local CSV file. It assumes one row per completed trading session, with date and close columns in chronological order after sorting.

import pandas as pd

prices = pd.read_csv(“prices.csv”, parse_dates=[“date”])

prices = prices.sort_values(“date”).set_index(“date”)

if prices.index.has_duplicates or prices[“close”].isna().any():

    raise ValueError(“Check duplicate dates and missing closes”)

fast = prices[“close”].rolling(20, min_periods=20).mean()

slow = prices[“close”].rolling(50, min_periods=50).mean()

ready = fast.notna() & slow.notna()

above = fast > slow

previous_above = above.shift(1, fill_value=False)

previous_ready = ready.shift(1, fill_value=False)

prices[“entry_signal”] = (

    ready & previous_ready & above & ~previous_above

)

prices[“exit_signal”] = (

    ready & previous_ready & ~above & previous_above

)

print(prices[[“close”, “entry_signal”, “exit_signal”]].tail())

The code waits until both averages have valid current and previous observations. It then flags changes in their relationship rather than printing a new entry signal every day the shorter average remains above the longer one.

We have created a research example, not a backtest or an order-placement system. Because the signal uses a session’s closing price, any simulated execution must occur after that information becomes available. Assuming an earlier fill would introduce look-ahead bias.

Before reusing the example, we would add checks for numeric values, valid trading dates and the data provider’s adjustment method. We would also define what happens when the averages are equal.

5. Backtest with Realistic Assumptions

Backtesting applies our rules to historical observations and simulates the resulting trades. We use it to investigate a strategy, not to establish what future returns will be.

The test needs assumptions about execution prices, order timing, position sizing and costs. Slippage is the difference between an expected price and the price achieved. Brokerage, applicable charges and the bid–ask spread can also change the result.

Suppose an illustrative test produces ₹6,000 in gross gains across 100 completed trades. If combined charges and assumed execution costs average ₹70 per completed trade, the result becomes a ₹1,000 loss. These figures are hypothetical, not Nubra’s fees.

We review drawdown, losing streaks, average gain or loss per trade and the number of observations behind the result. Drawdown measures the fall from a previous peak in portfolio value. A high win rate alone tells us little if occasional losses are much larger than typical gains.

Repeatedly changing parameters until the historical result looks attractive can lead to overfitting. We reserve a separate period for evaluation and test across different market conditions, keeping the rules unchanged during that evaluation.

6. Test the API Integration and Failure Handling

A trading API lets our software communicate with a broker’s systems. Before sending live orders, we check the current documentation, account requirements, supported operations and authentication process.

We first test the integration in an appropriate non-live environment where available. Paper trading or simulation can reveal logic problems, but simulated fills may differ from actual market execution.

Order handling needs particular care. If a request times out, we cannot assume it failed. Retrying immediately could create a duplicate order. We reconcile the order status and actual position before deciding what to do next.

For a partly filled order, subsequent actions must use the filled quantity. The intended position and the position actually held can be different, especially when several options legs are involved.

7. Add Risk Controls and Monitoring

We define position-size limits, exposure caps, permitted instruments and conditions that pause new orders. Daily loss limits and stop rules also need clear definitions, including how the system measures losses.

A stop order cannot guarantee its execution price during a sharp move or a gap. Similarly, stopping a program does not automatically cancel pending orders or close open positions. Our shutdown procedure must account for both.

Monitoring should cover data freshness, rejected orders, unexpected positions and connection failures. Logs need enough detail to reconstruct decisions, and alerts need a person who can respond.

What Should We Check Before Trading in India?

Live retail algorithmic trading sits within SEBI’s framework and applicable exchange and broker requirements. Before deployment, we confirm the requirements that apply to our particular setup with the broker.

These may cover account access, authentication, permitted connections, order identification, registration and risk controls. We should not infer an exemption or approval from a code example, order frequency or a successful historical test.

We also check current instrument specifications and trading restrictions. A script that runs correctly in research may still submit an invalid quantity or an unsupported order when connected to an account.

Where Can We Take the Research Next?

Once the basic process works, we can investigate additional signals, portfolio-level exposure or models that use more than one input. Each addition needs a clear reason and an evaluation method.

Machine learning can help us study relationships in data, but it introduces further choices about features, training periods and validation. More complex models can overfit too. We should compare them with a simple baseline before assuming the extra complexity adds value.

For options, automation also needs to account for expiry, changing sensitivities and the risk of legs filling at different times. Our option strategy builder guide provides context for understanding combined positions before we consider coding them.

Exploring the Process with Nubra

After defining the research question, we can use specific Nubra tools to inspect the market context:

Dashboard access may require sign-in. These visual tools support analysis; reviewing a setup on screen does not validate its automated execution or profitability.

For programmatic development, our Nubra API documentation covers Python SDK and REST API resources for market-data, trading and portfolio operations. We should match the current documented capabilities to our specification and confirm account access before integration.

FAQs
Is Python Suitable for Algorithmic Trading?

Python is useful for data analysis, strategy research and API integration. Whether it suits a live system depends on the required speed, infrastructure and operational controls. Language choice alone does not determine execution quality.

Do We Need Coding Skills to Build a Python Trading System?

We need enough programming knowledge to understand the data, conditions, errors and order handling, or development support that covers those areas. Copying a working script does not establish that it behaves correctly in every situation.

Can Algorithmic Trading with Python Be Profitable?

It can generate profits or losses. Results depend on the strategy, costs, execution and market conditions. Automation follows instructions; it does not create a profitable trading edge by itself.

How Much Capital Do We Need?

There is no universal amount. We need to consider the instrument, position size, applicable margin, charges and potential losses. Researching historical data does not require funding a live position, although data or software services may involve costs.

How Does Backtesting Differ from Paper Trading?

Backtesting simulates a strategy over historical data. Paper trading observes its behaviour in a simulated trading setting, often as new data arrives. Both help us evaluate a system, but neither reproduces every feature of live execution.

Does Nubra Provide Python API Resources?

Yes. Nubra’s API documentation includes Python SDK resources alongside REST API references. We should use the current documentation for setup and confirm the account permissions and requirements relevant to our intended use.

Disclaimer: The information provided in this blog is for educational and informational purposes only and should not be construed as investment advice, financial advice, or a recommendation to buy, sell, or hold any securities or financial products. Investments in the securities market are subject to market risks. Please read all related documents carefully before investing. Readers should conduct their own research and consult a SEBI-registered investment adviser or other qualified financial professional before making any investment decisions. Past performance is not indicative of future results.

Published Oct 27, 2026
Open a Nubra account

Put this into practice

Trade options with a live chain, a strategy builder and real-time Greeks — the same tools this guide describes.

Keep Reading