← Back to All Lessons
Lesson 19

Introduction to Algorithmic Trading — Automation & Backtesting

Discover how algorithmic trading works. See Python pseudocode examples and learn the basics of backtesting a strategy.

Algorithmic trading — or "algo trading" — uses computer programs to execute trades automatically based on predefined rules. No emotions, no hesitation, no fat-finger errors. It's estimated that over 70% of trades on major exchanges are now executed by algorithms.

What Is Algorithmic Trading?

At its core, an algo is just a set of instructions: "If condition X is true, do Y." For example: "If the 20-day moving average crosses above the 50-day moving average AND volume is above the 20-day average, buy."

The advantage is speed, consistency, and the ability to backtest — running your strategy against historical data to see how it would have performed. A human trader can't manually test 10 years of data. A computer can do it in seconds.

Simple Strategy in Python (Pseudocode)

Here's what a basic moving average crossover strategy looks like in Python-style pseudocode. This isn't production code — it's designed to show the logic:

# Simple Moving Average Crossover Strategy
# ------------------------------------------

import data_provider  # fetches historical price data
import broker_api     # connects to your broker

# Settings
SYMBOL = "GBPUSD"
SHORT_MA = 20    # fast moving average period
LONG_MA = 50     # slow moving average period
RISK_PER_TRADE = 0.01  # risk 1% of account per trade

# Fetch daily closing prices
prices = data_provider.get_closes(SYMBOL, period="1Y")

# Calculate moving averages
short_ma = average(prices, last=SHORT_MA)
long_ma = average(prices, last=LONG_MA)

# Previous values for crossover detection
prev_short = average(prices[:-1], last=SHORT_MA)
prev_long = average(prices[:-1], last=LONG_MA)

# Check for Golden Cross (buy signal)
if prev_short <= prev_long and short_ma > long_ma:
    position_size = calculate_size(
        account_balance=broker_api.get_balance(),
        risk_percent=RISK_PER_TRADE,
        stop_distance=prices[-1] - long_ma
    )
    broker_api.buy(SYMBOL, size=position_size)
    broker_api.set_stop_loss(price=long_ma)

# Check for Death Cross (sell signal)
if prev_short >= prev_long and short_ma < long_ma:
    broker_api.close_position(SYMBOL)

Backtesting — Testing Before Risking

Backtesting means running your strategy against historical data. If your MA crossover strategy would have lost money over the last 5 years on the FTSE 100, you probably shouldn't use it live.

Key metrics from a backtest:

  • Win rate: What percentage of trades were profitable?
  • Profit factor: Total gross profit divided by total gross loss. Above 1.5 is decent; above 2.0 is good
  • Maximum drawdown: The largest peak-to-trough decline. If your backtest shows a 40% drawdown, could you stomach that in real life?
  • Sharpe ratio: Risk-adjusted return. Above 1.0 is acceptable; above 2.0 is excellent

⚠ Backtesting Pitfalls

  • Overfitting: Tweaking parameters until they perfectly match historical data. Your strategy will fail on new data
  • Survivorship bias: Only testing on stocks that still exist today — ignoring companies that went bankrupt
  • Ignoring costs: Spread, commission, slippage, and overnight financing can destroy a strategy that looks profitable in a backtest

Getting Started with Algo Trading

  • 1.Learn Python basics — you don't need to be an expert, but you need to read and modify code
  • 2.Use a backtesting library like Backtrader or Zipline to test strategies
  • 3.Paper trade your algo for at least 3 months before using real money
  • 4.Start with tiny position sizes — the goal is to prove the system works, not to make money immediately

Risk Warning

Trading and investing carry significant risk. You can lose more than your initial deposit when trading leveraged products. Past performance is not indicative of future results. The content on TradeLearn is for educational purposes only and should not be considered financial advice. Always do your own research and consider seeking advice from a qualified financial adviser before making investment decisions.

Trading Essentials

As an Amazon Associate we may earn from qualifying purchases.