
Hands-On AI Trading with Python, QuantConnect, and AWS
Description
Alles über E-Books | Antworten auf Fragen rund um E-Books, Kopierschutz und Dateiformate finden Sie in unserem Info- & Hilfebereich.
Master the art of AI-driven algorithmic trading strategies through hands-on examples, in-depth insights, and step-by-step guidance
Hands-On AI Trading with Python, QuantConnect, and AWS explores real-world applications of AI technologies in algorithmic trading. It provides practical examples with complete code, allowing readers to understand and expand their AI toolbelt.
Unlike other books, this one focuses on designing actual trading strategies rather than setting up backtesting infrastructure. It utilizes QuantConnect, providing access to key market data from Algoseek and others. Examples are available on the book's GitHub repository, written in Python, and include performance tearsheets or research Jupyter notebooks.
The book starts with an overview of financial trading and QuantConnect's platform, organized by AI technology used:
- Examples include constructing portfolios with regression models, predicting dividend yields, and safeguarding against market volatility using machine learning packages like SKLearn and MLFinLab.
- Use principal component analysis to reduce model features, identify pairs for trading, and run statistical arbitrage with packages like LightGBM.
- Predict market volatility regimes and allocate funds accordingly.
- Predict daily returns of tech stocks using classifiers.
- Forecast Forex pairs' future prices using Support Vector Machines and wavelets.
- Predict trading day momentum or reversion risk using TensorFlow and temporal CNNs.
- Apply large language models (LLMs) for stock research analysis, including prompt engineering and building RAG applications.
- Perform sentiment analysis on real-time news feeds and train time-series forecasting models for portfolio optimization.
- Better Hedging by Reinforcement Learning and AI: Implement reinforcement learning models for hedging options and derivatives with PyTorch.
- AI for Risk Management and Optimization: Use corrective AI and conditional portfolio optimization techniques for risk management and capital allocation.
Written by domain experts, including Jiri Pik, Ernest Chan, Philip Sun, Vivek Singh, and Jared Broad, this book is essential for hedge fund professionals, traders, asset managers, and finance students. Integrate AI into your next algorithmic trading strategy with Hands-On AI Trading with Python, QuantConnect, and AWS.
More details
Other editions
Additional editions

