Share E-Book

Quantitative Trading Strategies Using Python Technical Analysis, Statistical Testing, and Machine Learning (Peng Liu)(Z-Library)

Author

Rating No ratings yet

Log in to rate

Python
Language English

Build and implement trading strategies using Python. This book will introduce you to the fundamental concepts of quantitative trading and shows how to use Python and popular libraries to build trading models and strategies from scratch. It covers practical trading strategies coupled with step-by-step implementations that touch upon a wide range of topics, including data analysis and visualization, algorithmic trading, backtesting, risk management, optimization, and machine learning, all coupled with practical examples in Python. Part one of Quantitative Trading Strategies with Python covers the fundamentals of trading strategies, including an introduction to quantitative trading, the electronic market, risk and return, and forward and futures contracts. Part two introduces common trading strategies, including trend-following, momentum trading, and evaluation process via backtesting. Part three covers more advanced topics, including statistical arbitrage using hypothesistesting, optimizing trading parameters using Bayesian optimization, and generating trading signals using a machine learning approach. Whether you're an experienced trader looking to automate your trading strategies or a beginner interested in learning quantitative trading, this book will be a valuable resource. Written in a clear and concise style that makes complex topics easy to understand, and chock full of examples and exercises to help reinforce the key concepts, you’ll come away from it with a firm understanding of core trading strategies and how to use Python to implement them. Who This Book Is For Aspiring quantitative traders and analysts, data scientists interested in finance, and researchers or students studying quantitative finance, financial engineering, or related fields.

Format PDF
Size 9.1 MB
7
Views
(First 20 pages)

Registered users can read the full content for free

Register as a Gaohf Library member to read the complete e-book online for free and enjoy a better reading experience.

