Page
1
(This page has no text content)
Page
2
Python for Algorithmic Trading Cookbook Second Edition Recipes for designing, building, and deploying algorithmic trading strategies with Python Jason Strimpel
Page
3
Python for Algorithmic Trading Cookbook Second Edition Copyright © 2026 Packt Publishing All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews. Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book. Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information. Portfolio Director: Sunith Shetty Relationship Lead: Apeksha Shetty Project Manager: Shashank Desai Content Engineer: Tiksha Abhimanyu Lad Technical Editor: Seemanjay Ameriya Indexer: Manju Arasan Production Designer: Deepak Chavan Growth Lead: Merlyn M Shelley First published: August 2024 Second edition: July 2026 Production reference: 1190626 Published by Packt Publishing Ltd. Grosvenor House 11 St Paul's Square Birmingham B3 1RB, UK. ISBN 978-1-80666-203-6 www.packtpub.com
Page
4
Contributors About the author Jason Strimpel is the founder of PyQuant News, co-founder of Quant Science, and Managing Director of Global AI and Advanced Analytics at a top-tier consulting firm. His 20+ year career spans trading, quant risk, ML, and enterprise data across Chicago, London, and Singapore. At BP, he managed $20B in counterparty credit exposure, then led quant engineering globally for BP's derivatives book. In Singapore, he led engineering, data science, and analytics at Rio Tinto Commercial, scaling the team behind its $60B commodities trading business. At AWS, he joined the firm's GenAI operations organization, building internally facing GenAI tools. He holds a Master's in Quantitative Finance from Illinois Institute of Technology.
Page
5
About the reviewer Sudarshan Sawal specializes in quantitative finance with a background in economics and engineering. Currently working at a high-frequency trading (HFT) firm, he leads the quantitative research efforts by managing and guiding a team of researchers focused on developing systematic trading strategies and machine learning-driven research pipelines. Formerly, as Head of Products (Quant) at PredictNow.ai, he enhanced trading models and improved client portfolios, contributing notable research in portfolio optimization using Conditional Portfolio Optimization (CPO). Earlier at QTS Capital Management, he researched trading algorithms and supported clients with machine learning models. He has also represented PredictNow.ai at financial conferences.
Page
6
Table of Contents Preface xi Free benefits with your book ............................................................................ xviii Chapter 1: Acquire Free Financial Market Data with Cutting-Edge Python Libraries 1 Technical requirements ........................................................................................ 2 Working with stock market data on the OpenBB platform ..................................... 4 Comparison of fundamental data • 6 Building stock screeners • 8 Fetching historical futures data with the OpenBB platform ................................. 10 Navigating options market data with the OpenBB platform .................................. 15 Option Greeks • 19 Harnessing factor data using pandas_datareader ................................................. 20 Chapter 2: Analyze and Transform Financial Market Data with pandas 25 Diving into pandas index types ........................................................................... 26 DatetimeIndex • 27 PeriodIndex • 28 MultiIndex • 28 Building pandas Series and DataFrames .............................................................. 29 Building a MultiIndex DataFrame from scratch • 32 Reindexing an existing DataFrame with a MultiIndex object • 33 Manipulating and transforming DataFrames ...................................................... 36 Creating new columns using aggregates, Booleans, and strings • 37 Concatenating two DataFrames together • 39 Pivoting a DataFrame such as Excel • 40 Grouping data on a key or index and applying an aggregate • 41
Page
7
Joining options data together to create straddle prices • 42 Grouping by multiple columns • 44 Applying different methods to different columns • 45 Applying custom functions • 47 Grouping and transforming data • 47 Examining and selecting data from DataFrames .................................................. 48 Selection by label using loc • 51 Selection by position using iloc • 51 Selection by Boolean indexing • 52 Partial string indexing • 53 Using at for fast access to a scalar • 53 Using nsmallest and nlargest • 54 Using the query method to query DataFrames • 54 Calculating asset returns using pandas ............................................................... 54 Measuring the volatility of a return series ........................................................... 59 Generating a cumulative return series ................................................................. 63 The cumulative sum of simple returns • 64 The cumulative sum of compound returns • 65 Resampling data for different time frames ........................................................... 67 Addressing missing data issues ........................................................................... 73 Applying custom functions to analyze time series data ........................................ 78 Chapter 3: Accelerate Financial Market Data Analysis with Polars and DuckDB 83 Technical requirements ...................................................................................... 84 Converting CSV files to parquet for efficient storage ............................................ 84 Using asynchronous python to speed up processing ............................................. 88 Manipulating financial market data with polars .................................................. 98 Integrating polars with DuckDB for analysis ..................................................... 106 Building a high-performance data lake over parquet files with DuckLake ........... 115 121 Table of Contents vi
Page
8
Chapter 4: Visualize Financial Market Data with Matplotlib, Seaborn, and Plotly Dash Quickly visualizing data using pandas ................................................................ 122 Animating the evolution of the yield curve with matplotlib ................................ 131 Plotting options implied volatility surfaces with matplotlib ............................... 136 Visualizing statistical relationships with Seaborn ............................................. 140 Creating an interactive PCA analytics dashboard with Plotly Dash ...................... 147 Chapter 5: Build a Quantamental Research Database with Hedge Fund Tools 157 Technical requirements ..................................................................................... 158 Creating bias-free historical datasets with versioned data and time travel ........... 158 Compute rolling metrics on millions of rows of historic price data ...................... 166 Building a Warren Buffett value stock screener with historical fundamental data ..... 174 Building an options data analytics query tool with millions of rows of options data .. 178 Chapter 6: Conduct Market Research with Advanced AI and Agentic Workflows 185 Building your own AI equity research analyst to analyze financial statements .... 186 Writing Python code to analyze stock price performance automatically with AI .. 191 Using AI agentic workflows to automate comparative analysis ........................... 196 Automating equity research reports with AI ...................................................... 206 Converting trading strategy research papers into code with LlamaIndex ............. 213 Chapter 7: Build Alpha Factors for Stock Portfolios 221 Identifying latent return drivers using principal component analysis ................ 222 Finding and hedging portfolio beta using linear regression ................................ 228 Analyzing portfolio sensitivities to the Fama-French factors .............................. 234 Assessing market inefficiency based on volatility ............................................... 242 Preparing a factor ranking model using zipline pipeline .................................... 249 For windows, Unix/Linux, and mac intel users • 249 vii Table of Contents
Page
9
For apple silicon users • 250 Chapter 8: Vector-Based Backtesting with VectorBT 255 Building technical strategies with VectorBT ....................................................... 255 Conducting walk-forward optimization with vectorbt ...................................... 263 Optimizing the SuperTrend strategy with VectorBT Pro .................................... 269 For Windows, Unix/Linux, and Mac Intel users • 270 For Apple Silicon users • 270 Chapter 9: Event-Based Backtesting Factor Portfolios with Zipline Reloaded 281 Technical requirements ..................................................................................... 281 For Windows, Unix/Linux, and Mac Intel users • 282 For Mac M1/M2 users • 282 Backtesting a momentum factor strategy with Zipline Reloaded ........................ 282 Exploring a mean reversion strategy with Zipline Reloaded ............................... 294 Chapter 10: Evaluate Factor Risk and Performance with Alphalens Reloaded 307 Preparing backtest results ................................................................................ 308 Evaluating the information coefficient ............................................................... 314 Examining factor returns performance ............................................................. 320 Evaluating factor turnover ................................................................................. 327 Chapter 11: Assess Backtest Risk and Performance Metrics with Pyfolio 335 Preparing Zipline backtest results for Pyfolio Reloaded ...................................... 336 Generating strategy performance and return analytics ...................................... 342 Building a drawdown and rolling risk analysis .................................................. 350 Analyzing strategy holdings, leverage, exposure, and sector allocations ............. 356 Breaking down strategy performance to trade level ........................................... 365 Table of Contents viii
Page
10
Chapter 12: Set Up the Interactive Brokers Python API 373 Building an algorithmic trading app .................................................................. 374 Request-callback pattern • 379 Inheritance and overriding • 380 Our trading app class • 380 Creating a Contract object with the IB API ........................................................ 383 Creating an Order object with the IB API ........................................................... 387 Fetching historical market data ........................................................................ 390 Requesting historic data • 394 Receiving historic data • 396 Getting a market data snapshot ........................................................................ 400 Streaming live market data ............................................................................... 402 Requesting streaming data • 407 Receiving streaming data • 408 Storing live tick data in a local SQL database ..................................................... 410 Chapter 13: Manage Orders, Positions, and Portfolios with the IB API 417 Executing orders with the IB API ....................................................................... 418 Getting details about your portfolio .................................................................. 424 Inspecting positions and position details .......................................................... 428 Computing portfolio profit and loss ................................................................... 431 Chapter 14: Deploy Strategies to a Live Environment 435 Calculating real-time key performance and risk indicators ................................ 436 Cumulative returns • 440 Max drawdown • 441 Volatility • 441 Omega ratio • 441 Sharpe ratio • 442 Conditional value at risk • 442 ix Table of Contents
Page
11
Sending orders based on portfolio targets .......................................................... 443 Ordering for a fixed amount of money with order_value • 447 Ordering to adjust a position to the target number of shares with order_target_quantity • 447 Ordering to a given percent of current portfolio value with order_percent • 448 Ordering to adjust a position to a target value with order_target_value • 448 Ordering to adjust a position to a target value with order_target_value • 449 Ordering to adjust a position to a target percent of the current portfolio value with order_target_percent • 449 Deploying a monthly factor portfolio strategy .................................................... 451 Deploying an options combo strategy ............................................................... 458 Deploying an intraday multi-asset mean-reversion strategy .............................. 464 Chapter 15: Advanced Recipes for GPU-Accelerated Trading Research 475 Technical requirements .................................................................................... 476 Accelerating large-scale financial data wrangling with cuDF .............................. 477 Speeding up factor model training with cuML ................................................... 483 Building GPU-accelerated asset correlation networks with cuGraph .................. 489 Running GPU-accelerated portfolio optimization with cuOpt ............................ 495 Chapter 16: Unlock Your Exclusive Benefits 501 Unlock this Book's Free Benefits in 3 Easy Steps ................................................. 502 Other Books You May Enjoy 506 Index 509 Table of Contents x
Page
12
Preface Algorithmic trading combines statistical models, programming, and quantitative methods to systematically trade financial assets. Markets now generate orders of magnitude more data than a discretionary trader can process, and the firms producing the best risk-adjusted returns are the ones with the most disciplined research, backtesting, and execution infrastructure. Python for Algorithmic Trading Cookbook, Second Edition gives you 68 hands-on recipes across 15 chapters to design, backtest, and deploy your own algorithmic trading strategies in Python. The code spans 51 annotated Jupyter notebooks and 17 modular Python trading applications, plus four GPU-accelerated research scripts. Most trading books still focus on technical analysis indicators applied to small datasets. Those approaches rarely survive contact with live markets. This book brings professional techniques and tools to non-professionals in small, digestible recipes. You will learn how to source institutional-quality data, accelerate analysis with columnar engines, store research datasets free from lookahead bias, build alpha factors, evaluate them rigorously, and execute strategies through a production-grade Interactive Brokers trading application. This second edition reflects how the algorithmic trading toolchain has evolved in the past two years. Three chapters are new. Chapter 3 covers Parquet, Polars, and DuckDB for fast, scalable analytics over financial datasets. Chapter 5 introduces ArcticDB, the high-performance DataFrame database used by Man Group to manage petabyte-scale market data. Chapter 6 covers AI and agentic workflows built on LangChain and LlamaIndex, including an AI equity research analyst, multi-agent comparative analysis, and converting research papers into executable Python. Chapter 15 has been rewritten end-to-end to GPU-accelerate the research stack with NVIDIA RAPIDS, demonstrating how to wrangle 267 million rows with cudf.pandas, train factor models with cuml.accel, compute correlation networks across 10,000 stocks with nx‑cugraph, and solve Mean-CVaR portfolio optimization with NVIDIA cuOpt. I have spent 20+ years inside real trading environments building, trading, and managing risk across the U.S., Europe, and Asia. I started on a Chicago hedge fund desk, became a risk manager at JPMorgan, traded derivatives, led production risk technology for an energy derivatives firm in London, served as APAC CIO of a financial software company in Singapore, and built the data science function for a global metals trading firm. The techniques in this book reflect the workflows used in those environments. I have taught the same material to 1,700+ students through my course, Getting Started With Python for Quant Finance.
Page
13
Python gives you direct access to financial data, fast numerical computation, the broadest ecosystem of quantitative libraries in any language, and a path to production. This book takes you from raw market data to live algorithmic trading without skipping the parts in between. By the end of this book you will have a working toolkit to design, validate, and deploy systematic strategies. Markets change. The advantage goes to traders who can iterate on research and ship code faster than the competition. Who this book is for This book is for traders, investors, and Python developers who want practical recipes for designing, backtesting, and deploying algorithmic trading strategies. The three target personas are: Active traders and investors: Individuals already investing in the markets who want to use algorithmic methods to enhance performance. You will learn how to acquire and process market data with OpenBB, build a research database with ArcticDB, and run AI-driven equity research with LangChain and LlamaIndex. Python developers with market interest: Developers comfortable with pandas and NumPy who want to apply their programming skills to financial markets. You will learn how to accelerate analysis with Polars and DuckDB, engineer alpha factors with PCA and Fama-French models, and run walk-forward optimization with VectorBT. Aspiring algorithmic traders: Readers with basic Python experience who want to enter the field. You will build production-ready backtests with Zipline Reloaded, evaluate factor quality with Alphalens Reloaded and Pyfolio Reloaded, build a modular trading application on the Interactive Brokers API, and deploy live factor, options combo, and intraday mean reversion strategies. You should have basic familiarity with Python syntax and core libraries like pandas and NumPy. No prior trading experience is assumed, though comfort with financial markets terminology will accelerate your progress. What this book covers Chapter 1, Acquire Free Financial Market Data with Cutting-Edge Python Libraries, covers practical methods for sourcing financial market data. You will work with stock, futures, and options data through the OpenBB Platform, fetch Fama-French factor data with pandas-datareader, and bulk-download historical fundamentals with Financial Modeling Prep. Chapter 2, Analyze and Transform Financial Market Data with pandas, covers the core pandas operations used throughout the rest of the book. You will work with index types, build Series and DataFrames, manipulate and transform tabular data, compute simple and log returns, • • • Preface xii
Page
14
measure volatility, generate cumulative return series, resample time series, handle missing data, and apply custom functions to financial datasets. Chapter 3, Accelerate Financial Market Data Analysis with Polars and DuckDB, covers fast, scalable analytics over financial datasets. You will convert CSV files into compressed Parquet, manipulate time series with Polars, query Parquet directly with Polars expressions, integrate Polars with DuckDB for hybrid SQL and DataFrame analytics, and build a high-performance datalake with DuckLake. Chapter 4, Visualize Financial Market Data with Matplotlib, Seaborn, and Plotly Dash, covers visualization techniques for financial data. You will quickly visualize data with pandas, animate yield curve evolution with Matplotlib, plot options implied volatility surfaces, visualize statistical relationships with Seaborn, and build an interactive PCA analytics dashboard with Plotly Dash. Chapter 5, Build a Quantamental Research Database with Hedge Fund Tools, covers ArcticDB, the high-performance DataFrame database from Man Group. You will create bias-free historical datasets with versioning and time travel, build an options analytics tool over millions of rows, construct a Warren Buffett style value stock screener from historical fundamentals, and compute rolling metrics across massive datasets. Chapter 6, Conduct Market Research with Advanced AI and Agentic Workflows, covers applying large language models and agentic workflows to automate market research. You will build an AI equity research analyst that queries annual reports, write Python code with AI to analyze stock performance, run agentic comparative analysis across companies, automate multi-agent equity research reports, and convert trading strategy research papers into executable code with LlamaIndex. Chapter 7, Build Alpha Factors for Stock Portfolios, covers alpha factor construction. You will identify latent return drivers with principal component analysis, hedge portfolio beta with linear regression, analyze portfolio sensitivities to Fama-French factors, assess market inefficiency through volatility, and prepare a factor ranking model with Zipline Pipelines. Chapter 8, Vector-Based Backtesting with VectorBT, covers high-performance vectorized backtesting. You will build technical strategies with VectorBT, conduct walk-forward optimization to test robustness out of sample, and optimize the SuperTrend strategy with VectorBT Pro at scale. Chapter 9, Event-Based Backtesting Factor Portfolios with Zipline Reloaded, covers event-driven backtesting. You will backtest a momentum factor strategy and a mean reversion strategy with Zipline Reloaded, learning how to structure pipelines, schedule rebalances, and track portfolio performance under realistic execution assumptions. xiii Preface
Page
15
Chapter 10, Evaluate Factor Risk and Performance with Alphalens Reloaded, covers factor evaluation. You will prepare Zipline backtest results for Alphalens, evaluate the information coefficient, examine factor return performance and decay, and measure factor turnover to assess the durability of an alpha signal. Chapter 11, Assess Backtest Risk and Performance Metrics with Pyfolio, covers portfolio analytics. You will prepare Zipline results for Pyfolio Reloaded, generate strategy performance and return analytics, build drawdown and rolling risk analyses, examine holdings, leverage, exposure, and sector allocations, and break performance down to the trade level. Chapter 12, Set Up the Interactive Brokers Python API, covers the infrastructure for live trading. You will build a modular algorithmic trading app, create Contract and Order objects with the IB API, fetch historical market data, request market data snapshots, stream live tick data, and persist tick data in a local SQL database. Chapter 13, Manage Orders, Positions, and Portfolios with the IB API, covers trade and portfolio management. You will execute market, limit, stop, and trailing stop orders, manage placed orders, query portfolio details, inspect positions, and compute portfolio profit and loss in real time. Chapter 14, Deploy Strategies to a Live Environment, covers live deployment. You will compute real-time performance and risk indicators, send orders driven by portfolio targets, and deploy a monthly factor portfolio, an options combo strategy, and an intraday multi-asset mean reversion strategy. Chapter 15, Advanced Recipes for GPU-Accelerated Trading Research, covers NVIDIA RAPIDS for GPU acceleration. You will wrangle 267 million rows of global equity data with cudf.pandas, train Random Forest factor models and run KMeans regime detection on 2 million observations with cuml.accel, build and analyze a 10,000-node asset correlation network with nx‑cugraph, and solve a Mean-CVaR portfolio optimization problem with NVIDIA cuOpt as the solver backend through CVXPY. To get the most out of this book You will need Python 3.11 to work through the examples. All notebooks specify Python 3 as the kernel, and the code in Chapters 1 through 11 follows a consistent procedural style with imports at the top, minimal abstractions, and one concept per cell. Chapters 12 through 14 build a modular Python trading application across 17 incremental recipe directories, each composed of app.py, wrapper.py, client.py, contract.py, order.py, and utils.py modules. Chapter 15 requires an NVIDIA GPU and the RAPIDS ecosystem. The full list of libraries and versions used across the book: Preface xiv
Page
16
Software/hardware covered Operating system requirements Python 3.11 Windows, macOS, or Linux pandas 2+, NumPy OpenBB Platform 4+, yfinance, pandas-datareader, ThetaData Polars 1.35.2, DuckDB 1.4.2, PyArrow Matplotlib, Seaborn, Plotly 6.5.0, Streamlit 1.51.0 ArcticDB 5.1.1 (conda install required) LangChain 0.3.x, LlamaIndex 0.12.x scikit-learn, statsmodels, TA-Lib VectorBT 0.28.1, Zipline Reloaded 3.1.1 Alphalens Reloaded 0.4.6, Pyfolio Reloaded 0.9.9 Interactive Brokers API (ibapi), empyrical, exchange_calendars NVIDIA RAPIDS (cudf.pandas, cuml.accel, nx- cugraph, cuOpt) NVIDIA GPU required for Chapter 15 Specific installation instructions are included in each chapter where a library is first introduced. If you are using the digital version of this book, type the code yourself or clone it from the GitHub repository linked in the next section. Doing so avoids errors from copy and paste and reinforces the patterns used throughout the book. Download the example code files You can download the example code files for this book from GitHub at https://github.com/ PacktPublishing/Python-for-Algorithmic-Trading-Cookbook-Second-Edition. If there is an update to the code, it will be updated in the GitHub repository. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out. xv Preface
Page
17
Download the color images We also provide a PDF file that has color images of the screenshots and diagrams used in this book. You can download it from the Packt product page for this title. Conventions used There are a number of text conventions used throughout this book. Code in text: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and library names. Here is an example: "Import pandas as pd and call pd.read_parquet() to load a Parquet file into a DataFrame." A block of code is set as follows: returns = df.close.pct_change() returns.name = "return" returns.plot.bar( title="AAPL returns", grid=False, legend=True, xticks=[] ) Any command-line input or output is written as follows: $ conda install -c conda-forge arcticdb$ pip install vectorbt zipline-reloaded Bold: Indicates a new term, an important word, or words that you see onscreen. For instance, words in menus or dialog boxes appear in bold. Here is an example: "Select Paper Trading from the Account menu in Trader Workstation." Warnings or important notes appear like this. Note Tips and tricks appear like this. Tip Preface xvi
Page
18
Get in touch Feedback from our readers is always welcome. General feedback: If you have questions about any aspect of this book, email us at customercare@packtpub.com and mention the book title in the subject of your message. Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report it. Please visit www.packtpub.com/support/errata and fill in the form. Piracy: If you come across any illegal copies of our works in any form on the internet, we would be grateful if you would provide us with the location address or website name. Please contact us at copyright@packt.com with a link to the material. If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com. xvii Preface
Page
19
Free benefits with your book This book comes with free benefits to support your learning. Activate them now for instant access (see the "How to Unlock" section for instructions). Here's a quick overview of what you can instantly unlock with your purchase: Preface xviii
Page
20
How to Unlock Scan the QR code (or go to packtpub.com/unlock). Search for this book by name, confirm the edition, and then follow the steps on the page. Note: Keep your invoice handy. Purchases made directly from Packt don't require one Share your thoughts Once you've read Python for Algorithmic Trading Cookbook, Second Edition, we'd love to hear your thoughts! Scan the QR code below to go straight to the Amazon review page for this book and share your feedback. https://packt.link/r/1806662035 Your review is important to us and the tech community and will help us make sure we're delivering excellent quality content. xix Preface