Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases now! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Python for Algorithmic Trading Cookbook
Python for Algorithmic Trading Cookbook

Python for Algorithmic Trading Cookbook: Recipes for designing, building, and deploying algorithmic trading strategies with Python

eBook
€24.99 €35.99
Paperback
€44.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Product feature icon AI Assistant (beta) to help accelerate your learning
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Table of content icon View table of contents Preview book icon Preview Book

Python for Algorithmic Trading Cookbook

Analyze and Transform Financial Market Data with pandas

The pandas library was invented by Wes McKinney while at the investment management firm AQR Capital Management, where he researched macro and credit trading strategies. He built pandas to provide flexible, easy-to-use data structures for data analysis. Since it was open sourced in 2009, pandas has become the standard tool to analyze and transform data using Python.

pandas is well-suited for working with tabular data, like that stored in spreadsheets or databases, and it integrates well with many other data analysis libraries in the Python ecosystem. Its capabilities extend to handling missing data, reshaping datasets, and merging and joining datasets, and it also provides robust tools for loading data from flat files, Excel files, databases, and HDF5 file formats. It’s widely used in academia, finance, and many areas of business due to its rich features and ease of use.

This chapter will begin by covering recipes...

Diving into pandas index types

The Index is an immutable sequence that’s used for indexing and alignment that serves as the label or key for rows in the DataFrame or elements in a series. It allows for fast lookup and relational operations and as of pandas version 2, it can contain values of any type, including integers, strings, and even tuples. Indexes in pandas are immutable, which makes them safe to share across multiple DataFrames or Series. They also have several built-in methods for common operations, such as sorting, grouping, and set operations such as union and intersection. pandas supports multiple indexes, allowing for complex, hierarchical data organization. This feature is particularly useful when dealing with high-dimensional data such as option chains. We’ll see examples of MultiIndexes later in this chapter.

There are seven types of pandas indexes. The differences are dependent on the type of data used to create the index. For example, an Int64Index...

Analyze and Transform Financial Market Data with pandas

The pandas library was invented by Wes McKinney while at the investment management firm AQR Capital Management, where he researched macro and credit trading strategies. He built pandas to provide flexible, easy-to-use data structures for data analysis. Since it was open sourced in 2009, pandas has become the standard tool to analyze and transform data using Python.

pandas is well-suited for working with tabular data, like that stored in spreadsheets or databases, and it integrates well with many other data analysis libraries in the Python ecosystem. Its capabilities extend to handling missing data, reshaping datasets, and merging and joining datasets, and it also provides robust tools for loading data from flat files, Excel files, databases, and HDF5 file formats. It’s widely used in academia, finance, and many areas of business due to its rich features and ease of use.

This chapter will begin by covering recipes...

Diving into pandas index types

The Index is an immutable sequence that’s used for indexing and alignment that serves as the label or key for rows in the DataFrame or elements in a series. It allows for fast lookup and relational operations and as of pandas version 2, it can contain values of any type, including integers, strings, and even tuples. Indexes in pandas are immutable, which makes them safe to share across multiple DataFrames or Series. They also have several built-in methods for common operations, such as sorting, grouping, and set operations such as union and intersection. pandas supports multiple indexes, allowing for complex, hierarchical data organization. This feature is particularly useful when dealing with high-dimensional data such as option chains. We’ll see examples of MultiIndexes later in this chapter.

There are seven types of pandas indexes. The differences are dependent on the type of data used to create the index. For example, an Int64Index...

Building pandas Series and DataFrames

A Series is a one-dimensional labeled array that can hold any data type, including integers, floats, strings, and objects. The axis labels of a Series are collectively referred to as the index, which allows for easy data manipulation and access. A key feature of the pandas Series is its ability to handle missing data, represented as a NumPy nan (Not a Number).

Important

NumPy’s nan is a special floating-point value. It is commonly used as a marker for missing data in numerical datasets. The nan value being a float is useful because it can be used in numerical computations and included in arrays of numbers without changing their data type, which aids in maintaining consistent data types in numeric datasets. Unlike other values, nan doesn’t equal anything, which is why we need to use functions such as numpy.isnan() to check for nan.

Furthermore, the Series object provides a host of methods for operations such as statistical...

Manipulating and transforming DataFrames

Before moving on to more advanced recipes, it’s important to understand the fundamentals of working with data. DataFrames are the most common pandas data structures you’ll work with. Despite the existence of hundreds of methods for DataFrame manipulation, only a subset of these are regularly used.

In this recipe, we will show you how to manipulate a DataFrame using the following common methods:

  • Creating new columns using aggregates, Booleans, and strings
  • Concatenating two DataFrames together
  • Pivoting a DataFrame such as Excel
  • Grouping data on a key or index and applying an aggregate
  • Joining options data together to create straddle prices