Persons
JIRI PIK: Founder and CEO of RocketEdge.com. A software architect and cloud computing expert, Jiri Pik specializes in designing high-performance trading systems. He has decades of experience in financial technologies and has worked with some of the world's leading financial institutions, including Goldman Sachs and JPMorgan Chase.
ERNEST P. CHAN: A pioneer in applying machine learning to quantitative trading, Ernest P. Chan founded Predictnow.ai and QTS Capital Management. He is author of books such as Quantitative Trading and Machine Trading.
JARED BROAD: Founder and CEO of QuantConnect(TM), Jared Broad has empowered over 300,000 algorithmic traders worldwide with a platform that simplifies strategy design, backtesting, and live deployment.
PHILIP SUN: CEO and Co-founder of Adaptive Investment Solutions, LLC, and a seasoned quantitative fund manager, Philip Sun and his team focus on building state-of-the-art AI-driven risk management platform for wealth advisors and institutional investors.
VIVEK SINGH: A product leader at Amazon Web Services (AWS), Vivek Singh spearheads the development of large language models (LLMs) and Generative AI applications, bringing cutting-edge AI technologies to the trading domain.
Content
Biographies xiii
Preface: QuantConnect xv
Introduction xxiii
Part I Foundations of Capital Markets and Quantitative Trading 1
Chapter 1 Foundations of Capital Markets 3
Market Mechanics 3
Market Participants 4
Trading Is the "Play" 4
The Stage and Basic Rules of Trading-The Limit Order Book 4
Actors-Liquidity Trader, Market Maker, and Informed Trader 5
Liquidity Trader 5
Market Maker 5
Informed Trader 6
AI Actors Wanted! 7
Data and Data Feeds 7
Custom and Alternative Data 9
Brokerages and Transaction Costs 10
Transaction Costs 11
Security Identifiers 13
Assets and Derivatives 15
US Equities 15
US Equity Options 19
Index Options 21
US Futures 21
Cryptocurrency 23
Chapter 2 Foundations of Quantitative Trading 25
Research Process 25
Research 25
Backtesting 26
Parameter Optimization 26
Paper and Live Trading 26
Testing and Debugging Tools 26
Debuggers 27
Logging 27
Charting 27
Object Store 28
Coding Process 28
Time and Look-ahead Bias 29
Look-ahead Bias 29
Market Hours and Scheduling 30
Strategy Styles 30
Trading Signals 31
Allocating Capital 31
Regimes and Portfolios of Strategies 32
Parameter Sensitivity Testing and Optimization 33
1. Remove 33
2. Replace 34
3. Reduce 34
Parameter Sensitivity Testing 34
Margin Modeling 35
Equities 35
Equity Options 36
Futures 37
Diversification and Asset Selection 37
Fundamental Asset Selection 38
ETF Constituents Asset Selection 39
Dollar-Volume Asset Selection 40
Universe Settings 40
Indicators and Other Data Transformations 41
Automatic Indicators 41
Manual Indicators 41
Indicator Warm Up 42
Storing Objects 42
Indicator Events 42
Sourcing Ideas 42
Hypothesis-driven Testing 43
Data Driven Investing 44
Quantpedia 44
QuantConnect Research and Strategy Explorer 45
Part II Foundations of Ai and Ml in Algorithmic Trading 47
Step-by-step Guide for AI-based Algorithmic Trading 48
Chapter 3 Step 1: Problem Definition 49
Chapter 4 Step 2: Dataset Preparation 53
Data Collection 53
Exploratory Data Analysis 53
Data Preprocessing 54
Handling Missing Data 55
Handling Outliers 58
Feature Engineering 61
Normalization and Standardization of Features 62
Transforming Time Series Features to Stationary 64
Identification of Cointegrated Time Series with Engle-Granger Test 70
Feature Selection 76
Correlation Analysis 76
Feature Importance Analysis 77
Auto-identification of Features 78
Dimensionality Reduction/Principal Component Analysis 80
Splitting of Dataset into Training, Testing, and Possibly Validation Sets 83
How to Split Your Data 83
Chapter 5 Step 3: Model Choice, Training, and Application 87
Regression 88
Linear Regression 89
Polynomial Regression 91
LASSO Regression 93
Ridge Regression 96
Markov Switching Dynamic Regression 99
Decision Tree Regression 103
Support Vector Machines Regression with Wavelet Forecasting 105
Classification 110
Multiclass Random Forest Model 110
Logistic Regression 114
Hidden Markov Models 117
Gaussian Naive Bayes 119
Convolutional Neural Networks 122
Ranking 127
LGBRanker Ranking 127
Clustering 130
OPTICS Clustering 130
Language Models 132
OpenAI Language Model 132
Amazon Chronos Model 135
FinBERT Model 137
Part III Advanced Applications of Ai in Trading and Risk Management 141
Getting Started with Source Code 141
Chapter 6 Applied Machine Learning 143
Example 1-ML Trend Scanning with MLFinlab 143
Example 2-Factor Preprocessing Techniques for Regime Detection 148
Example 3-Reversion vs. Trending: Strategy Selection by Classification 154
Example 4-Alpha by Hidden Markov Models 158
Example 5-FX SVM Wavelet Forecasting 170
Example 6-Dividend Harvesting Selection of High-Yield Assets 176
Example 7-Effect of Positive-Negative Splits 181
Example 8-Stop Loss Based on Historical Volatility and Drawdown Recovery 185
Example 9-ML Trading Pairs Selection 197
Example 10-Stock Selection through Clustering Fundamental Data 207
Example 11-Inverse Volatility Rank and Allocate to Future Contracts 214
Example 12-Trading Costs Optimization 221
Example 13-PCA Statistical Arbitrage Mean Reversion 228
Example 14-Temporal CNN Prediction 233
Example 15-Gaussian Classifier for Direction Prediction 242
Example 16-LLM Summarization of Tiingo News Articles 250
Example 17-Head Shoulders Pattern Matching with CNN 256
Example 18-Amazon Chronos Model 265
Example 19-FinBERT Model 272
Chapter 7 Better Hedging with Reinforcement Learning 281
Introduction 281
A New AI Trading Assistant 281
Continuous Hedging Is Not Required 282
Machine Learning Comes to the Rescue 283
A Simplified but Effective Reinforcement Learning Approach 284
Overview of the Reinforcement Learning 285
Identification 285
Simulation 286
Ref inement Training on Actual Market Data 287
Testing and Implementation 287
Implementation on QuantConnect 288
Primary Research Notebook 289
The Policy Network 290
Model Functions 292
Fine-tuning with Market Data 296
Results 300
Conclusion 303
Chapter 8 AI for Risk Management and Optimization 305
What Is Corrective AI and Conditional Parameter Optimization? 305
Feature Engineering 308
Applying Corrective AI to Daily Seasonal Forex Trading 312
What Is Conditional Parameter Optimization? 318
Applying Conditional Parameter Optimization to an ETF Strategy 319
Unconditional vs. Conditional Parameter Optimizations 320
Performance Comparisons 322
Conditional Portfolio Optimization 322
Regime Changes Obliterate Traditional Portfolio Optimization Methods 322
Learning to Optimize 324
Ranking Is Easier Than Predicting 325
The Fama-French Lineage 327
Comparison with Conventional Optimization Methods 327
Model Tactical Asset Allocation Portfolio 331
CPO Software-as-a-Service 333
Conclusion 340
Definitions of Spread_EMA & Spread_VAR 340
Chapter 9 Application of Large Language Models and Generative AI in Trading 341
Role of Generative AI in Creating Alpha 341
Selecting an LLM for Building a Generative AI Application 342
Prompt Engineering 344
Prompt Engineering in Practice 345
Addressing Model "Hallucination" 346
Question Answering Using a Retrieval Augmented Application in SageMaker Canvas 347
RAG Application Costs and Optimization Techniques 350
Testing Our Infrastructure 351
Summarization 356
Useful AI Platforms and Services 359
ChatGPT 359
Gemini 359
Bedrock 359
SageMaker 359
Q Business 360
References 361
Subject Index 363
Code Index 379
Chapter 1
Foundations of Capital Markets
This chapter introduces the core concepts of modern financial markets and how they're represented in QuantConnect. We'll cover the modern US markets, data feeds, and the asset classes used in later chapters. Readers who are familiar with QuantConnect may skip this chapter.
Market Mechanics
The United States has 11 major stock exchanges. The two largest are the New York Stock Exchange (NYSE) and the National Association of Securities Dealers Automated Quotations System (NASDAQ). Trades on these exchanges are compiled by the Securities Information Processor (SIP) into a single data feed. This feed helps the Securities and Exchange Commission (SEC) determine the national best bid or offer (NBBO), which shows the best prices posted on public markets in the United States. When a new quote for more than 100 shares offers a better price, it is flagged as the NBBO. Quotes or trades involving fewer than 100 shares, known as odd lots, are excluded from this pricing. Figure 1.1 illustrates this flow.
Figure 1.1 Flow of retail and institutional traffic across public and private markets, and the origin of national best pricing.
Brokerages often send orders to market makers to be executed "off the market." Market makers executing these orders are required to provide fills within the NBBO price range. Furthermore, these off-market trades are reported to the Trade Reporting Facility (TRF) and eventually are included in the SIP data feed. Some brokers offer Direct Market Access (DMA), which allows your orders to be routed directly to a specific exchange. However, using DMA might not always get you the best national price for the asset, so it's important to be careful when using this option.
Market Participants
Trading Is the "Play"
If markets are theaters, then trading is the "play." Like a Shakespearean play, trading, especially algorithmic trading, is a highly coordinated and scripted activity. Comparing trading to the Bard's plays will probably make Shakespeare turn in his grave. But he will forgive this literary enthusiast for the forced metaphor.
The Stage and Basic Rules of Trading-The Limit Order Book
To stretch this analogy further, the stage of trading is the "limit order book," which is a ledger of some sort that lists limit order prices of a security in columns. On the left side is the column of bid prices, that is, prices traders are willing to buy a security at, and the amounts or "sizes" of the orders (for stocks, the sizes are typically in multiples of round lots of 100 shares; and for futures and options, in numbers of contracts). On the opposite side of this ledger is the column of ask prices, that is, prices traders are willing to sell a security at, and sizes. The prices are usually sorted from high to low from top to bottom, with the best bid and ask meeting in the middle. Bid prices cannot be higher than ask prices, that is, bid and ask prices do not cross, otherwise the buyers and sellers will be able to fulfill each other's order in a way that benefits one or both sides. Any buy orders that enter the market higher than current best ask price is effectively a market order and will be matched up to the size of the best ask price, and then the next best ask price and so on, until entire buy orders are filled in a process called "walk-the-book," or when remaining ask prices are above the best bid price. Because of this, a trader who posts limit orders will usually post bid prices below the best ask price and ask prices above the best bid price.
Because there is a spread between the best bid and ask prices, limit orders do not get filled right away, and indeed sometimes, not filled at all. To ensure immediacy of trades, in a sufficiently liquid market, a trader can post a "market order," which gets matched with the best bid for a market sell order and matched with best ask for a market buy order. If there is not enough size at the current bid and asks, the market sell and buy orders will walk the book as described previously: the market buy order will pay progressively higher prices; and conversely, the market sell order will accept progressively lower prices. If the size of the market order is large compared to sizes of available limit orders, the order will walk deeper (i.e., higher for buyer or lower for seller) in the order book, causing an immediate rise or decline in the trade price of the securities. This is a form of adverse price impact of trading.
Actors-Liquidity Trader, Market Maker, and Informed Trader
Now that the stage is set, let's introduce the actors, or more appropriately, the characters or roles in the play. Just like actors, traders can play multiple roles, sometimes in the same play or even at the same time.
Liquidity Trader
A "liquidity trader," also called "fundamental trader" or derogatively "noise trader," is a trader whose primary goal is to get in or out of a position for purposes other than profiting from advantaged information (not always insider information). For example, a mutual fund manager decides to rebalance her stock portfolio to match a benchmark index. The trader acting on the instruction of the fund manager is a liquidity trader. The same fund manager may be a macro forecaster, sector specialist, or stock picker basing her trades on publicly available information and deciding to buy or sell some stocks to profit from her mosaic view. Still, such a fund manager does not possess any advantaged information. The trader who executes her trades may be respectfully called a "fundamental trader," even though fundamentally she is no different from a liquidity trader. Finally, you also have undisciplined traders who are trading for the sake of trading-and we can safely call them "noise traders". Whether the traders are fundamental or noise, their objective is to complete buy or sell orders with no advantaged information.
Market Maker
If a liquidity trader wants liquidity, who is there to pour him a drink? Well, it could be the liquidity trader on the other side of the trade. It is likely that most liquid stock transactions occur by matching simultaneous market orders on opposite sides of the trade. And much of those orders are matched by your broker dealer before they reach the stock exchange. This is done by internally "crossing" or "netting" the orders, usually done at the mid-price, that is, halfway between best bid and ask in the limit order book.
If there is not enough market order from the opposite side, a market order will "hit the bid" or "lift the offer." It will walk the book if there is not enough size at the best bid or ask, as we discussed previously. Here, it is the other limit orders that will fulfill the liquidity-seeking market order. Exchanges will pay a rebate on a filled limit order to reward the trader for liquidity.
Strategies that facilitate trading and improve transaction prices, or immediacy, are strategies typically deployed by a "market maker." Traditionally, when trading was conducted on the floor of a stock exchange (e.g., NYSE), dedicated market makers were physically located in booths and their jobs were to match trades for their assigned list of stocks. They stood ready when the listed buy and sell (limit) orders were not sufficient to clear the market of open orders (e.g., when the market was at a standstill because the best bid and ask prices were too far apart). In situations like that, it was the market maker's job and her opportunity to post orders that get in between the best bid and ask prices to encourage liquidity traders to transact at her better prices. In return, the market maker would profit from the bid and ask spread, that is, she bought at her bid price and sold higher at the current or improved ask price. The previous narrative is in the past tense because the majority of market-making activities have shifted to electronic trading platforms. Some floor trading still exists for less liquid stocks and other asset classes. For example, the Chicago Board of Options still operates a pit to trade equity and equity index options, while the Chicago Mercantile Exchange ceased pit trading in March 2020 due to COVID-19 and decided the closure would be permanent.
In the modern era of electronic trading, market makers are now almost exclusively algorithmic and high-frequency trading programs. There are still traders whose primary or exclusive job is to make markets in certain stocks, but anyone can make markets intentionally or unintentionally by deploying strategies that improve outcomes-better prices and immediacy-for liquidity traders.
Informed Trader
Wait, a market maker helps only liquidity traders? What about other types of traders? Doesn't the market maker help everyone? Yes, market-making activity helps everyone, except other market makers who are competing against each other. That being said, market makers are more wary of "informed traders" than other market makers. To skirt the controversy about insider trading, we shall broadly define informed traders as ones who possess advantaged or privileged information that is only known to a small number of agents and is not released to the public. As we discussed previously, a trader or fund manager might have her unique opinion about the future outcome of financial markets and of individual securities. And she might have superior...
System requirements
File format: ePUB
Copy protection: Adobe-DRM (Digital Rights Management)
System requirements:
- Computer (Windows; MacOS X; Linux): Install the free reader Adobe Digital Editions prior to download (see eBook Help).
- Tablet/smartphone (Android; iOS): Install the free app Adobe Digital Editions or the app PocketBook before downloading (see eBook Help).
- E-reader: Bookeen, Kobo, Pocketbook, Sony, Tolino and many more (not Kindle).
The file format ePub works well for novels and non-fiction books – i.e., „flowing” text without complex layout. On an e-reader or smartphone, line and page breaks automatically adjust to fit the small displays.
This eBook uses Adobe-DRM, a „hard” copy protection. If the necessary requirements are not met, unfortunately you will not be able to open the eBook. You will therefore need to prepare your reading hardware before downloading.
Please note: We strongly recommend that you authorise using your personal Adobe ID after installation of any reading software.
For more information, see our ebook Help page.