Sign In Start Free Trial
Account

Add to playlist

Create a Playlist

Modal Close icon
You need to login to use this feature.
  • Book Overview & Buying Python for Algorithmic Trading Cookbook
  • Table Of Contents Toc
Python for Algorithmic Trading Cookbook

Python for Algorithmic Trading Cookbook - Second Edition

By : Jason Strimpel
close
close
Python for Algorithmic Trading Cookbook

Python for Algorithmic Trading Cookbook

By: Jason Strimpel

Overview of this book

Get practical Python code for algorithmic trading from Jason Strimpel, founder of PyQuant News and a veteran of global trading, risk management, and machine learning. This hands-on guide shows you how to turn market data into tested, automated trading strategies using modern Python tools. You’ll source equities, options, and futures data with OpenBB and FMP, then accelerate Python for data analysis workflows with Pandas, Polars, Parquet, DuckDB, and ArcticDB. You’ll visualize market data with Matplotlib, Seaborn, and Plotly Dash before moving into alpha research and quantitative trading techniques. Detailed recipes help you engineer alpha factors with PCA, regression, Fama-French models, SciPy, and statsmodels. You’ll design and evaluate quantitative trading strategies using VectorBT, Zipline Reloaded, Alphalens Reloaded, and PyFolio, including walk-forward analysis and risk-aware performance review. For execution, you’ll connect to the Interactive Brokers API to stream ticks, manage orders, retrieve portfolio state, and monitor live trading workflows. By the end, you’ll have reusable Python templates for researching, backtesting, evaluating, and operating algorithmic trading strategies.
Table of Contents (19 chapters)
close
close
17
Other Books You May Enjoy
18
Index

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.

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, 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.

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:

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.

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.

Tips and tricks appear like this.

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 [email protected] 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 [email protected] 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.

CONTINUE READING
83
Tech Concepts
36
Programming languages
73
Tech Tools
Icon Unlimited access to the largest independent learning library in tech of over 8,000 expert-authored tech books and videos.
Icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Icon 50+ new titles added per month and exclusive early access to books as they are being written.
Python for Algorithmic Trading Cookbook
notes
bookmark Notes and Bookmarks search Search in title playlist Add to playlist download Download options font-size Font size

Change the font size

margin-width Margin width

Change margin width

day-mode Day/Sepia/Night Modes

Change background colour

Close icon Search
Country selected

Close icon Your notes and bookmarks

Confirmation

Modal Close icon
claim successful

Buy this book with your credits?

Modal Close icon
Are you sure you want to buy this book with one of your credits?
Close
YES, BUY

Submit Your Feedback

Modal Close icon
Modal Close icon
Modal Close icon