⚠ Trading involves significant risk of loss. Everything on this site is for education only and is not financial advice.
Trading

Python for Traders & Investors: From Price Data to a Backtest

Learn to set up a Python research environment, load and clean price data with pandas, compute returns and indicators correctly, and build, measure and review your own backtests in code.

Level: IntermediateDuration: about 14 hours13 lessonsAuthor: Moustafa Hijazi

Start free lesson 1Join for free

Self-study course Self-study course: written lessons, videos and downloadable materials for independent learning. There is no supervision, assessment, individual feedback or tutoring. Self-check quizzes are evaluated automatically in your browser — we do not see your results.

All 13 lessons free

Before you start

  • Understanding of backtesting concepts such as look-ahead bias, costs and performance metrics (as in the Systematic Trading & Backtesting course)
  • Familiarity with moving averages, RSI and ATR (as in the Technical Analysis in Depth course)
  • A computer on which you can install software; no prior programming experience is required

What you will be able to do

  • Set up an isolated Python environment with pandas, numpy, matplotlib and Jupyter and keep it reproducible
  • Load, clean and adjust price data from files and free APIs and resample it to other timeframes
  • Compute simple and log returns, annualised return and volatility, and the standard indicators as vectorised functions
  • Build a vectorised and an event-driven backtest with correct timing, costs, stops and position sizing
  • Code and unit-test performance metrics such as CAGR, maximum drawdown, Sharpe and profit factor
  • Automate a daily watchlist script and review a research notebook against look-ahead bias and overfitting

Lessons in this course

Setting Up a Research Environment: Python, Virtual Environments, Jupyter and VS Code

Install Python, create an isolated project environment, add pandas, numpy and matplotlib, and run your first notebook calculation.

Free

Python Essentials for Finance in One Session: Data Types, Lists, Dictionaries, Loops, Functions and Error Messages

Learn the minimum core Python a trader needs: numbers, strings, lists, dictionaries, loops, functions and how to read a traceback.

Free

pandas Fundamentals: Series, DataFrames, the DatetimeIndex, Selecting and Filtering, and Resampling Daily Bars to Weekly

Understand Series and DataFrames, index price data by date, select rows with loc and iloc, filter with boolean masks and aggregate daily bars into weekly bars.

Free

Loading Price Data: CSV Files and Free APIs, Adjusted versus Unadjusted Prices, Missing Values and Time Zones

Read price files and API downloads into a clean DataFrame, understand how split and dividend adjustments work, and handle gaps and time zones correctly.

Free

Returns in Code: Simple versus Log Returns, Cumulative Returns, Annualised Return and Volatility, and Rolling Windows

Compute simple and log returns in pandas, compound them correctly, annualise return and volatility, and build rolling statistics.

Free

Indicators in Code: Vectorised SMA, EMA, RSI, ATR and Bollinger Bands, Verified against a Charting Platform

Write vectorised pandas functions for the five most used indicators and learn why their values can differ from a charting platform and how to reconcile them.

Free

A Vectorised Backtest: Signals, Positions, Shifting to Avoid Look-Ahead, Transaction Costs and the Equity Curve

Build a complete vectorised backtest of a moving-average rule in pandas, including the position shift, per-trade costs, the equity curve and a benchmark comparison.

Free

An Event-Driven Backtest: A Loop Engine with ATR Stops, Position Sizing and a Trade List in R-Multiples

Build a bar-by-bar backtest loop in Python that sizes positions by ATR risk, honours stops including gaps, and records every trade in R-multiples.

Free

Performance Metrics as Reusable Functions: CAGR, Drawdown, Sharpe, Sortino, Profit Factor and Their Unit Tests

Write a small metrics module with annualisation done correctly, add rolling versions, and prove the functions with pytest against values you calculated by hand.

Free

Plotting for Analysis: Price with Indicators, Equity and Drawdown Charts, Return Distributions and Exporting Figures

Use matplotlib's figure-and-axes interface to build the four charts every backtest report needs, read them correctly, and export them at print quality.

Free

Portfolio Analysis in pandas: Correlation and Covariance Matrices, Weighted Portfolio Volatility and a Rebalancing Simulation

Compute annualised covariance and correlation matrices from returns, derive portfolio volatility and risk contributions with NumPy, and simulate drift versus calendar rebalancing.

Free

Automating a Daily Watchlist: A Scheduled Script That Fetches Data, Computes Signals and Writes a Report, plus API-Key and Rate-Limit Pitfalls

Turn notebook code into a robust command-line script with configuration, logging, retries with back-off, safe API-key handling and a scheduler, and write a daily report file.

Free

A Complete Research-Notebook Project from Data to Report, with a Code-Review Checklist against Look-Ahead Bias and Overfitting

Organise a full strategy study as a reproducible project, run it from raw data to a written result, and review the code with a checklist that catches the errors that flatter backtests.

Free
Recommended next course

Prop Firms, Funded Accounts & Trading as a Business

Continue with Prop Firms, Funded Accounts & Trading as a Business to learn how a tested approach fits into evaluation rules, capital allocation and the business side of trading.

View course outline