Algo trading with Python: what you need and where it gets hard
Python can do every step of algorithmic trading. The hard parts are writing a bug-free backtest, testing many combinations in reasonable time, and moving finished rules to the platform you trade on.
By Soren Huang · Published · updated · Editorial policy
Contents
- Can you do algorithmic trading with Python?
- What do you need for a Python trading stack?
- Which backtest bugs catch most Python traders?
- How does look-ahead bias slip into pandas code?
- Which fill assumptions make a Python backtest too optimistic?
- Which cost and contract-math mistakes distort futures results?
- How slow does Python get when you test many combinations?
- How do you move a Python strategy to a live platform?
- When does code give you more, and when does dedicated software save time?
- Frequently asked questions
- References
Can you do algorithmic trading with Python?
Yes. Python can handle every step of algorithmic trading: loading data, testing rules, measuring results and sending orders. The hard parts are not the language. They are writing a backtest without hidden bugs, running enough tests in reasonable time, and moving finished rules to the platform you trade on. Dedicated software handles these standard steps for you.
Algorithmic trading is trading in which a computer follows written rules to decide when to enter and exit. Python is popular for this because it is free, easy to read and has mature tools for working with tables of prices. Building your own system in Python is like building a car from parts. You know every bolt, but you also have to find every loose one yourself.
What do you need for a Python trading stack?
A working Python setup for trading has five layers, and you write the glue between them yourself. The table shows what each layer does and the part that usually stays your job.
| Layer | Typical tools | What you still write yourself |
|---|---|---|
| Data feed | Broker API, data vendor files, exchange downloads | Download scripts, storage, handling of missing bars |
| Data handling | pandas, NumPy | Time zones, trading sessions, contract rolls |
| Backtesting | An open-source backtesting library or your own loop | Signal logic, fill rules, cost model |
| Analysis | pandas, plotting libraries | Equity curve, drawdown, trade statistics |
| Live trading | Broker API or a trading platform | Order handling, reconnects, monitoring |
pandas is a Python library for tables of data with a time index, and it is where most traders start. NumPy is the library underneath it for fast work on arrays of numbers.
Backtesting libraries come in two styles. A vectorized backtest is one that computes signals and returns for the whole price history at once, as columns in a table. It is fast and short to write, but rules that depend on earlier trades, such as trailing stops or "only one position at a time", are hard to express. An event-driven backtest is one that steps through the data bar by bar, the way a live system would. It handles any rule, but it runs slower and needs more code.
The data layer causes more trouble than most people expect. Futures data needs correct session times, time zones and contract rolls before any test means anything. The checklist in backtest data quality: gaps, bad ticks, time zones and rolls covers what to inspect first.
Which backtest bugs catch most Python traders?
The most common Python backtest bugs all make results look better than reality, so a strong first result is a reason to check the code, not to celebrate. Three groups cause most of the damage.
How does look-ahead bias slip into pandas code?
Look-ahead bias is the use of information in a backtest that would not have been available at the moment of the trading decision. In pandas it hides easily:
- No shift. A signal computed from today's close is applied to today's return. The fix is to shift the signal by one bar, with shift(1), so it trades on the next bar.
- Whole-sample statistics. Scaling an indicator by the average or the highest value of the full history uses future data. Use rolling windows that end at the current bar.
- Resampling labels. By default, pandas labels a resampled 5-minute bar with its start time. A bar labeled 09:00 therefore contains prices up to 09:05. Joining it to other data at 09:00 leaks five minutes of the future.
- Daily values used too early. The day's high, low or close is only known after the session ends. Using it during the session is a quiet form of look-ahead.
Which fill assumptions make a Python backtest too optimistic?
Fill rules decide at what price the backtest assumes you traded. Common mistakes:
- Deciding on a bar's close and also filling at that same close. You cannot trade at a price you only see once it is final. Next-bar execution is more realistic.
- Filling every limit order as soon as price touches it. In real markets, a touch often does not fill you.
- Filling stop orders at the exact stop price when the market gaps through it.
- Assuming the target was hit before the stop when both fall inside the same bar. With bar data you cannot know the order, so choose the cautious assumption.
Which cost and contract-math mistakes distort futures results?
Slippage is how far your real fill lands from the price the backtest assumed. Leaving out slippage and commission is the classic mistake, and it hurts high-frequency rules most. The worked numbers in trading costs in backtests: commission, slippage and the average trade show how a positive edge can turn negative. Futures add two more traps. Profit must be measured in points times the contract's point value, not in percent of price. Also, back-adjusted continuous contracts can drift far from real prices over a long history and can even turn negative, so percentage returns on them can be wrong.
How slow does Python get when you test many combinations?
Python is fast enough for testing one idea, but it slows down sharply once you search many parameter combinations, because the number of tests grows by multiplication. Each new parameter multiplies the total by the number of values you try for it.
Hypothetical example
A rule has 5 parameters, and you try 10 values for each. That is 10 × 10 × 10 × 10 × 10 = 100,000 combinations. If one bar-by-bar backtest takes 0.1 seconds, the search takes 10,000 seconds, about 2.8 hours. If you repeat the search in 10 walk-forward windows, you run one million backtests, about 28 hours. Add one more parameter with 10 values, and every figure grows ten times.
Python traders use three main ways to go faster: vectorize the logic with NumPy, compile hot loops with a just-in-time compiler such as Numba, or spread the work over several processor cores. Each one helps, and each one adds code to write and test. Rules with stops, position limits or trade-by-trade logic are the hardest to speed up.
For a sense of scale on dedicated software, AlphaPrime (Valynox) publishes one benchmark. It recorded 1,268,200,000 strategy evaluations in 18 h 23 min on one RTX 3090, measured 2026-10-05. The setup used TY 37-minute bars from 2015-01-01 to 2026-09-25, 114,371 bars per candidate, with commission and slippage included in every evaluation. Real speed depends on the graphics card, the data length and the research settings, so this figure cannot be compared directly with the hypothetical example above.
Speed has a second cost. The more combinations you test, the more of them look good by luck alone, so the best backtest of a large search is usually inflated (Bailey et al., 2014; White, 2000). A larger search needs stricter checks on data the search did not use, such as walk-forward analysis. In AlphaPrime, strategy validation runs Basic, Standard or Extensive checks, with walk-forward analysis in Extensive, against thresholds you set for every candidate.
How do you move a Python strategy to a live platform?
A strategy researched in Python reaches a live market by one of two routes. Either you run Python yourself and send orders through a broker API, or you rewrite the rules in the language of the platform you trade on. Most charting platforms run strategies in their own scripting language, so the second route means a translation step.
The first route keeps one codebase but makes you responsible for live engineering: lost connections, partial fills, rejected orders, clock drift and a computer that must stay on during the session. The second route lets the platform handle orders, but every rule is written twice, and the two versions can drift apart.
Whichever route you choose, follow the same order of steps:
- Freeze the rules. Write down every parameter, session setting and cost assumption before translating anything.
- Translate or connect. Rewrite the rules in the platform's language, or connect your Python code to the broker.
- Compare trade lists on the same data. Run both versions over the same period and match the trades one by one, by entry time, direction and price.
- Explain every difference. Small gaps usually come from session times, how bars are built, rounding or the first bars an indicator needs. Each one has a cause you can find.
- Run in simulation first. Let the live version trade on a simulated account and check that its orders match what the backtest would have done.
When does code give you more, and when does dedicated software save time?
Code gives flexibility for unusual ideas. Dedicated software saves time on the standard work of searching and testing bar-based rules with costs. The table matches common situations to the approach that usually fits.
| Situation | Usually fits | Why |
|---|---|---|
| Custom data such as order book data, news or your own machine-learning features | Python | You can shape any data and any model. |
| Testing one specific idea in detail | Either | The search is small. The choice depends on your coding skill. |
| Searching many indicator rules and parameter ranges on bar data | Dedicated software | Costs, fills, sessions and the search loop are already built and tested. |
| Validating many candidates with the same standards | Dedicated software | The same checks run on every candidate without new code. |
| Trading through a charting platform | Dedicated software with export | No hand translation of every rule. |
| Full control over every line of the system | Python | You own and can audit every step. |
A useful test is to count the hours you spend on plumbing (data cleaning, fill logic, speed work, translation) against the hours you spend on trading ideas. If plumbing wins every week, a dedicated tool frees that time. If your edge depends on data or models that no tool covers, code is the right place to work.
AlphaPrime covers the standard part. Its backtesting evaluates every candidate with the same settings for data resolution, next-bar execution, fees, slippage and trading sessions. Its platform export writes strategy source code for MultiCharts (PowerLanguage), TradingView (Pine Script v6), TradeStation (EasyLanguage), NinjaTrader (NinjaScript), MetaTrader 4 (MQL4) and MetaTrader 5 (MQL5).
What this means if you use AlphaPrime: you can keep Python for custom data work and one-off ideas, and let AlphaPrime run the rule search, the cost-aware backtests, the validation and the export to your platform. Then compare the exported strategy's trade list with the platform's own backtest before you trade it.
Frequently asked questions
Is Python good for algorithmic trading?
Python works well for algorithmic trading research because pandas and NumPy make price data easy to handle and the language is easy to read. It can also send live orders through broker APIs. The effort goes into building correct backtests, speeding up large searches and running a reliable live connection.
Which Python library should I use for backtesting?
Choose by style. Vectorized libraries are fast and short for simple signal rules. Event-driven libraries step through bars one by one and handle stops, position limits and other trade-by-trade logic. Whichever you pick, check its default fill and cost settings before you trust any result.
Can I run a Python strategy directly in TradingView?
No. TradingView runs strategies written in Pine Script, so a Python strategy has to be rewritten in Pine Script to run there. After rewriting, compare the trade list from both versions on the same data and explain every difference.
Why do my Python backtest results look too good?
The usual causes are look-ahead bias, unrealistic fills and missing costs. Check that every signal is shifted by one bar, that orders fill on the next bar, and that commission and slippage are subtracted from every trade. Also remember that the best result of a large search is usually inflated by luck.
Do I need to learn Python before I start algorithmic trading?
No. Python is one way to research and run rules, and dedicated strategy software is another. Learning Python pays off if you want custom data or models. If you mainly want to test indicator rules on bar data, a dedicated tool lets you start with the trading questions instead of the code.
References
- Bailey, D. H., Borwein, J., López de Prado, M., & Zhu, Q. J. (2014). Pseudo-Mathematics and Financial Charlatanism: The Effects of Backtest Overfitting on Out-of-Sample Performance. Notices of the American Mathematical Society, 61(5), 458–471.
- White, H. (2000). A Reality Check for Data Snooping. Econometrica, 68(5), 1097–1126.

