Skip to content

Chapter 21: AI for Finance

Apply ML to markets responsibly: returns and risk metrics (Sharpe, drawdown), a moving-average strategy, honest backtesting, and the biases that wreck naive results.


Metadata

Field Value
Track Advanced
Time 10 hours
Prerequisites Chapters 1, 3, 4, 6, 7

Learning Objectives

  • Compute returns (simple and log) and explain when to use each
  • Measure risk-adjusted return with the annualized Sharpe ratio
  • Quantify downside with maximum drawdown
  • Build a signal from a moving-average crossover
  • Backtest a strategy and produce an equity curve
  • Avoid look-ahead bias by lagging signals correctly
  • Account for costs and understand why they dominate high-turnover strategies
  • Reason about overfitting and the dangers of multiple-testing on price data

What's Included

Notebooks

Notebook Description
01_returns_and_risk.ipynb Simple vs log returns, Sharpe ratio, and maximum drawdown
02_strategy_and_backtest.ipynb Moving-average crossover signal and a look-ahead-safe backtest
03_pitfalls_and_ml.ipynb Look-ahead bias, overfitting, and where ML fits in markets

Scripts

  • config.py — Chapter config: seeds, annualization factor, cost assumptions
  • metrics.py — Returns, Sharpe ratio, maximum drawdown, volatility
  • backtest.py — Moving-average crossover signal and a lagged backtester

Exercises

  • Problem Set 1: Returns & Risk — Compute Sharpe and maximum drawdown and check their signs
  • Problem Set 2: Backtesting — Run a backtest and prove the look-ahead lag matters
  • Solutions — in exercises/solutions/ (notebooks and solutions.py for CI)

Diagrams (Mermaid)

  • backtest_flow.mermaid, risk_metrics.mermaid

Read Online

  • 21.1 Introduction — Simple vs log returns, Sharpe ratio, and maximum drawdown
  • 21.2 Intermediate — Moving-average crossover signal and a look-ahead-safe backtest
  • 21.3 Advanced — Look-ahead bias, overfitting, and where ML fits in markets

Or try the code in the Playground.

How to Use This Chapter

Quick Start

Clone the repo, install dependencies, and open the first notebook.

git clone https://github.com/luigipascal/berta-chapters.git
cd berta-chapters/chapters/chapter-21-ai-for-finance
pip install -r requirements.txt
jupyter notebook notebooks/01_returns_and_risk.ipynb

GitHub Folder

All chapter materials live in: chapters/chapter-21-ai-for-finance/


Created by Luigi Pascal Rondanini | Generated by Berta AI