Sitemap

Machine Learning for Algorithmic Trading — Part 29 From Zero to Backtest: A Beginner’s Guide

5 min readJun 8, 2026

--

Press enter or click to view image in full size

Part 1 of 4 — Key takeaways from Stefan Jansen’s Machine Learning for Algorithmic Trading*, rebuilt for people with little or no coding background.*

If the phrase “machine learning trading bot” makes you picture a Wall Street quant surrounded by six monitors, this series is for you. You don’t need a finance degree or years of programming. You need curiosity, a free afternoon, and a willingness to be honest with yourself about what these tools can and can’t do.

This first post sets the foundation: what algorithmic trading actually is, the workflow every serious strategy follows, how to set up Python without pain, and how to run your very first backtest. We won’t even touch machine learning yet — because the biggest beginner mistake is reaching for fancy models before understanding the loop they live inside.

A note before we start. Nothing here is financial advice, and I’m not a financial advisor. This is educational material about building and testing strategies. Markets are adversarial and most retail strategies lose money. Treat everything in this series as a learning exercise, and never risk money you can’t afford to lose.

What “algorithmic trading” really means

Strip away the mystique and algorithmic trading is just this: a set of rules, written in code, that decides when to buy and sell. A rule can be as simple as “buy when the 20-day average price crosses above the 50-day average.” Machine learning enters later as one way to generate those rules from data instead of guessing them.

The reason to write rules in code rather than trade by gut isn’t speed or magic. It’s that code lets you test an idea on years of history before risking a cent. That testing step — the backtest — is the heart of everything.

The ML4T workflow

One of the most useful ideas in Jansen’s book is that every strategy, simple or sophisticated, moves through the same pipeline. Memorize this; it’s your map for the whole series.

  1. Idea — a hypothesis about what predicts returns (“stocks that went up recently keep going up”).
  2. Data — the raw material: prices, volume, fundamentals, news.
  3. Features — turning raw data into informative signals (momentum, volatility, etc.).
  4. Model — a rule or ML model that maps features to a prediction.
  5. Backtest — simulating the strategy on historical data to see if it would have worked.
  6. Execution — actually placing orders (we’ll only ever do this on paper).
  7. Risk management — sizing positions and limiting losses so one bad call doesn’t wipe you out.

Beginners obsess over step 4 (the model). Professionals obsess over steps 2, 3, and 5, because that’s where strategies actually live or die.

Setting up Python (the gentle version)

You need three things: Python, a place to write code, and a few libraries.

The easiest path is to install Anaconda, which bundles Python and most of what you’ll need. Once installed, open a terminal (or Anaconda Prompt) and create a clean workspace:

conda create -n trading python=3.11 -y
conda activate trading
pip install yfinance pandas numpy matplotlib scikit-learn

For writing code, Jupyter Notebook (included with Anaconda) is ideal for beginners — you run code in small chunks and see results immediately. Launch it by typing jupyter notebook.

Get Connie Zhou’s stories in your inbox

Join Medium for free to get updates from this writer.

That’s the whole setup. If a line above fails, copy the error into a search engine; 99% of beginner errors have been hit and solved by thousands of people before you.

Getting free market data

Professionals pay for clean data. You don’t need to. The yfinance library pulls historical prices from Yahoo Finance for free:

import yfinance as yf
# Download daily prices for Apple, 2018 through 2023
data = yf.download("AAPL", start="2018-01-01", end="2024-01-01")
print(data.head())

You’ll get a table with columns like Open, High, Low, Close, and Volume, indexed by date. The Close price is what most simple strategies use.

Your first strategy: a moving-average crossover

Here’s a complete, classic strategy with no machine learning at all. It buys when a short-term average crosses above a long-term average (a sign of upward momentum) and sells when it crosses back below.

import yfinance as yf
import pandas as pd
import matplotlib.pyplot as plt
data = yf.download("AAPL", start="2018-01-01", end="2024-01-01")# Two moving averages of the closing price
data["SMA_short"] = data["Close"].rolling(20).mean()
data["SMA_long"] = data["Close"].rolling(50).mean()
# Signal: 1 = want to be invested, 0 = want to be in cash
data["signal"] = (data["SMA_short"] > data["SMA_long"]).astype(int)
# CRITICAL: act on tomorrow's open, not today's. Shift the signal by one day
# so we only trade on information we'd actually have had.
data["position"] = data["signal"].shift(1)
# Daily returns of the stock, and of our strategy
data["market_return"] = data["Close"].pct_change()
data["strategy_return"] = data["position"] * data["market_return"]
# Compare growth of $1 in each
growth = (1 + data[["market_return", "strategy_return"]]).cumprod()
growth.plot(figsize=(11, 5))
plt.title("Buy & Hold vs. Moving-Average Crossover")
plt.ylabel("Growth of $1")
plt.show()

Run this and you’ll see two lines: how $1 would have grown if you simply held Apple, versus how it would have grown following the crossover rule.

The single most important line in that code

Look again at this line:

data["position"] = data["signal"].shift(1)

That .shift(1) is doing something profound. The signal is computed from today's closing price — but you can't actually trade on a close until the next day. By shifting the position forward one day, we make sure the strategy only ever acts on information it genuinely had at the time.

Forget this, and your backtest will look amazing and your real account will bleed. This mistake is called lookahead bias, and it’s the number-one reason beginner backtests lie. We’ll return to it constantly.

Key takeaways

  • Algorithmic trading is just rules, written in code, that let you test an idea on history before risking money.
  • Every strategy follows the same pipeline: idea → data → features → model → backtest → execution → risk. The model is the part beginners overrate.
  • You can start completely free with Anaconda, Jupyter, and yfinance.
  • Lookahead bias — using information you wouldn’t have had at the time — is the silent killer of beginner strategies. The humble .shift(1) is your defense.

What’s next

In Part 2, we’ll replace the hand-picked crossover rule with an actual machine learning model. You’ll learn to turn raw prices into features and train a model to predict whether tomorrow goes up or down — and you’ll see, honestly, just how hard that really is.

Coming up: Part 2 — Turning Data Into Signals: Feature Engineering and Your First ML Trading Model.

--

--

Connie Zhou
Connie Zhou

Proficient in analyzing, modeling, and deploying ML solutions, I publish one tech blog every week.