Getting ready…

We’ll start by importing the necessary libraries and downloading market price data:

  1. Start by importing NumPy, pandas, and the OpenBB Platform:
    import numpy as np
    import pandas as pd
    from openbb import obb
    obb.user.preferences...

Examining and selecting data from DataFrames

Once you’ve loaded, manipulated, and transformed data in DataFrames, the next step is retrieving the data from DataFrames. This is where indexing and selecting data come into play. This functionality allows you to access data using methods such as iloc and loc and techniques such as Boolean indexing or query functions. These methods can target data based on its position, labels, or condition based on whether you’re after a specific row, column, or combination. Inspection enables potential issues to be identified, such as missing values, outliers, or inconsistencies, that can affect analysis and modeling. Additionally, an initial inspection provides insights into the nature of data, helping determine appropriate preprocessing steps and analysis methods.

How to do it…

Let’s start by downloading stock price data:

  1. Start by importing pandas and the OpenBB Platform:
    import pandas as pd
    from openbb import...

Calculating asset returns using pandas

Returns are integral to understanding the performance of a portfolio. There are two types: simple returns and compound (or log) returns.

Simple returns, which are calculated as the difference in price from one period to the next divided by the price at the beginning of the period, are beneficial in certain circumstances. They aggregate across assets, meaning the simple return of a portfolio is the aggregate of the returns of the individual assets, weighted according to their proportions. This trait makes simple returns practical for comparing assets and evaluating portfolio performance over short-term intervals.

Simple returns are defined as follows:

R t =  P t P t1 _ P t1  =  P t _ P t1  1

On the other hand, compound returns, which are calculated using the natural logarithm of the price-relative change, are additive over...

Measuring the volatility of a return series

Volatility plays an integral role in finance, serving as a key indicator of risk linked to a particular asset. A higher degree of volatility suggests a greater risk associated with the asset as it indicates more significant price changes and, therefore, a less predictable investment outcome.

Standard deviation is widely used as the measure of asset return volatility. It statistically quantifies the dispersion of asset returns from their mean, thus providing an effective metric for risk. When asset returns exhibit a larger standard deviation, it signifies more pronounced volatility, pointing to a higher risk level. Conversely, a lower standard deviation implies that the asset returns are more stable and less likely to deviate significantly from their average, indicating a lower risk.

The standard deviation’s value as a risk measure extends beyond its ability to quantify risk alone. It is a common component in calculating risk...

Generating a cumulative return series

Cumulative returns quantify the total change in the value of an investment over a specific period. To compute the cumulative return of a series of simple single-period returns, you need to add 1 to each return, then multiply these results together, and finally subtract 1 from the product. Recall the formula for the simple return:

R t =  P t P t1 _ P t1  =  P t _ P t1  1

Upon writing ( P t _ P t2) = ( P t _ P t1)( P t1 _ P t2), the two-period return can be expressed as follows:

R(2) = ( P t _ P t1 )( P t1 _ P t2 ) 1

= (1 + R t)(1 + R t1) 1

To compute the cumulative return of a series of continuously...

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Follow practical Python recipes to acquire, visualize, and store market data for market research
  • Design, backtest, and evaluate the performance of trading strategies using professional techniques
  • Deploy trading strategies built in Python to a live trading environment with API connectivity
  • Purchase of the print or Kindle book includes a free PDF eBook

Description

Discover how Python has made algorithmic trading accessible to non-professionals with unparalleled expertise and practical insights from Jason Strimpel, founder of PyQuant News and a seasoned professional with global experience in trading and risk management. This book guides you through from the basics of quantitative finance and data acquisition to advanced stages of backtesting and live trading. Detailed recipes will help you leverage the cutting-edge OpenBB SDK to gather freely available data for stocks, options, and futures, and build your own research environment using lightning-fast storage techniques like SQLite, HDF5, and ArcticDB. This book shows you how to use SciPy and statsmodels to identify alpha factors and hedge risk, and construct momentum and mean-reversion factors. You’ll optimize strategy parameters with walk-forward optimization using VectorBT and construct a production-ready backtest using Zipline Reloaded. Implementing all that you’ve learned, you’ll set up and deploy your algorithmic trading strategies in a live trading environment using the Interactive Brokers API, allowing you to stream tick-level data, submit orders, and retrieve portfolio details. By the end of this algorithmic trading book, you'll not only have grasped the essential concepts but also the practical skills needed to implement and execute sophisticated trading strategies using Python.

Who is this book for?

Python for Algorithmic Trading Cookbook equips traders, investors, and Python developers with code to design, backtest, and deploy algorithmic trading strategies. You should have experience investing in the stock market, knowledge of Python data structures, and a basic understanding of using Python libraries like pandas. This book is also ideal for individuals with Python experience who are already active in the market or are aspiring to be.