Page 1
Quantitative Trading Strategies Using Python Technical Analysis, Statistical Testing, and Machine Learning — Peng Liu
Page 2
Quantitative Trading Strategies Using Python Technical Analysis, Statistical Testing, and Machine Learning Peng Liu
Page 3
Quantitative Trading Strategies Using Python: Technical Analysis, Statistical Testing, and Machine Learning ISBN-13 (pbk): 978-1-4842-9674-5 ISBN-13 (electronic): 978-1-4842-9675-2 https://doi.org/10.1007/978-1-4842-9675-2 Copyright © 2023 by Peng Liu This work is subject to copyright. All rights are reserved by the Publisher, whether the whole or part of the material is concerned, specifically the rights of translation, reprinting, reuse of illustrations, recitation, broadcasting, reproduction on microfilms or in any other physical way, and transmission or information storage and retrieval, electronic adaptation, computer software, or by similar or dissimilar methodology now known or hereafter developed. Trademarked names, logos, and images may appear in this book. Rather than use a trademark symbol with every occurrence of a trademarked name, logo, or image we use the names, logos, and images only in an editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the trademark. The use in this publication of trade names, trademarks, service marks, and similar terms, even if they are not identified as such, is not to be taken as an expression of opinion as to whether or not they are subject to proprietary rights. While the advice and information in this book are believed to be true and accurate at the date of publication, neither the authors nor the editors nor the publisher can accept any legal responsibility for any errors or omissions that may be made. The publisher makes no warranty, express or implied, with respect to the material contained herein. Managing Director, Apress Media LLC: Welmoed Spahr Acquisitions Editor: Celestin Suresh John Development Editor: James Markham Coordinating Editor: Mark Powers Cover designed by eStudioCalamar Cover image by Ahmad Ardity on Pixabay (www.pixabay.com) Distributed to the book trade worldwide by Springer Science+Business Media New York, 1 New York Plaza, Suite 4600, New York, NY 10004-1562, USA. Phone 1-800-SPRINGER, fax (201) 348-4505, e-mail orders-ny@ springer-sbm.com, or visit www.springeronline.com. Apress Media, LLC is a California LLC and the sole member (owner) is Springer Science + Business Media Finance Inc (SSBM Finance Inc). SSBM Finance Inc is a Delaware corporation. For information on translations, please e-mail booktranslations@springernature.com; for reprint, paperback, or audio rights, please e-mail bookpermissions@springernature.com. Apress titles may be purchased in bulk for academic, corporate, or promotional use. eBook versions and licenses are also available for most titles. For more information, reference our Print and eBook Bulk Sales web page at http://www.apress.com/bulk-sales. Any source code or other supplementary material referenced by the author in this book is available to readers on GitHub (github.com/apress). For more detailed information, please visit https://www.apress. com/gp/services/source-code. Paper in this product is recyclable Peng Liu Singapore, Singapore
Page 4
(This page has no text content)
Page 5
(This page has no text content)
Page 6
(This page has no text content)
Page 7
(This page has no text content)
Page 8
(This page has no text content)
Page 9
(This page has no text content)
Page 10
ix About the Author Peng Liu is an assistant professor of quantitative finance (practice) at Singapore Management University and an adjunct researcher at the National University of Singapore. He holds a Ph.D. in statistics from the National University of Singapore and has ten years of working experience as a data scientist across the banking, technology, and hospitality industries. Peng is the author of Bayesian Optimization (Apress, 2023).
Page 11
xi About the Technical Reviewer Sonal Raj is an engineer, mathematician, data scientist, and Python evangelist from India, who has carved a niche in the financial services domain. He is a Goldman Sachs and D. E. Shaw alumnus who currently serves as Vice President and Head of Data Management and Research for a leading high-frequency trading firm. Sonal holds dual masters in computer science and business administration and is a former research fellow of the Indian Institute of Science. He is a doctoral candidate in data science at the Swiss School of Business Management, Geneva. His areas of research range from image processing and real-time graph computations to electronic trading algorithms. Sonal is the author of the titles The Pythonic Way (BPB, 2021) and Neo4j High Performance (Packt, 2015). During his career, Sonal has created low latency trading algorithms, trading strategies, market signal models, and components of electronic trading systems. He is also a community speaker and a Python and data science mentor to young minds in the field. When not engrossed in reading fiction or playing symphonies, he spends far too much time watching rockets lift off. He is a loving son and husband and a custodian of his personal library.
Page 12
1 CHAPTER 1 Quantitative Trading: An Introduction Quantitative trading, also called algorithmic trading, refers to automated trading activities that buy or sell particular instruments based on specific algorithms. Here, an algorithm can be considered a model that transforms an input into an output. In this case, the input includes sufficient data to make a proper trading decision, and the output is the action of buying or selling an instrument. The quality of a trading decision thus relies on the sufficiency of the input data and the suitability and robustness of the model. Developing a successful quantitative trading strategy involves the collection and processing of vast amounts of input data, such as historical price data, financial news, and economic indicators. The data is passed as input to the model development process, where the goal is to accurately forecast market trends, identify trading opportunities, and manage potential risks, all of which are reflected in the resulting buy or sell signals. A robust trading algorithm is often identified via the process of backtesting, which involves simulating the algorithm’s performance using historical data. Simulating the performance of the algorithm under different scenarios allows us to assess the strategy’s potential effectiveness better, identify its limitations, and fine-tune the parameters to optimize its results. However, one also needs to be aware of the potential risks of overfitting and survivorship bias, which can lead to inflated metrics and potentially poor test set performance. In this chapter, we start by covering a few basic and important concepts related to quantitative trading. We then switch to hands-on examples of working with financial data using Python. © Peng Liu 2023 P. Liu, Quantitative Trading Strategies Using Python, https://doi.org/10.1007/978-1-4842-9675-2_1
Page 13
2 Overview of Quantitative Trading Quantitative trading refers to the use of mathematical models and algorithms to analyze large datasets (structured or unstructured), identify consistent patterns, and generate robust trading signals. The key components of quantitative trading include data collection and preprocessing, feature engineering, model development, backtesting, optimization, and execution. Quantitative strategies can vary greatly in complexity, ranging from simple moving average crossovers to advanced machine learning techniques, all of which are covered in later chapters of the book. A good trading strategy could be as simple as buying low and selling high (i.e., long a security) or selling high and buying low (i.e., short a security). The underlying trading model can consume different types of input data. For example, the input data could include structured features such as specific performance metrics of a particular stock or unstructured news contents pertinent to the company of the stock. When the input is financial news, the challenge is often concerned with converting unstructured textual information to structured features in a consistent and principled manner. The input data could also be raw financial ratios readily available from the balance sheet or derived features such as firm-specific technical indicators. We can categorize the input data into the following four general groups: • Market states: Security-specific price movements such as tick data that measures the minimum upward or downward movement in the price of a security, or market-specific factors such as bid-ask spread in limit-order books (LOB) in high-frequency trading. Besides the tick size, other resolution parameters of a LOB include the lot size, which specifies the smallest amount of a stock that can be traded. • Financial news: Macroeconomic news, analyst reports, earnings conference call transcripts, etc. • Fundamentals: Overall economic or sector-specific conditions and firm-specific metrics such as revenue, cash flow, earnings per share (EPS), etc. • Technicals: Derived technical indicators based on the raw price series, including moving averages, stochastic indicators, etc. Chapter 1 Quantitative trading: an introduCtion
Page 14
3 More generally, quantitative trading can be defined as the process of order execution based on trading signals generated using computer programs and algorithms. The purpose is either to seek profits and achieve an abnormal rate of return that beats the market (called alpha) or manage different types of risk. In a nutshell, quantitative trading refers to an algorithm (also called a function or a model) that digests any of these structured or unstructured data sources and outputs a trading decision. The automatic trading strategies could be in the form of experience- based rules based on technical analysis or data-driven machine learning models trained based on historical data. Upon receiving the output as a trading signal, we would either buy (also called long) an asset to open a position or sell (also called short) an asset to close a position, make a profit, or stop a loss. Trading signals could occur intraday in a high-frequency setting (also called day trading) or in a longer term (also called position trading). Figure 1-1 illustrates this process. Figure 1-1. Illustrating the overall quantitative trading process The model used to generate trading signals could be either rule-based or trained using data. The rule-based approach mainly relies on domain knowledge and requires explicitly writing out the logic flow from input to output, similar to following a cooking recipe. On the other hand, the data-driven approach involves training a model using machine learning techniques and using the model as a black box for prediction and inference. Let us review the overall model training process in a typical machine learning workflow. Chapter 1 Quantitative trading: an introduCtion
Page 15
4 Model Development Workflow A typical model development workflow starts with some training data. The training data consists of input-output pairs in supervised learning tasks where both input and output data are given. Each input entry could contain multiple features that describe the same observation from different perspectives. The corresponding output has the true target, acting as the correct answer to guide the training process. Model training aims to generate a mapping function, a model, that correctly maps a given input to the corresponding output. A trained model consists of two parts: parameters and architecture. Parameters are the integral components of a model, and the architecture specifies how these components interact with the input data to produce the final prediction output. This predicted value is then compared with the ground truth target to make an error metric jointly. Here, the error indicates the current cost on how close or far away it is between the prediction and the actual value. Following a particular optimization procedure, the training process adjusts the model parameters for a given architecture to reduce the training cost. After changing the weights, the new error is calculated again, forming a feedback loop. The whole model training process is depicted in Figure 1-2. Chapter 1 Quantitative trading: an introduCtion
Page 16
5 Figure 1-2. Example of a typical model training process. The workflow starts with the available training data and gradually tunes a model. The tuning process requires matching the model prediction to the target output, where the gap is measured by a particular cost function and used as feedback for the next round of tuning. Each tuning produces a new model, and we want to look for one that minimizes the cost Now let us look at a specific type of algorithmic trading at large institutions: institutional algorithmic trading. Institutional Algorithmic Trading Since the underlying decision model could be a black box, algorithmic trading is also called automated trading, black-box trading, or robo-trading. It is used to generate and execute orders in markets with electronic access. In the context of large institutions, hedge funds, and trading desks, the trading volume is often quite large. In this case, institutional algorithmic trading often seeks to break up large orders into smaller ones to reduce the execution risk, which refers to the case when a large order cannot be fulfilled in the market. Chapter 1 Quantitative trading: an introduCtion
Page 17
6 Besides preserving anonymity in transactions, large institutions also use algorithmic trading to minimize the price impact of a trade. This is because even if a large order is executable, it is difficult to guarantee that the market price will not be impacted due to the execution of the large order. Thus, the main objective of institutional algorithmic trading is to control the market risk and the execution cost rather than gaining profits. When executing a large order by an institutional investor, the demand for a large amount of liquidity will typically affect the cost of the trade negatively. This is called slippage, which refers to situations when a market participant receives a different execution price than initially intended. This could happen for many instruments, including stocks, bonds, currencies, and derivatives. To execute these block trades anonymously without generating a noticeable impact in the market, large institutions often involve dark pools to carry out these trades. Dark pools are private exchanges that execute orders from institutional investors away from the central stock exchanges, thus exhibiting little transparency in the transactional process. These large institutional orders, when split into small-sized orders, are also called iceberg orders. By partially exposing the tip of an iceberg, the majority of the orders could remain hidden and transition into visible orders afterward, thus minimizing the disruption to the trading market as opposed to a single large order. These smaller orders will then be executed electronically over minutes, hours, or days. To minimize the impact of these orders, institutional investors would trade more at the market opens and closes when the trading volume is relatively high and less during a slow period around lunchtime. Let us look at a simple example of generating a small subset of iceberg orders from the original orders using Python. In Listing 1-1, we create a list of ten random integers saved in total_order to indicate all the orders to be executed by an institutional investor. We can randomly sample two indexes and use them to access the corresponding elements in total_order and save in iceberg_order, representing the iceberg orders to be exposed to the market. Listing 1-1. Generating iceberg orders # generate multiple random integers total_order = [random.randint(0, 10) for p in range(0, 10)] >>> total_order [9, 6, 4, 3, 7, 6, 3, 0, 0, 6] Chapter 1 Quantitative trading: an introduCtion
Page 18
7 # randomly sample two indexes to identify iceberg orders iceberg_order_idx = random.sample(total_order, 2) >>> iceberg_order_idx [0, 4] # retrieve iceberg orders iceberg_order = np.array(total_order)[iceberg_order_idx] iceberg_order array([9, 7]) The institutional algorithmic strategies generate optimal trading signals by analyzing daily quotes and prices. For example, an institutional algorithmic strategy may suggest entering a long position if the current stock price moves from below to above the volume- weighted average price (VWAP) over a day, a technical indicator often used by short-term traders. The institutional algorithmic strategies may also exploit arbitrage opportunities or price spreads between correlated securities. Here, arbitrage means making positive sure profits with zero investments. Arbitrage opportunities, if exist, would normally disappear very fast as many hedge funds and investors are constantly looking for such arbitrage opportunities. The next section briefly introduces the role of a quant trader. Being a Quant Trader A quant trader is a specialized trader that uses mathematical models and quantitative analysis to evaluate different financial products and identify trading opportunities to buy or sell the best securities out of hundreds of thousands of candidates. Quant traders make use of data-driven methods to make model-based trading decisions, seeking to exploit temporary inefficiencies and underlying patterns in the market that may not be easily discernible through traditional qualitative analysis. The first attribute of an aspiring quant trader is familiarity with numbers and mathematical models. As the majority of the time is spent on analyzing the data, proposing, backtesting, and implementing trading strategies to either buy, sell, or hold specific security, a quant trader needs to be comfortable with both mathematical models and programming, which often requires an advanced degree in financial modeling or related field. When a positive signal pops up, the quant trader needs to act swiftly using self-developed programs to capitalize on the current trading opportunities. Chapter 1 Quantitative trading: an introduCtion
Page 19
8 The second attribute lies in soft skills such as handling high pressure with a good temperament. This requires good emotional intelligence to neither assume too much risk nor be overly risk averse. Knowing when to exit a position and stop loss is a critical skill that requires discipline in daily trading activities. The following section covers the major asset classes and various tradable instruments. Major Asset Classes and Derivatives Multiple tradable financial instruments are used to raise capital in public and private markets. Institutional and retail investors can enter into long or short positions involving different single or combinations of assets, profit-seeking, or risk management (i.e., hedging). Let us first get a glimpse of the many tradable assets. In the following list, we provide a short definition of common assets used in the market: • Stocks: Also called equity, a form of security representing proportionate ownership of the issuing company. A unit of stock is called a share, and the number of shares determines the proportionate ownership and, thus, profit sharing of the stock owner. The stock owner profits when the stock price increases or by receiving dividends. • Bonds: Fixed-income debt instruments representing a fixed- duration loan from the investor/lender to the borrower (company or government). A bond provides the owner with fixed-rate coupon or variable interest payments, and the principal is paid to the owner at the end date. It is a fixed-income asset due to the regular and stable interest paid to the owner. • Annuities: Insurance contracts from financial institutions that provide a fixed-income stream to the contract owner in the future. Investors mainly purchase annuities for retirement as they can receive a guaranteed stream of payments in the future for a specified period or the remainder of life. Chapter 1 Quantitative trading: an introduCtion
Page 20
9 • Cash and equivalents: Highly liquid short-term (less than 90 days) investment securities with low risk and low return (usually less than the inflation rate). The equivalents include bank accounts, near-term instruments such as US Treasury bills, and money market funds. These current assets can be easily accessed anytime and reflect the firm’s ability to pay the short-term debt. • Commodities: Basic goods used in commerce as raw inputs to produce other goods or services. Common commodities, such as gold, oil, and natural gas, can be traded in the spot (cash) market or via derivatives such as futures and options. • Futures: Financial derivatives in the form of legal agreements that oblige the futures contract buyer to buy or sell the underlying asset at a prespecified price, amount, and time in the future. Futures are often used to hedge against price movements of the underlying asset and thus avoid losses due to unfavorable price changes in the future. The price of a futures contract is settled daily, that is, marked to market (MTM). • Forward: Similar to the futures contract. The difference is that a forward contract is a private and customizable agreement traded over the counter (OTC), which is a decentralized marketplace where participants trade instruments directly without engaging a central exchange or a broker. The price of a forward contract is settled at the end of the agreement. • Options: Financial derivatives that offer the buyer of the options contract the opportunity to buy (if it is a call option) or sell (if it is a put option) the underlying asset on or before a specific expiration (maturity) date and (strike) price. Options give the buyers the right, not the obligation, to long or short an underlying asset. They can be used for both hedging and speculation. Note that we focus on the European option by default. • Currencies: International currencies and currency derivatives traded via the (largest and most liquid) global electronic marketplace, also called the foreign exchange market or forex. Forex allows investors to Chapter 1 Quantitative trading: an introduCtion
The above is a preview of the first 20 pages. Register to read the complete e-book.

Recommended for You

Loading recommended books...
Failed to load, please try again later

Tip the Site

Scan the WeChat Pay or Alipay code to tip. No login required.

WeChat Pay
Alipay
← Back to List