Back to blog
Automated Trading

Python Algorithmic Trading: A First Strategy

7 min read · Automated Trading · By Karani Markets
Python Algorithmic Trading: A First Strategy

Python algorithmic trading means writing rules in code that decide when to buy or sell, then testing those rules against historical price data before risking real money. For an S&P 500 E-mini (ES) strategy, that often starts with something simple: a moving-average crossover, translated into a script that reads price bars, checks a condition, and logs a hypothetical trade. Writing the code is the easy part. Proving the rule survives data it never saw is where most first strategies fall apart.

What is python algorithmic trading?

Python became the default language for this kind of work because a few libraries do most of the heavy lifting. Pandas handles time-series price data, opens, highs, lows, closes, in a table you can slice and transform in a line or two. Numpy handles the math underneath it. None of that is special to trading. It's just why traders reach for Python over a spreadsheet when they want to test an idea fast.

The core idea is narrower than the phrase suggests. You take a trading rule you can state in one sentence, encode it exactly, and let the code apply it consistently across years of data. No hesitation, no second-guessing a signal because the market feels wrong that morning. The rule either fires or it doesn't.

Coding a moving-average rule for ES

Here's a rule simple enough to code in an afternoon. Calculate two moving averages of ES closing prices, one over a short window like 10 bars, one over a longer window like 50 bars. When the short average crosses above the long average, that's a buy signal. When it crosses back below, that's a sell signal. In pandas, this takes about five lines: load the price series, compute the two rolling means, compare them bar by bar, and mark the crossover points.

From there you turn signals into a track record. For each crossover, record the entry price, the exit price at the next opposite signal, and the difference in points. Multiply by the ES point value of $50 per point (or $12.50 per tick, since one tick is 0.25 points) and you have a dollar result for every trade the rule would have taken. String those together and you have a backtest.

A backtest that only worked on one stretch of history already told you something, just not what you wanted to hear.

What the backtest actually shows

Run that crossover against a few years of ES data and you'll get a number: total points gained or lost, a win rate, maybe an average trade size. It looks like proof the idea works. What it actually shows is how this exact rule, with these exact window lengths, would have performed on this exact stretch of history. Change the window from 10/50 to 12/48 and the result can shift meaningfully, sometimes from profitable to not.

That sensitivity is the first warning sign, not a footnote. A rule whose performance depends heavily on picking the precise window length is telling you it found a pattern specific to that data, not a durable edge in how markets behave.

How to spot the overfitting trap early

Overfitting happens when you tune a rule's parameters until the backtest looks good, without checking whether that tuning generalizes. With two adjustable numbers (the two window lengths) and a few years of five-minute ES bars, it's easy to find a combination that happened to work well on that specific stretch just by chance. The backtest will report a strong result. The rule hasn't learned anything about markets. It's memorized noise.

The standard defense is splitting your data before you start. Pick your parameters using one period, say 2015 through 2019, and never look at the following period until the parameters are locked. Then test on 2020 through 2023 without changing anything. If performance degrades sharply, the rule was fit to the first period's noise. If it holds up reasonably, you've learned something closer to real.

A second defense: be suspicious of any strategy with more than a handful of adjustable parameters. Every parameter is another dial you could have turned until the backtest flattered you. A two-parameter moving average crossover is easy to reason about. A ten-parameter rule with filters, thresholds, and time-of-day conditions is much easier to accidentally overfit and much harder to explain if someone asks why it works.

What a backtest can't tell you

A backtest assumes your fills happen at the exact price your code says they should. Real ES fills involve slippage, especially during fast moves, and commissions on every round turn. A rule that clears $15 a trade in backtest and pays $8 of that to commissions and slippage in live execution is not the strategy you thought you tested. Build those costs into the backtest from day one, even as a rough estimate, or the number you're staring at is fiction.

A backtest also can't tell you what happens when you're the one watching it lose money in real time. Code doesn't hesitate before taking the fortieth signal after nine losing trades in a row. A person does. That gap between what the code will do and what you'll actually let it do, under a live daily-loss cap and a kill switch you can hit, is a separate problem from the strategy itself, and it's the one that ends most first attempts at systematic trading.

Common questions

Do I need to know Python before I can backtest a trading strategy?

You need enough to load a price series, compute a rolling average, and compare two columns row by row. Pandas handles most of that with built-in functions, so basic Python plus a few pandas methods is usually enough for a first moving-average backtest.

What's the difference between a backtest and paper trading?

A backtest runs your rule against historical data all at once, instantly. Paper trading runs the same rule forward in real time against live prices, without real money, so you see how it behaves bar by bar as the market actually unfolds, including any lag between signal and execution.

Why do moving-average strategies often fail after they're coded?

Most failures trace back to overfitting the window lengths to one stretch of historical data, or ignoring slippage and commissions in the backtest math. Both make a rule look better on paper than it performs with real fills and real costs.

Karani runs the disciplined part for you

A tested, rules-based system on the S&P 500 futures, with hard risk limits and a kill switch you control. Access is invite-only.