What you will learn

  • Acquire and process freely available market data with the OpenBB Platform
  • Build a research environment and populate it with financial market data
  • Use machine learning to identify alpha factors and engineer them into signals
  • Use VectorBT to find strategy parameters using walk-forward optimization
  • Build production-ready backtests with Zipline Reloaded and evaluate factor performance
  • Set up the code framework to connect and send an order to Interactive Brokers

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Aug 16, 2024
Length: 404 pages
Edition : 1st
Language : English
ISBN-13 : 9781835087763
Category :
Languages :
Concepts :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Product feature icon AI Assistant (beta) to help accelerate your learning
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

Publication date : Aug 16, 2024
Length: 404 pages
Edition : 1st
Language : English
ISBN-13 : 9781835087763
Category :
Languages :
Concepts :

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
€189.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts
€264.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 118.97
Modern Time Series Forecasting with Python
€39.99
Python Feature Engineering Cookbook
€33.99
Python for Algorithmic Trading Cookbook
€44.99
Total 118.97 Stars icon

Table of Contents

15 Chapters
Chapter 1: Acquire Free Financial Market Data with Cutting-Edge Python Libraries Chevron down icon Chevron up icon
Chapter 2: Analyze and Transform Financial Market Data with pandas Chevron down icon Chevron up icon
Chapter 3: Visualize Financial Market Data with Matplotlib, Seaborn, and Plotly Dash Chevron down icon Chevron up icon
Chapter 4: Store Financial Market Data on Your Computer Chevron down icon Chevron up icon
Chapter 5: Build Alpha Factors for Stock Portfolios Chevron down icon Chevron up icon
Chapter 6: Vector-Based Backtesting with VectorBT Chevron down icon Chevron up icon
Chapter 7: Event-Based Backtesting Factor Portfolios with Zipline Reloaded Chevron down icon Chevron up icon
Chapter 8: Evaluate Factor Risk and Performance with Alphalens Reloaded Chevron down icon Chevron up icon
Chapter 9: Assess Backtest Risk and Performance Metrics with Pyfolio Chevron down icon Chevron up icon
Chapter 10: Set Up the Interactive Brokers Python API Chevron down icon Chevron up icon
Chapter 11: Manage Orders, Positions, and Portfolios with the IB API Chevron down icon Chevron up icon
Chapter 12: Deploy Strategies to a Live Environment Chevron down icon Chevron up icon
Chapter 13: Advanced Recipes for Market Data and Strategy Management Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon
Other Books You May Enjoy Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.6
(15 Ratings)
5 star 86.7%
4 star 0%
3 star 6.7%
2 star 0%
1 star 6.7%
Filter icon Filter
Top Reviews

Filter reviews by




Lucas Aug 17, 2024
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Subscriber review Packt
kasidit asavakittikawin Sep 09, 2024
Full star icon Full star icon Full star icon Full star icon Full star icon 5
"Python for Algorithmic Trading Cookbook" stands out as a practical and accessible guide for those seeking to enhance their algorithmic trading knowledge. The author's hands-on experience and understanding of the needs of beginners shine through in this well-structured book.Practical Approach: The book is filled with actionable Python recipes for acquiring, visualizing, storing, and analyzing market data. It walks readers through the entire process of designing, backtesting, and deploying trading strategies, making the complex world of algo trading manageable.Updated Data Sources: The book provides free and updated data sources, a valuable resource for those looking to apply the concepts in a real-world setting.
Amazon Verified review Amazon
Didier Lopes Sep 15, 2024
Full star icon Full star icon Full star icon Full star icon Full star icon 5
If you are starting using Python to do algorithmic trading - you should get this book. I recommend the paperback version personally, particularly to have it by your desk in a way that you can access it easily.The book is packed with clear, hands-on examples that make complex topics feel easy - Jason is one of the best people I know at doing this. That's why he has hundreds of thousands of followers and has had over 1000 students attending his cohorts.I also love how practical the book is. All theory has real-world examples that myself, as the reader, can use to better understand the topic at hand.It goes from basic technical analysis to more advanced strategies like machine learning, so there's a lot of room to grow your skills.If you're like me and appreciate learning by doing, this book is perfect. The code examples are super clear, and you can quickly get a strategy up and running or modify it to fit your own ideas.PS: I also particularly love that the book features OpenBB!
Amazon Verified review Amazon
Roger A. Strimpel Aug 29, 2024
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Excellent book!!
Amazon Verified review Amazon
Amazon Customer Aug 24, 2024
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I thought this book was very insightful and excellent source for information. The charts were understandable!
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.