100% found this document useful (1 vote)
66 views

Quantitative Trading Strategies Using Python Technical Analysis Statistical Testing And Machine Learning Pengliu download

The document discusses 'Quantitative Trading Strategies Using Python' by Peng Liu, focusing on technical analysis, statistical testing, and machine learning for trading strategies. It includes various chapters covering topics such as market structures, risk and return analysis, and specific trading strategies like trend-following and momentum trading. Additionally, it provides links to related ebooks and resources for further exploration in quantitative trading.

Uploaded by

thielopray5v
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
66 views

Quantitative Trading Strategies Using Python Technical Analysis Statistical Testing And Machine Learning Pengliu download

The document discusses 'Quantitative Trading Strategies Using Python' by Peng Liu, focusing on technical analysis, statistical testing, and machine learning for trading strategies. It includes various chapters covering topics such as market structures, risk and return analysis, and specific trading strategies like trend-following and momentum trading. Additionally, it provides links to related ebooks and resources for further exploration in quantitative trading.

Uploaded by

thielopray5v
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 82

Quantitative Trading Strategies Using Python

Technical Analysis Statistical Testing And


Machine Learning Pengliu download

https://ebookbell.com/product/quantitative-trading-strategies-
using-python-technical-analysis-statistical-testing-and-machine-
learning-pengliu-52168706

Explore and download more ebooks at ebookbell.com


Here are some recommended products that we believe you will be
interested in. You can click the link to download.

Quantitative Trading Strategies Harnessing The Power Of Quantitative


Techniques To Create A Winning Trading Program 1st Edition Lars
Kestner

https://ebookbell.com/product/quantitative-trading-strategies-
harnessing-the-power-of-quantitative-techniques-to-create-a-winning-
trading-program-1st-edition-lars-kestner-1367392

Optimal Trading Strategies Quantitative Approaches For Managing Market


Impact And Trading Risk 1st Robert Kissell

https://ebookbell.com/product/optimal-trading-strategies-quantitative-
approaches-for-managing-market-impact-and-trading-risk-1st-robert-
kissell-891378

Finding Alphas A Quantitative Approach To Building Trading Strategies


1st Edition Igor Tulchinsky

https://ebookbell.com/product/finding-alphas-a-quantitative-approach-
to-building-trading-strategies-1st-edition-igor-tulchinsky-5296488

Finding Alphas A Quantitative Approach To Building Trading Strategies


2nd Igor Tulchinsky Et Al

https://ebookbell.com/product/finding-alphas-a-quantitative-approach-
to-building-trading-strategies-2nd-igor-tulchinsky-et-al-10568410
Algorithmic Trading And Quantitative Strategies 1st Edition Raja Velu

https://ebookbell.com/product/algorithmic-trading-and-quantitative-
strategies-1st-edition-raja-velu-16313960

Trader Construction Kit Fundamental Technical Analysis Risk Management


Directional Trading Spreads Options Quantitative Strategies Execution
Position Management Data Science Programming 2nd Edition Joel Rubano

https://ebookbell.com/product/trader-construction-kit-fundamental-
technical-analysis-risk-management-directional-trading-spreads-
options-quantitative-strategies-execution-position-management-data-
science-programming-2nd-edition-joel-rubano-46138018

Trader Construction Kit Fundamental Technical Analysis Risk Management


Directional Trading Spreads Options Quantitative Strategies Execution
Position Management Data Science Programming Updated Second Edition
Joel Rubano 2nd Edition Joel Rubano
https://ebookbell.com/product/trader-construction-kit-fundamental-
technical-analysis-risk-management-directional-trading-spreads-
options-quantitative-strategies-execution-position-management-data-
science-programming-updated-second-edition-joel-rubano-2nd-edition-
joel-rubano-46223744

Quantative Analysis Derivatives Modeling And Trading Strategies Yi


Tang

https://ebookbell.com/product/quantative-analysis-derivatives-
modeling-and-trading-strategies-yi-tang-1232334

Quantitative Trading How To Build Your Own Algorithmic Trading


Business 1st Edition Chan

https://ebookbell.com/product/quantitative-trading-how-to-build-your-
own-algorithmic-trading-business-1st-edition-chan-55485234
Quantitative
Trading Strategies
Using Python
Technical Analysis, Statistical Testing,
and Machine Learning

Peng Liu
Quantitative Trading
Strategies Using Python
Technical Analysis, Statistical
Testing, and Machine Learning

Peng Liu
Quantitative Trading Strategies Using Python: Technical Analysis, Statistical Testing,
and Machine Learning
Peng Liu
Singapore, Singapore

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
Table of Contents
About the Author����������������������������������������������������������������������������������������������������� ix

About the Technical Reviewer��������������������������������������������������������������������������������� xi

Chapter 1: Quantitative Trading: An Introduction����������������������������������������������������� 1


Overview of Quantitative Trading�������������������������������������������������������������������������������������������������� 2
Model Development Workflow������������������������������������������������������������������������������������������������� 4
Institutional Algorithmic Trading���������������������������������������������������������������������������������������������� 5
Being a Quant Trader��������������������������������������������������������������������������������������������������������������� 7
Major Asset Classes and Derivatives��������������������������������������������������������������������������������������� 8
Grouping Tradable Assets������������������������������������������������������������������������������������������������������ 10
Common Trading Avenues and Steps������������������������������������������������������������������������������������ 14
Market Structures������������������������������������������������������������������������������������������������������������������ 15
Major Types of Buy-Side Stock Investors������������������������������������������������������������������������������ 16
Market Making���������������������������������������������������������������������������������������������������������������������� 17
Scalping��������������������������������������������������������������������������������������������������������������������������������� 18
Portfolio Rebalancing������������������������������������������������������������������������������������������������������������ 18
Getting Started with Financial Data Analysis������������������������������������������������������������������������������ 19
Summarizing Stock Prices���������������������������������������������������������������������������������������������������� 19
Downloading Stock Price Data���������������������������������������������������������������������������������������������� 21
Visualizing Stock Price Data�������������������������������������������������������������������������������������������������� 29
Summary������������������������������������������������������������������������������������������������������������������������������������ 32
Exercises������������������������������������������������������������������������������������������������������������������������������������� 33

Chapter 2: Electronic Market���������������������������������������������������������������������������������� 35


Introducing Electronic Market����������������������������������������������������������������������������������������������������� 35
Electronic Order��������������������������������������������������������������������������������������������������������������������� 36
Proprietary and Agency Trading��������������������������������������������������������������������������������������������� 38

iii
Table of Contents

Order Matching Systems������������������������������������������������������������������������������������������������������� 39


Market Order������������������������������������������������������������������������������������������������������������������������� 42
Limit Order����������������������������������������������������������������������������������������������������������������������������� 43
Limit Order Book�������������������������������������������������������������������������������������������������������������������� 44
Display vs. Non-display Orders��������������������������������������������������������������������������������������������� 47
Stop Order����������������������������������������������������������������������������������������������������������������������������� 47
Stop-Limit Order�������������������������������������������������������������������������������������������������������������������� 49
Pegged Order������������������������������������������������������������������������������������������������������������������������� 50
Trailing Stop Order����������������������������������������������������������������������������������������������������������������� 52
Market If Touched Order�������������������������������������������������������������������������������������������������������� 53
Summarizing Major Types of Orders�������������������������������������������������������������������������������������� 54
More Order Types: Limit and Cancelation������������������������������������������������������������������������������ 55
Price Impact�������������������������������������������������������������������������������������������������������������������������� 55
Order Flow����������������������������������������������������������������������������������������������������������������������������� 56
Working with LOB Data��������������������������������������������������������������������������������������������������������������� 57
Understanding Label Distribution������������������������������������������������������������������������������������������ 59
Understanding Price-Volume Data���������������������������������������������������������������������������������������� 61
Visualizing Price Movement�������������������������������������������������������������������������������������������������� 70
Summary������������������������������������������������������������������������������������������������������������������������������������ 74
Exercises������������������������������������������������������������������������������������������������������������������������������������� 75

Chapter 3: Forward and Futures Contracts������������������������������������������������������������ 77


Introducing Forward and Futures Contracts������������������������������������������������������������������������������� 78
Parameters of a Futures Contract����������������������������������������������������������������������������������������� 80
Hedging and Speculation������������������������������������������������������������������������������������������������������ 81
Obligations at Maturity���������������������������������������������������������������������������������������������������������� 82
Leverage in a Futures Contract��������������������������������������������������������������������������������������������� 83
Clearing House���������������������������������������������������������������������������������������������������������������������� 84
Mark-to-Market��������������������������������������������������������������������������������������������������������������������� 85
Pricing Forward Contract������������������������������������������������������������������������������������������������������� 88
Pricing Futures Contract�������������������������������������������������������������������������������������������������������� 91
Contango and Backwardation����������������������������������������������������������������������������������������������� 94

iv
Table of Contents

Working with Futures Data��������������������������������������������������������������������������������������������������������� 96


Adding Technical Indicators��������������������������������������������������������������������������������������������������� 99
Summary���������������������������������������������������������������������������������������������������������������������������������� 104
Exercises����������������������������������������������������������������������������������������������������������������������������������� 105

Chapter 4: Understanding Risk and Return���������������������������������������������������������� 107


Risk and Return Trade-Off��������������������������������������������������������������������������������������������������������� 108
Analyzing Returns���������������������������������������������������������������������������������������������������������������� 109
Working with Dummy Returns��������������������������������������������������������������������������������������������� 110
The 1+R Format������������������������������������������������������������������������������������������������������������������ 114
The Terminal Return������������������������������������������������������������������������������������������������������������ 115
Stock Return with Dividends����������������������������������������������������������������������������������������������� 117
Multiperiod Return��������������������������������������������������������������������������������������������������������������� 117
Annualizing Returns������������������������������������������������������������������������������������������������������������ 119
Calculating Single-Period Returns from Price Data������������������������������������������������������������� 120
Calculating Two-Period Terminal Return����������������������������������������������������������������������������� 123
Calculating Annualized Returns������������������������������������������������������������������������������������������� 124
Analyzing Risk��������������������������������������������������������������������������������������������������������������������������� 125
Introducing Variance and Standard Deviation��������������������������������������������������������������������� 126
Annualizing Volatility����������������������������������������������������������������������������������������������������������� 127
Combining Risk and Return via the Sharpe Ratio���������������������������������������������������������������� 129
Working with Stock Price Data�������������������������������������������������������������������������������������������� 132
Calculating the Mean, Variance, and Standard Deviation���������������������������������������������������� 134
Calculating the Annualized Volatility������������������������������������������������������������������������������������ 137
Calculating the Annualized Returns������������������������������������������������������������������������������������� 137
Calculating the Sharpe Ratio����������������������������������������������������������������������������������������������� 139
Summary���������������������������������������������������������������������������������������������������������������������������������� 139
Exercises����������������������������������������������������������������������������������������������������������������������������������� 140

v
Table of Contents

Chapter 5: Trend-Following Strategy�������������������������������������������������������������������� 141


Working with Log Returns��������������������������������������������������������������������������������������������������������� 142
Analyzing Stock Prices Using Log Returns�������������������������������������������������������������������������� 150
Introducing Trend Trading��������������������������������������������������������������������������������������������������������� 153
Understanding Technical Indicators������������������������������������������������������������������������������������ 154
Introducing Moving Averages���������������������������������������������������������������������������������������������� 155
Delving into Simple Moving Averages��������������������������������������������������������������������������������� 156
Delving into Exponential Moving Averages�������������������������������������������������������������������������� 163
Implementing the Trend-Following Strategy����������������������������������������������������������������������� 166
Summary���������������������������������������������������������������������������������������������������������������������������������� 173
Exercises����������������������������������������������������������������������������������������������������������������������������������� 174

Chapter 6: Momentum Trading Strategy��������������������������������������������������������������� 175


Introducing Momentum Trading������������������������������������������������������������������������������������������������ 176
Diving Deeper into Momentum Trading������������������������������������������������������������������������������� 176
Contrasting with the Trend-Following Strategy������������������������������������������������������������������� 177
Observing the Role of Lookback Windows�������������������������������������������������������������������������� 178
More on Trend Following����������������������������������������������������������������������������������������������������� 180
Implementing the Momentum Trading Strategy������������������������������������������������������������������������ 182
Obtaining DJI Stock Symbols���������������������������������������������������������������������������������������������� 182
Downloading Stock Prices��������������������������������������������������������������������������������������������������� 185
Calculating Monthly Returns����������������������������������������������������������������������������������������������� 185
Calculating the Six-Month Terminal Return������������������������������������������������������������������������� 187
Generating Trading Signals�������������������������������������������������������������������������������������������������� 188
Evaluating Out-of-Sample Performance������������������������������������������������������������������������������ 192
Comparing with the Buy-and-Hold Strategy������������������������������������������������������������������������ 194
Summary���������������������������������������������������������������������������������������������������������������������������������� 195
Exercises����������������������������������������������������������������������������������������������������������������������������������� 196

vi
Table of Contents

Chapter 7: Backtesting a Trading Strategy����������������������������������������������������������� 197


Introducing Backtesting������������������������������������������������������������������������������������������������������������ 197
Caveats of Backtesting�������������������������������������������������������������������������������������������������������� 199
Understanding Maximum Drawdown���������������������������������������������������������������������������������� 201
The Downside of Drawdown Risk���������������������������������������������������������������������������������������� 203
Calculating the Max Drawdown������������������������������������������������������������������������������������������������ 204
Backtesting the Trend-Following Strategy�������������������������������������������������������������������������������� 216
Summary���������������������������������������������������������������������������������������������������������������������������������� 222
Exercises����������������������������������������������������������������������������������������������������������������������������������� 223

Chapter 8: Statistical Arbitrage with Hypothesis Testing������������������������������������� 225


Statistical Arbitrage������������������������������������������������������������������������������������������������������������������ 225
Pairs Trading������������������������������������������������������������������������������������������������������������������������ 227
Cointegration����������������������������������������������������������������������������������������������������������������������� 229
Stationarity�������������������������������������������������������������������������������������������������������������������������� 232
Test for Cointegration���������������������������������������������������������������������������������������������������������� 236
Correlation and Cointegration���������������������������������������������������������������������������������������������� 240
Implementing the Pairs Trading Strategy���������������������������������������������������������������������������������� 242
Identifying Cointegrated Pairs of Stocks����������������������������������������������������������������������������� 242
Testing Pairwise Cointegration�������������������������������������������������������������������������������������������� 243
Obtaining the Spread����������������������������������������������������������������������������������������������������������� 245
Converting to Z-Scores�������������������������������������������������������������������������������������������������������� 246
Formulating the Trading Strategy���������������������������������������������������������������������������������������� 250
Summary���������������������������������������������������������������������������������������������������������������������������������� 254
Exercises����������������������������������������������������������������������������������������������������������������������������������� 255

Chapter 9: Optimizing Trading Strategies with Bayesian Optimization���������������� 257


Optimizing Trading Strategies��������������������������������������������������������������������������������������������������� 257
Parametric Trading Strategies��������������������������������������������������������������������������������������������� 258
More on Optimization���������������������������������������������������������������������������������������������������������� 260
Global Optimization������������������������������������������������������������������������������������������������������������� 261
The Objective Function�������������������������������������������������������������������������������������������������������� 265

vii
Table of Contents

Bayesian Optimization��������������������������������������������������������������������������������������������������������� 268


Gaussian Process���������������������������������������������������������������������������������������������������������������� 270
Acquisition Function������������������������������������������������������������������������������������������������������������ 273
EI and UCB��������������������������������������������������������������������������������������������������������������������������� 275
The Full BO Loop����������������������������������������������������������������������������������������������������������������� 277
Optimizing the Pairs Trading Strategy��������������������������������������������������������������������������������������� 278
Trading Strategy Performance As the Black-Box Function�������������������������������������������������� 279
Generating Training Set for Bayesian Optimization������������������������������������������������������������� 284
Implementing the Gaussian Process Model������������������������������������������������������������������������ 286
Guiding the Sequential Search by Maximizing the Acquisition Function����������������������������� 288
Performing Sequential Search��������������������������������������������������������������������������������������������� 292
Summary���������������������������������������������������������������������������������������������������������������������������������� 300
Exercises����������������������������������������������������������������������������������������������������������������������������������� 301

Chapter 10: Pairs Trading Using Machine Learning���������������������������������������������� 303


Machine Learning in Pairs Trading�������������������������������������������������������������������������������������������� 303
Machine Learning Workflow������������������������������������������������������������������������������������������������ 304
Support Vector Machine������������������������������������������������������������������������������������������������������ 306
Random Forest�������������������������������������������������������������������������������������������������������������������� 308
Neural Network������������������������������������������������������������������������������������������������������������������� 310
Implementing the Pairs Trading Strategy Using Machine Learning������������������������������������������ 313
Feature Engineering������������������������������������������������������������������������������������������������������������ 315
Pairs Trading Using SVM������������������������������������������������������������������������������������������������������ 316
Pairs Trading Using Random Forest������������������������������������������������������������������������������������� 319
Pairs Trading Using Neural Networks���������������������������������������������������������������������������������� 320
Summary���������������������������������������������������������������������������������������������������������������������������������� 324
Exercises����������������������������������������������������������������������������������������������������������������������������������� 325

Index��������������������������������������������������������������������������������������������������������������������� 327

viii
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).

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

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

1
© Peng Liu 2023
P. Liu, Quantitative Trading Strategies Using Python, https://doi.org/10.1007/978-1-4842-9675-2_1
Chapter 1 Quantitative Trading: An Introduction

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.

2
Chapter 1 Quantitative Trading: An Introduction

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.

3
Chapter 1 Quantitative Trading: An Introduction

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.

4
Chapter 1 Quantitative Trading: An Introduction

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.

5
Chapter 1 Quantitative Trading: An Introduction

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]

6
Chapter 1 Quantitative Trading: An Introduction

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

7
Chapter 1 Quantitative Trading: An Introduction

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.

8
Chapter 1 Quantitative Trading: An Introduction

• 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

9
Chapter 1 Quantitative Trading: An Introduction

exchange one currency for the equivalent value in another currency


at the current market rate. Traders also speculate on the direction
of currency values to profit from a favorable price movement of a
particular pair of currencies.

• ETFs: Exchange-traded funds that refer to a type of pooled


investment security that are baskets of securities (stocks, bonds,
commodities, etc.) and are traded intraday like regular stocks.

• REITs: Real estate investment trusts that refer to companies that own,
operate, or finance income-generating real estate. Investors in REITs
(liquid and publicly traded like stocks) can earn a steady income
stream from real estate investments without purchasing, managing,
or financing the actual properties themselves.

• Mutual funds: A type of financial vehicle that consists of a portfolio


of stocks, bonds, or other securities. Mutual funds are managed
by professional money managers and allow individual investors
to access diversified and professionally managed portfolios at the
expense of annual fees. Mutual funds only can be purchased at the
end of each trading day based on a calculated price known as the net
asset value.

• Hedge funds: Actively managed investment pools that aim at earning


above-average returns for investors via a wide range of (often risky)
trading strategies at the expense of higher fees than conventional
investment funds.

These tradable asset types can be grouped into different classes based on a particular
perspective. We introduce a few popular perspectives in the following section.

Grouping Tradable Assets


An asset class is a collection of investment instruments that exhibit similar fundamental
characteristics in terms of risk and return. There are four major asset classes: equities,
fixed-income instruments, cash and equivalents, and alternative investments, defined as
financial assets that do not fall into prior investment categories. Figure 1-3 illustrates the
four classes of investment securities.

10
Chapter 1 Quantitative Trading: An Introduction

Figure 1-3. Grouping common investment assets into four major classes

Alternatively, we can group tradable assets based on the type of maturity. Stocks,
currencies, and commodities are asset classes with no maturity, while fixed-income
instruments and derivatives have maturities. For vanilla security with a maturity date,
such as a futures contract, it is possible to compute its fair price based on the no-­
arbitrage argument, a topic we will discuss in Chapter 3.
We can also group assets based on the linearity of the payoff function at maturity
for certain derivative instruments. For example, a futures contract allows the buyer/
seller to buy/sell the underlying asset at an agreed price at maturity. Let us assume the
underlying (stock) price at the maturity date is ST and the agreed price is K. When a
buyer enters/longs a futures contract to buy the stock at price K, the buyer would make
a profit of ST − K if ST ≥ K (purchase the stock at a lower price) or suffer a loss of K − ST
if ST < K (purchase the stock at a higher price). A similar analysis applies to the case of
entering a short position in a futures contract. Both functions are linear with respect
to the underlying asset’s price upon exercise. See Figure 1-4 for an illustration of linear
payoff functions.

11
Chapter 1 Quantitative Trading: An Introduction

Figure 1-4. Illustration of the linear payoff function of entering a long or short
position in a futures contract

Other derivative products with linear payoff functions include forwards and swaps.
These are easy to price since their prices are linear functions of the underlying asset. We
can price these instruments irrespective of the mathematical model for the underlying
price. In other words, we only require the underlying asset’s price, not the mathematical
model around the asset. These assets are thus subject to model-independent pricing.
Let us look at the nonlinear payoff function from an options contract. A call option
gives the buyer a choice to buy the underlying asset at the strike price K at the maturity
date T when the underlying asset price is ST, while a put option changes such choice
to selling the underlying asset at the strike price K. Under both situations, the buyer
can choose not to exercise the option and therefore gains no profit. Given that an
investor can either long or short a call or put option, there are four combinations when
participating in an options contract, as listed in the following:

• Long a call: Buy a call option to obtain the opportunity to buy the
underlying asset at a prespecified strike price upon maturity.

• Short a call: Sell a call option to allow the buyer the opportunity to
buy the underlying asset at a prespecified strike price upon maturity.

12
Chapter 1 Quantitative Trading: An Introduction

• Long a put: Buy a put option to obtain the opportunity to sell the
underlying asset at a prespecified strike price upon maturity.

• Short a put: Sell a put option to allow the buyer the opportunity to
sell the underlying asset at a prespecified strike price upon maturity.

Figure 1-5 contains the payoff functions for the four different combinations, all of
which are nonlinear functions of the underlying asset price ST.

Figure 1-5. Four types of nonlinear payoff functions in an options contract

Note that tradable instruments within the same asset class exhibit similar
characteristics but will differ from one another in some aspects. The market behavior
will differ for tradable instruments that follow their respective price dynamics.
We can also group a tradable asset according to whether it belongs to the cash
market or the derivative market. The cash market, also called the spot market, is
a marketplace where trading instruments are exchanged at the point of sale, and

13
Chapter 1 Quantitative Trading: An Introduction

purchasers take immediate possession of the trading products. For example, the stock
exchange falls into the cash market since investors receive shares of stock almost
immediately in exchange for cash, thus settling the transactions on the spot.
On the other hand, the derivative market completes a transaction only at a
prespecified date in the future. Take the futures market, for example. A buyer who
pays for the right to receive a good only gets to expect the delivery at a prespecified
future date.
The next section introduces common trading avenues and steps.

Common Trading Avenues and Steps


As mentioned earlier, investors engage in trading activities for the purpose of profit-­
making or risk management. When the purpose is to invest and make profits, the next
sequence of actions is to observe and analyze the market and act upon the trading
signals. For example, if investors use predictive methods to predict when the market
will go up or down, they can initiate trades to turn the market into profits and make
short, instant wins. Such activity is referred to as market timing, where an investor enters
or exits a position or rebalances a portfolio (moving money between assets) based on
predicted market movement in the near future. This is opposite to the buy-and-hold
strategy, where an investor purchases trading instruments and holds them for a long
period, irrespective of the market’s volatility (ups and downs).
When engaging in trading activity, it is important to understand the short-term
and long-term seasonality effect for a particular tradable asset. Take stock trading, for
example. Short-term swings in stock prices tend to occur when the market opens and
closes, falling under the regular trading hours of major stock exchanges and forming the
opening and closing prices of the particular day. In the longer term, trading activities at
the end of the year tend to be quieter than other periods of the particular year.
Trading activities can happen at one of the following four avenues:

• Regulated exchanges, such as the New York Stock Exchange (NYSE)


and NASDAQ

• Dark pools, private exchanges that are less regulated


• Brokered market, where transactions between the buyer and the
seller are performed via middlemen called brokers (or agents,
intermediaries)

14
Chapter 1 Quantitative Trading: An Introduction

• Over-the-counter (OTC) market, a decentralized market that allows


direct transactions between buyers and sellers

Let us look at the anatomy of a trade. There are four usual steps involved when
performing a trade:

• Acquisition of information and quotes: Before engaging in a trade, it


is important to access quality information about the asset and gain
transparency in many tangible and intangible factors such as supply
and demand, the risk attitude of investors, and the overall economic
and geopolitical environment. Information on the market structure,
liquidity, and information flow eventually determine the price
discovery of the tradable asset.

• Routing of order, such as selecting the broker(s) to handle the


trade(s) or deciding which market(s) to transmit and execute the
trade(s).

• Execution of order, matching and executing the trading orders


between buyers and sellers according to the rules of the
particular market.

• Confirmation, clearance, and settlement: This happens at the end of


executing a trading order. Clearance is the recording and comparison
of trade records, and settlement involves the actual delivery of the
security and its payment.

In the next section, we will look at different market structures.

Market Structures
Before 2010, open outcry was a popular way to communicate trade orders in trading
pits (floor). Traders would tap into temporary information asymmetry and use verbal
communication and hand signals to perform trading activities at stock, option, and
futures exchanges. Traders would arrange their trades face to face on the exchange’s
trading floor, cry out bids and offers to offer liquidity, and listen for bids and offers to
take liquidity. The open outcry rule is that traders must announce their bids and offers
so that other traders may react to them, avoiding whispering among a small group of
traders. They must also publicly announce that they accept bids (assets sold) or offers

15
Chapter 1 Quantitative Trading: An Introduction

(assets taken) of particular trades. The largest pit was the US long-term treasury bond
futures market, with over 500 floor traders under the Chicago Board of Trade (CBOT), a
major market maker that later merged into the CMT Group.
As technology advanced, the trading markets moved from physical to electronic,
shaping a fully automated exchange. First proposed by Fischer Black in 1971, the fully
automated exchange was also called program trading, which encompasses a wide range
of portfolio trading strategies.
The trading rules and systems together define a trading market’s market structure.
One type of market is called the call market, where trades are allowed only when the
market is called. The other type of market is the continuous market, where trades
are allowed anytime during regular trading hours. Big exchanges such as NYSE, LSE
(London Stock Exchange), and SGX (Singapore Exchange) allow a hybrid mode of
market structure.
The market structure can also be categorized based on the nature of pricing among
the tradable assets. When the prices are determined based on the bid (buy) and ask (sell)
quotations from market makers or dealers, it is called a quote-driven or price-driven
market. The trades are determined by dealers and market makers who participate in
every trade and match orders from their inventory. Typical assets in a quote-driven
market include bonds, currencies, and commodities.
On the other hand, when the trades are based on the buyers’ and sellers’
requirements, it is called an order-driven market where the bid and ask prices, along
with the number of shares desired, are put on display. Typical assets in an order-driven
market include stock markets, futures exchanges, and electronic communications
networks (ECNs). There are two basic types of orders: market orders, based on the asset’s
market price, and limit orders, where the assets are only traded based on the preset
limit price.
Let us look at a few major types of buy-side stock investors.

Major Types of Buy-Side Stock Investors


Buy-side investors include institutional (account for the majority) and retail investors.
Here, buy-side activities include purchasing stocks, bonds, or other financial securities
based on the specific requirements and strategies of the institution’s or client’s portfolio.
The buy side is a segment of financial markets made up of investing institutions and
retail investors that purchase financial products for money-management purposes.

16
Chapter 1 Quantitative Trading: An Introduction

Typical buy-side institutional investors include

• Mutual fund

• Passive exchange-traded fund (ETF)

• Pension fund

• Sovereign wealth fund

• Hedge fund

• Insurance company

• Bank

• Corporate nominee

Typical buy-side retail investors include

• Start-up investor

• Family business

• Household/individual

The next section introduces the concept of market making.

Market Making
Market maker refers to a firm or an individual that actively quotes the two-sided markets
(buy side and sell side) of a particular security. The market maker provides bids,
meaning the particular price of the security along with the quantity it is willing to buy. It
also provides offers (asks), meaning the price of the security and the quantity it is willing
to sell. Naturally, the asking price is supposed to be higher than the bid price, so that the
market maker can make a profit based on the spread of the two quote prices.
Market makers post quotes and stand ready to trade, thereby providing immediacy
and liquidity to the market. By quoting bid and ask prices, market makers make the
assets more liquid for potential buyers and short sellers.
A market maker also takes a significant risk of holding the assets because a security’s
value may decline between its purchase and sale to another buyer. They need capital to
finance their inventories. The capital available to them thus limits their ability to offer
liquidity. Because market making is very risky, investors generally dislike investing in

17
Chapter 1 Quantitative Trading: An Introduction

market-making operations. Market-making firms with significant external financing


typically have excellent risk management systems that prevent their dealers from
generating large losses.
The next section introduces the concept of scalping.

Scalping
Scalping is a type of trading that makes small and fast profits by quickly (typically no
more than a few minutes in large positions) and continuously acquiring and unwinding
their positions. Traders that engage in scalping are referred to as scalpers.
When engaged in scalping, a trader requires a live feed of quotes in order to move
fast. The trader, also called the day trader, must follow a strict exit strategy because one
large loss could eliminate the many small gains the trader worked to accumulate.
Active traders such as day traders are strong believers in market timing, a key
component of actively managed investment strategies. For example, if traders can
predict when the market will go up and down, they can make trades to turn that market
move into a profit. Obviously, this is a difficult and strenuous task as one needs to watch
the market continuously, from daily to even hourly, as compared to long-term position
traders that invest for the long run.
The next section introduces the concept of portfolio rebalancing.

Portfolio Rebalancing
As time goes on, a portfolio’s current asset allocation will drift away from an investor’s
original target asset allocation. If left unadjusted, the portfolio will either become too
risky or too conservative. Such rebalancing is completed by changing the position of one
or more assets in the portfolio, either buying or selling, with the goal of maximizing the
portfolio return or hedging another financial instrument.
Asset allocations in a portfolio can change as market performance alters the values of
the assets due to price changes. Rebalancing involves periodically buying or selling the
assets in a portfolio to regain and maintain that original, desired level of asset allocation
defined by an investor’s risk and reward profile.
There are several reasons why a portfolio may deviate from its target allocation
over time, such as due to market fluctuations, additional cash injection or withdrawal,
and changes in risk tolerance. We can perform portfolio rebalancing using either a

18
Chapter 1 Quantitative Trading: An Introduction

time-based rebalancing approach (e.g., quarterly or annually) or a threshold-based


rebalancing approach, which occurs when the allocation of an asset class deviates from
the target by a predefined percentage.
In the world of quantitative trading, Python has emerged as a powerful tool
for formulating and implementing trading algorithms. Part of the reason is its
comprehensive open source libraries and strong community support. In the next
section, we will discuss the practical aspect of financial data analysis and start by
acquiring and summarizing the stock data using Python.

Getting Started with Financial Data Analysis


Financial data analysis is the process of processing and analyzing financial data to
support decision-making in various financial applications, such as investing, trading,
risk management, and corporate finance. It involves the use of advanced analytical
techniques and models to identify the underlying patterns, trends, and relationships in
the data, which will be used to support more informed financial decisions.
The interval of stock data can be different, such as by minute, hour, or day. Since
time is continuous, we need a measure to summarize the profile of the stock price
data within the interval. Let us start by introducing one of the most popular ways to
summarize stock data.

Summarizing Stock Prices


The most common type of summary for stock data is the daily OHLC prices (open, high,
low, close). An OHLC chart is a bar chart that shows open, high, low, and closing prices
for each period, often daily. They present a day’s four major data points, with the closing
price considered the most important indicator by many traders.
The OHLC chart, similar to the candlestick chart shown in Figure 1-6, is useful
because it can show increasing or decreasing momentum. When the open and closing
prices have a big gap in between, it shows a strong momentum for an increase or
decrease in the day. When the open and closing prices are close, it shows indecision or a
weak momentum. The high and low prices show the full price range and can be used to
assess the volatility.

19
Chapter 1 Quantitative Trading: An Introduction

Figure 1-6 shows two candlestick charts, both summarizing the price movements
over a specified period, for example, daily. The color represents emotions for the stock
price movement, with an up candle shaded green and a down candle shaded red,
although these colors can be altered in the specific trading platform. A collection of
candlestick charts can be used to determine the direction of the market movement. Each
candlestick chart consists of four main points: open, high, low, and close, following the
sequence of time in the period. The open and close points determine the real body of
the candlestick. The green color represents a bullish candlestick, that is, the stock price
closes above where it opens. Similarly, the red color represents a bearish candlestick,
that is, the stock price closes below where it opens.

Figure 1-6. Illustrating the bullish candlestick in green and bearish


candlestick in red

Let us examine the bullish candle in the green of a trading day. When the market
starts, the stock assumes an opening price and starts to move. Across the day, the stock
will experience the highest price point (high) and the lowest price point (low), where
the gap in between indicates the momentum of the movement. We know for a fact that
the high will always be higher than the low, as long as there is movement. When the
market closes, the stock registers a close. Figure 1-7 depicts a sample movement path
summarized by the green candlestick.

20
Chapter 1 Quantitative Trading: An Introduction

Figure 1-7. A sample path of stock price movement represented by the green
candlestick chart. When the market starts, the stock assumes an opening price and
starts to move. It will experience the highest price point (high) and the lowest price
point (low), where the gap in between indicates the momentum of the movement.
When the market closes, the stock registers a close

Next, we will switch gears and start working on the actual stock price data using
Python. We will download the data from Yahoo! Finance and introduce different ways to
graph the data.

Downloading Stock Price Data


Yahoo! Finance is a common source where we can get market data. To download the
stock price data, we can use the yfinance library, a popular open source (and free)
library, to access the financial data available on Yahoo! Finance. It is relatively quick to
set up and offers a high level of granularity in the data (covering daily or even
per-­minute data).
To start with, we need to install the yfinance package via the pip command in the
Jupyter notebook environment and import it:

!pip install yfinance


import yfinance as yf

Next, we can use the Ticker() module from the yfinance package to observe the
profile information of a specific stock. The following code snippet obtains the ticker
information on Microsoft and prints it out via the info attribute:

21
Chapter 1 Quantitative Trading: An Introduction

# use the Ticker module to access ticker data


msft = yf.Ticker("MSFT")

# get stock info


>>> msft.info
{'zip': '98052-6399',
'sector': 'Technology',
'fullTimeEmployees': 221000,
'longBusinessSummary': 'Microsoft Corporation develops, licenses, and
supports software, services, devices, and solutions worldwide. The
company operates in three segments: Productivity and Business Processes,
Intelligent Cloud, and More Personal Computing. The Productivity and
Business Processes segment offers Office, Exchange, SharePoint, Microsoft
Teams, Office 365 Security and Compliance, Microsoft Viva, and Skype for
Business; Skype, Outlook.com, OneDrive, and LinkedIn; and Dynamics 365, a
set of cloud-based and on-premises business solutions for organizations and
enterprise divisions. The Intelligent Cloud segment licenses SQL, Windows
Servers, Visual Studio, System Center, and related Client Access Licenses;
GitHub that provides a collaboration platform and code hosting service
for developers; Nuance provides healthcare and enterprise AI solutions;
and Azure, a cloud platform. It also offers enterprise support, Microsoft
consulting, and nuance professional services to assist customers in
developing, deploying, and managing Microsoft server and desktop solutions;
and training and certification on Microsoft products. The More Personal
Computing segment provides Windows original equipment manufacturer (OEM)
licensing and other non-volume licensing of the Windows operating system;
Windows Commercial, such as volume licensing of the Windows operating
system, Windows cloud services, and other Windows commercial offerings;
patent licensing; and Windows Internet of Things. It also offers Surface,
PC accessories, PCs, tablets, gaming and entertainment consoles, and
other devices; Gaming, including Xbox hardware, and Xbox content and
services; video games and third-party video game royalties; and Search,
including Bing and Microsoft advertising. The company sells its products
through OEMs, distributors, and resellers; and directly through digital
marketplaces, online stores, and retail stores. Microsoft Corporation was
founded in 1975 and is headquartered in Redmond, Washington.',

22
Chapter 1 Quantitative Trading: An Introduction

'city': 'Redmond',
'phone': '425 882 8080',
'state': 'WA',
'country': 'United States',
'companyOfficers': [],
'website': 'https://www.microsoft.com',
'maxAge': 1,
'address1': 'One Microsoft Way',
'fax': '425 706 7329',
'industry': 'Software—Infrastructure',
'ebitdaMargins': 0.48672,
'profitMargins': 0.34366,
'grossMargins': 0.6826,
'operatingCashflow': 87693000704,
'revenueGrowth': 0.106,
'operatingMargins': 0.41691002,
'ebitda': 98841001984,
'targetLowPrice': 234,
'recommendationKey': 'buy',
'grossProfits': 135620000000,
'freeCashflow': 46155874304,
'targetMedianPrice': 290,
'currentPrice': 238.73,
'earningsGrowth': -0.133,
'currentRatio': 1.84,
'returnOnAssets': 0.15223,
'numberOfAnalystOpinions': 45,
'targetMeanPrice': 296.91,
'debtToEquity': 44.442,
'returnOnEquity': 0.42875,
'targetHighPrice': 411,
'totalCash': 107244003328,
'totalDebt': 77136003072,
'totalRevenue': 203074994176,
'totalCashPerShare': 14.387,

23
Chapter 1 Quantitative Trading: An Introduction

'financialCurrency': 'USD',
'revenuePerShare': 27.142,
'quickRatio': 1.585,
'recommendationMean': 1.8,
'exchange': 'NMS',
'shortName': 'Microsoft Corporation',
'longName': 'Microsoft Corporation',
'exchangeTimezoneName': 'America/New_York',
'exchangeTimezoneShortName': 'EST',
'isEsgPopulated': False,
'gmtOffSetMilliseconds': '-18000000',
'quoteType': 'EQUITY',
'symbol': 'MSFT',
'messageBoardId': 'finmb_21835',
'market': 'us_market',
'annualHoldingsTurnover': None,
'enterpriseToRevenue': 8.615,
'beta3Year': None,
'enterpriseToEbitda': 17.7,
'52WeekChange': -0.30287635,
'morningStarRiskRating': None,
'forwardEps': 11.18,
'revenueQuarterlyGrowth': None,
'sharesOutstanding': 7454470144,
'fundInceptionDate': None,
'annualReportExpenseRatio': None,
'totalAssets': None,
'bookValue': 23.276,
'sharesShort': 40445360,
'sharesPercentSharesOut': 0.0054,
'fundFamily': None,
'lastFiscalYearEnd': 1656547200,
'heldPercentInstitutions': 0.72300005,
'netIncomeToCommon': 69788999680,
'trailingEps': 9.29,

24
Chapter 1 Quantitative Trading: An Introduction

'lastDividendValue': 0.68,
'SandP52WeekChange': -0.19752294,
'priceToBook': 10.256488,
'heldPercentInsiders': 0.00059,
'nextFiscalYearEnd': 1719705600,
'yield': None,
'mostRecentQuarter': 1664496000,
'shortRatio': 1.38,
'sharesShortPreviousMonthDate': 1667174400,
'floatShares': 7447764118,
'beta': 0.933189,
'enterpriseValue': 1749498331136,
'priceHint': 2,
'threeYearAverageReturn': None,
'lastSplitDate': 1045526400,
'lastSplitFactor': '2:1',
'legalType': None,
'lastDividendDate': 1668556800,
'morningStarOverallRating': None,
'earningsQuarterlyGrowth': -0.144,
'priceToSalesTrailing12Months': 8.763292,
'dateShortInterest': 1669766400,
'pegRatio': 1.92,
'ytdReturn': None,
'forwardPE': 21.353308,
'lastCapGain': None,
'shortPercentOfFloat': 0.0054,
'sharesShortPriorMonth': 36909448,
'impliedSharesOutstanding': 0,
'category': None,
'fiveYearAverageReturn': None,
'previousClose': 238.19,
'regularMarketOpen': 236.11,
'twoHundredDayAverage': 261.927,
'trailingAnnualDividendYield': 0.010663755,

25
Chapter 1 Quantitative Trading: An Introduction

'payoutRatio': 0.26700002,
'volume24Hr': None,
'regularMarketDayHigh': 238.87,
'navPrice': None,
'averageDailyVolume10Day': 35831410,
'regularMarketPreviousClose': 238.19,
'fiftyDayAverage': 240.6454,
'trailingAnnualDividendRate': 2.54,
'open': 236.11,
'toCurrency': None,
'averageVolume10days': 35831410,
'expireDate': None,
'algorithm': None,
'dividendRate': 2.72,
'exDividendDate': 1676419200,
'circulatingSupply': None,
'startDate': None,
'regularMarketDayLow': 233.9428,
'currency': 'USD',
'trailingPE': 25.697523,
'regularMarketVolume': 21206982,
'lastMarket': None,
'maxSupply': None,
'openInterest': None,
'marketCap': 1779605569536,
'volumeAllCurrencies': None,
'strikePrice': None,
'averageVolume': 30495014,
'dayLow': 233.9428,
'ask': 238.45,
'askSize': 800,
'volume': 21206982,
'fiftyTwoWeekHigh': 344.3,
'fromCurrency': None,
'fiveYearAvgDividendYield': 1.17,

26
Chapter 1 Quantitative Trading: An Introduction

'fiftyTwoWeekLow': 213.43,
'bid': 238.2,
'tradeable': False,
'dividendYield': 0.0114,
'bidSize': 1000,
'dayHigh': 238.87,
'coinMarketCapLink': None,
'regularMarketPrice': 238.73,
'preMarketPrice': None,
'logo_url': 'https://logo.clearbit.com/microsoft.com',
'trailingPegRatio': 2.1113}

The result shows a long list of information about Microsoft, useful for our initial
analysis of a particular stock. Note that all this information is structured in the form of a
dictionary, making it easy for us to access a specific piece of information. For example,
the following code snippet prints the market cap of the stock:

# access a specific attribute from the dictionary


>>> msft.info["marketCap"]
1779605569536

Such structured information, also considered metadata in this context, comes in


handy when we analyze multiple tickers together.
Now let us focus on the actual stock data of Microsoft. In Listing 1-2, we download
the stock price data of Microsoft from the beginning of 2022 till the current date. Here,
the current date is determined automatically by the today() function from the datetime
package, which means we will obtain a different (bigger) result every time we run the
code on a future date. We also specify the format of the date to be “YYYY-mm-dd,” an
important practice to unify the date format.

Listing 1-2. Downloading stock price data

# download daily stock price data by passing in specified ticker and


date range
from datetime import datetime
today_date = datetime.today().strftime('%Y-%m-%d')
print(today_date)
data = yf.download("MSFT", start="2022-01-01", end=today_date)

27
Chapter 1 Quantitative Trading: An Introduction

We can examine the first few rows by calling the head() function of the DataFrame.
The resulting table contains price-related information such as open, high, low, close,
and adjustment close prices, along with the daily trading volume:

# view the first few rows.


>>> data.head()
           Open       High       Low        Close      Adj Close  Volume
Date
2022-01-03 335.350006 338.000000 329.779999 334.750000 331.642456 28865100
2022-01-04 334.829987 335.200012 326.119995 329.010010 325.955750 32674300
2022-01-05 325.859985 326.070007 315.980011 316.380005 313.442993 40054300
2022-01-06 313.149994 318.700012 311.489990 313.880005 310.966217 39646100
2022-01-07 314.149994 316.500000 310.089996 314.040009 311.124725 32720000

We can also view the last few rows using the tail() function:

>>> data.tail()
           Open       High       Low        Close      Adj Close  Volume
Date
2022-12-30 238.210007 239.960007 236.660004 239.820007 239.820007 21930800
2023-01-03 243.080002 245.750000 237.399994 239.580002 239.580002 25740000
2023-01-04 232.279999 232.869995 225.960007 229.100006 229.100006 50623400
2023-01-05 227.199997 227.550003 221.759995 222.309998 222.309998 39585600
2023-01-06 223.000000 225.759995 219.350006 224.929993 224.929993 43597700

It is also a good habit to check the dimension of the DataFrame using the shape()
function:

# check data dimension/size


>>> data.shape
(254, 6)

The following section will look at visualizing the time series data via
interactive charts.

28
Chapter 1 Quantitative Trading: An Introduction

Visualizing Stock Price Data


The plotly package is an interactive graphing library that supports exploratory and
expository visualizations. Let us demonstrate its use via a few examples, focusing on the
stock’s closing price for now.
First, let us visualize the closing price as a time series plot. As the name suggests,
a time series is a sequence of data with a timestamp in each data point. Thus, when
plotted on a graph, the horizontal axis indicates the time that flows from left to right,
and the vertical axis represents the quantity of interest, that is, the daily closing price.
Also, since each timestamp corresponds to one stand-alone point on the graph, we will
connect all neighboring points via straight lines to form the final time series plot and
show the trending patterns.
Listing 1-3 completes this task. Here, we pass the index of the DataFrame to indicate
the dates on the x-axis (passed to the x argument) and the closing pricing on the y-axis
(passed to the y argument) and specify the presentation mode to be in lines.

Listing 1-3. Plotting the daily closing price

# plot closing price as a time series chart


import plotly.graph_objects as go

fig = go.Figure(data=go.Scatter(x=data.index,y=data['Close'],
mode='lines'))
fig.show()

Running the code produces Figure 1-8. Note that the graph is interactive; by hovering
over each point, the corresponding date and closing price come forward.

Figure 1-8. Interactive time series plot of the daily closing price of Microsoft

29
Chapter 1 Quantitative Trading: An Introduction

We can also enrich the graph by overlaying the trading volume information, as
shown in Listing 1-4.

Listing 1-4. Overlaying trading volume in the daily closing price chart

# overlay the trading volume


from plotly.subplots import make_subplots

fig2 = make_subplots(specs=[[{"secondary_y": True}]])


fig2.add_trace(go.Scatter(x=data.index,y=data['Close'],name='Price'),
secondary_y=False)
fig2.add_trace(go.Bar(x=data.index,y=data['Volume'],name='Volume'),
secondary_y=True)
fig2.show()

Running the code generates Figure 1-9. Note that the trading volume assumes a
secondary y-axis on the right, by setting secondary_y=True.

Figure 1-9. Visualizing the daily closing price and trading volume of Microsoft

Based on this graph, a few bars stand out, making it difficult to see the line chart.
Let us change it by controlling the magnitude of the secondary y-axis. Specifically, we
can enlarge the total magnitude of the right y-axis to make these bars appear shorter, as
shown in Listing 1-5.

Listing 1-5. Rescaling the y-axis

# rescale volume
fig2.update_yaxes(range=[0,500000000],secondary_y=True)
fig2.update_yaxes(visible=True, secondary_y=True)
fig2

30
Chapter 1 Quantitative Trading: An Introduction

Running the code generates Figure 1-10. Now the bars appear shorter given a bigger
range (0 to 500M) of the y-axis on the right.

Figure 1-10. Controlling the magnitude of the daily trading volume as bars

Lastly, let us plot all the price points via candlestick charts. This requires us to pass
in all the price-related information in the DataFrame. The Candlestick() function can
help us achieve this, as shown in Listing 1-6.

Listing 1-6. Plotting the candlestick chart

# switch to candlestick chart


fig3 = make_subplots(specs=[[{"secondary_y": True}]])
fig3.add_trace(go.Candlestick(x=data.index,
                              open=data['Open'],
                              high=data['High'],
                              low=data['Low'],
                              close=data['Close'],
                             ))
fig3

Running the code generates Figure 1-11. Each bar represents one day’s summary
points (open, high, low, and close), with the green color indicating an increase in price
and red indicating a decrease in price at the end of the trading day.

31
Chapter 1 Quantitative Trading: An Introduction

Figure 1-11. Visualizing all daily price points of Microsoft as candlestick charts

Notice the sliding window at the bottom. We can use it to zoom in a specific range, as
shown in Figure 1-12. The dates along the x-axis are automatically adjusted as we zoom
in. Also, note that these bars come in groups of five. This is no incidence—there are five
trading days in a week.

Figure 1-12. Zooming in a specific range

Summary
In this chapter, we covered the basics of quantitative trading, covering topics such as
institutional algorithmic trading, major asset classes, derivatives such as options, market
structures, buy-side investors, market making, scalping, and portfolio rebalancing. We
then delved into exploratory data analysis of the stock data, starting with summarizing
the periodic data points using candlestick charts. We also reviewed the practical side of
things, covering data retrieval, analysis, and visualization via interactive charts. These
will serve as the building blocks as we develop different trading strategies later on.

32
Chapter 1 Quantitative Trading: An Introduction

Exercises
• List a few financial instruments and describe the risk and reward
profile.

• Can a model get exposed to the test set data during training?

• A model is considered better if it does better than another model on


the training set, correct?
• For daily stock price data, can we aggregate it as weekly data? How
about hourly?

• What is the payoff function for the issuer of a European call option?
Put option? How is it connected to the payoff function of the buyer?

• Suppose you purchase a futures contract that requires you to sell a


particular commodity one month later for a price of $10,000. What
is your payoff when the price of the commodity grows to $12,000?
Drops to $7000?

• What about the payoff for the buyer in both cases?

• How do the results change if we switch to an options contract with


the same strike price and delivery date?

• Draw a sample stock price curve of a red candlestick.

• Download the stock price data of Apple, plot it as both a line and a
candlestick chart, and analyze its trend.

• Calculate the YTD (year-to-date) average stock price of Apple.

33
CHAPTER 2

Electronic Market
In this chapter, we delve into the world of electronic markets, which have revolutionized
the way financial instruments are traded. With the rapid advancements in technology
and the widespread adoption of the Internet, electronic markets have largely replaced
traditional, floor-based trading venues, ushering in an era of speed, efficiency, and
accessibility for market participants around the globe.
Electronic markets facilitate the buying and selling of financial instruments,
such as stocks, bonds, currencies, and commodities (covered in Chapter 1), through
computerized systems and networks. They have played a critical role in democratizing
access to financial markets, enabling a broader range of participants, including retail
investors, institutional investors, and high-frequency traders, to engage in trading
activities with ease and transparency. At the heart of electronic markets lies the trading
mechanism, which governs how buy and sell orders are matched, executed, and settled.
Furthermore, electronic markets offer a variety of order types that cater to the diverse
needs and objectives of traders. These order types can be used to achieve specific goals,
such as minimizing market impact, ensuring a desired level of execution, or managing
risk. In this chapter, we will examine the most common types of orders, including market
orders, limit orders, stop orders, and their various iterations.
As we progress through this chapter, readers will gain a comprehensive
understanding of the inner workings of electronic markets, the trading mechanisms that
drive them, and the wide array of order types available to market participants.

Introducing Electronic Market


The electronic market operates on the basis of a discrete price grid where prices are
arranged linearly according to the price magnitude. Every market has a minimum tick
size. One tick is the minimum price difference between any two adjacent prices on
the price grid of a trading instrument in a market. The price movements of different

35
© Peng Liu 2023
P. Liu, Quantitative Trading Strategies Using Python, https://doi.org/10.1007/978-1-4842-9675-2_2
Chapter 2 Electronic Market

trading instruments could vary a lot, and we use their respective tick sizes to represent
the minimum amount they can move up or down on an exchange. Stocks generally
trade in one-cent tick size increments, currencies in pips (percentage in point or price
interest point), and rates in basis points (bps). When the price grid is such that prices are
arranged from the smallest price to the largest price, it is called the price ladder.
The price ladder plays a crucial role in electronic markets by providing a visual
representation of the order book, which contains a list of all pending buy and sell orders
for a specific trading instrument. The order book is continuously updated in real time,
reflecting the dynamic nature of the market as new orders are placed, modified, or
canceled. Each rung of the price ladder corresponds to a specific price level, with buy
orders (or bids) listed on one side and sell orders (or asks) on the other. The highest bid
and the lowest ask are referred to as the best bid and best ask, respectively, and the gap
between them is known as the bid-ask spread.
Market participants can use the information provided by the price ladder and order
book to gain valuable insights into a particular trading instrument’s supply and demand
dynamics. This data can help traders identify potential trading opportunities, assess
liquidity, and gauge the depth of the market at various price levels. For instance, large
clusters of orders at specific price points may indicate significant support or resistance
levels, while a thinning order book might suggest a lack of liquidity and increased price
volatility. By carefully analyzing the price ladder and order book, traders can make
more informed decisions and develop strategies that take advantage of the prevailing
market conditions. Additionally, understanding the role of tick sizes in the price grid is
crucial for traders when placing orders, managing risk, and executing trades, as even
small changes in tick sizes can have a substantial impact on the potential profit or loss of
a trade.

Electronic Order
The rise of electronic trading has brought about significant improvements in the
efficiency, speed, and accessibility of financial markets. Transactions that once
took minutes or hours to complete can now be executed in milliseconds or even
microseconds, thanks to the power of high-speed networks and advanced computer
algorithms. As a result, market participants can take advantage of fleeting trading
opportunities, react more swiftly to market news, and benefit from tighter bid-ask
spreads, which translate into lower transaction costs.

36
Chapter 2 Electronic Market

Moreover, electronic trading has democratized access to global financial markets,


allowing individual investors to trade alongside institutional players such as hedge
funds, banks, and proprietary trading firms. Through user-friendly online trading
platforms, retail investors can access a vast array of financial instruments, from stocks
and bonds to currencies and derivatives, and participate in various markets around
the world. These platforms provide a wealth of market data, research tools, and risk
management features, empowering investors to make more informed decisions
and execute their trading strategies with precision and ease. At the same time, the
increased transparency and availability of market data have fostered a more competitive
landscape, driving innovation in trading strategies, algorithms, and financial products.
Orders are short messages to the exchange through the broker. An order is a set
of instructions the trader gives to the exchange. It must contain at least the following
instructions:

• Contract/security (or contracts/securities) to trade

• Buy or sell or cancel or modify

• Size: How many shares or contracts to trade

From an investor’s perspective, making a trade via a computer system is simple and
easy. However, the complex process behind the scenes sits on top of an impressive array
of technology. What was once associated with shouting traders and wild hand gestures
in open outcry markets has now become more closely associated with computerized
trading strategies.
When you place an order to trade a financial instrument, the complex technology
enables your brokerage to interact with all the securities exchanges looking to execute
the trade. Those exchanges simultaneously interact with all the brokerages to facilitate
trading activities.
For example, the Singapore Exchange (SGX), a Singaporean investment holding
company, acts through its central depository (CDP) as a central counterparty to all
matched trades (mainly securities) executed on the SGX ST Trading Engine, as well as
privately negotiated married trades that are reported to the clearing house for clearing
on the trade date. Being a central counterparty (CCP), CDP assumes the role of the seller
to the buying clearing member and buyer to the selling clearing member. CDP, therefore,
takes the buyer’s credit risks and assumes the seller’s delivery risks. This interposing
of CDP as the CCP eliminates settlement uncertainty for market participants. SGX

37
Chapter 2 Electronic Market

provides a centralized order-driven market with automated order routing, supported


by decentralized computer networks. There are no designated market makers (liquidity
providers), and member firms act as brokers or principals for clearing and settlement.

Proprietary and Agency Trading


In the world of finance, the distinction between proprietary and agency trading plays
a crucial role in determining the objectives and motivations behind trading activities.
While both types of trading involve the execution of orders in financial markets, they
serve different purposes and are subject to different regulations and risk profiles.
Proprietary trading allows financial institutions to generate profits by leveraging their
own capital and expertise in market analysis, risk management, and trading strategies.
Prop traders often engage in various strategies such as arbitrage, market making, and
statistical arbitrage, seeking opportunities to capitalize on market inefficiencies and
price discrepancies. However, proprietary trading carries a higher degree of risk due to
the full responsibility for potential losses. As a result, proprietary trading desks are often
subject to strict risk management controls and regulatory oversight, particularly in the
wake of the 2008 financial crisis.
On the other hand, agency trading focuses on providing execution services for
clients, prioritizing the best execution of client orders, and ensuring that clients’ interests
are aligned with the broker’s actions. The primary goal of agency trading is to achieve
the most favorable terms for the client while minimizing the impact of the trade on the
market. Brokers engaged in agency trading earn income through commissions and fees,
rather than by taking positions in the market. Since agency traders do not assume market
risk on behalf of their clients, they are subject to different regulatory and compliance
requirements than proprietary traders.
A broker or trading agency can execute trading orders for their clients or their own
agency. The main difference between agency and proprietary trading is the trading
client, that is, for whom the trade is executed, and whose investment portfolio is changed
as a result of trading. Agency trading is any type of trade that a broker executes for their
clients/investors who are charged a brokerage fee. Proprietary trading, also known as
prop trading, refers to when an agency or broker executes trades for the benefit of its
own institution. The orders submitted by traders for their own accounts/institutions are
called proprietary orders. Since most traders cannot access the markets directly, most
orders are agency orders, which a broker presents to the market.

38
Chapter 2 Electronic Market

Agency orders can be held or not held. Held orders are those when the broker has
an obligation to a client to fill the order. Market-not-held orders are institutional orders
where the trader hires a broker-dealer to execute the order. Working on an order means a
broker-dealer takes some time to fill the order.
Understanding the differences between proprietary and agency trading is essential
for market participants to navigate the complex world of financial markets. While
proprietary trading focuses on generating profits through active market participation,
agency trading emphasizes the execution of client orders in the best possible manner,
ensuring that the interests of clients are at the forefront of the broker’s actions.

Order Matching Systems


A securities exchange needs to pair one or more unsolicited buy orders to one or more
sell orders to make trades. This process is called matching the trading orders. When
an investor wants to purchase a specific amount of stock, and another wants to sell the
same quantity at the same price, the orders from both sides match, and a transaction
takes place. The process of pairing these orders is called order matching, whereby
exchanges identify buy orders, or bids, with corresponding sell orders, or asks, to pair
and execute both orders.
This order matching process has become almost entirely automated, using rule-­
based systems to execute the pair of trades if certain conditions are satisfied. Most
exchanges, some brokerages, and almost all electronic communication networks use
rule-based order matching systems. These trading rules arrange trades from the orders
of specific sizes that traders submit to them, not requiring face-to-face negotiation. Note
that these systems follow particular order precedence rules.
Order precedence rules are a set of guidelines that dictate the priority in which
orders are matched and executed in the market. These rules aim to ensure a fair and
efficient order matching process by determining which orders take precedence over
others in the queue. There are three primary order precedence rules followed by most
trading systems: price, time, and size.

• Price precedence: Orders with better prices are given priority over
orders with worse prices. In the case of buy orders, higher bids have
precedence, while for sell orders, lower asks are prioritized. This rule
ensures that market participants who are willing to buy at higher
prices or sell at lower prices get their orders executed first.

39
Chapter 2 Electronic Market

• Time precedence: If two or more orders have the same price, the
order that was placed earlier takes precedence. This rule, also known
as the “first-come, first-served” principle, rewards traders who
submit their orders earlier, ensuring that they are not disadvantaged
by others submitting orders at the same price later.

• Size precedence: In some markets, when multiple orders have the


same price and time priority, the order with the larger size may
be given precedence. This rule encourages market participants to
place larger orders, which can contribute to enhanced liquidity in
the market.

There are three common types of orders that an electronic exchange sees: limit
orders, market orders, and cancelation orders. Limit orders must include information
such as the limit price, order size, and trade direction (buy or sell). Market orders must
include the order size and trade direction. A cancelation order cancels a standing limit
order entirely or reduces its order size.
Note that some exchanges, such as the London Stock Exchange and the NYSE Group,
support functionality to allow traders to specify whether their limit orders are to be
displayed or not on the limit order book (LOB). This is called lit (displayed) or unlit (not
displayed). In that case, the limit order must have at least the following:

• Limit price

• Order size

• Trade direction

• Display or non-display

• If displayed, the size to be displayed

Several common order precedence rules are considered for execution. For the
order type precedence, market orders always rank above limit orders. For the price
precedence, a more competitive price rule is. The display precedence takes the form
of lit or unlit preference, and the time precedence observes the time of arrival for
the orders.
The rule used by most exchanges is the price/display/time precedence rule to
determine the priority of execution. Specifically, the highest bids and lowest offers
always execute before lower bids and higher offers. Among equally priced orders,

40
Random documents with unrelated
content Scribd suggests to you:
The Project Gutenberg eBook of Armenia immolata
This ebook is for the use of anyone anywhere in the United States
and most other parts of the world at no cost and with almost no
restrictions whatsoever. You may copy it, give it away or re-use it
under the terms of the Project Gutenberg License included with this
ebook or online at www.gutenberg.org. If you are not located in the
United States, you will have to check the laws of the country where
you are located before using this eBook.

Title: Armenia immolata

Author: Edward Strieby Steele

Release date: May 4, 2016 [eBook #51998]


Most recently updated: October 23, 2024

Language: English

Credits: Produced by Charlene Taylor, Chuck Greif and the Online


Distributed Proofreading Team at http://www.pgdp.net
(This
file was produced from images generously made available
by The Internet Archive)

*** START OF THE PROJECT GUTENBERG EBOOK ARMENIA


IMMOLATA ***
Copyright. 1896, by Edward S. Steele.

Published by the author,


1522 Q Street, N. W., Washington, D. C.

ARMENIA IMMOLATA.
HYeONations
YE! Ho ye! all Europe, ho!
hear and patronize!
Unequalled realistic show
On the World stage we advertise!
Our repertoire will render flat
Your little operas and plays,
Your wagers of the ball and bat,
Your hunting rides, and all the craze
Of wheel and sail on land and main—
Yea, even tame the bulls of Spain!
Revival ours of classic sports,
Now with a brilliance to be seen
Which, should it reach the heavenly courts,
Would turn the eyes of Nero green!
To-day comes forth the Turkish beast,
Three days kept hungry in his den,
On the Armenian slave to feast,
Who meets him arm-ed with a pen!
Sure we shall win your approbation,—
There, France and Russia on the right—
The cost not a consideration;—
The Triple Friends shall have the sight
Here from the left, and in the center
Let Britain spread her cloth of gold!
All in between ye small folk enter—
America shall stand and scold!
Now all right merrily shall chime.
Ye knightly gentlemen, compose
Your little quarrels for the time;
Somewhat to reason each man owes,
And to the general happiness;
Your feuds shall suffer no abate
For an altruistical recess.
Now come ye all and come in state!
II.

Forthwith the powers and dignities


Proclaim a truce of God, and seek
Through all their ancient treasuries
A garb of pattern true antique.
Not easy sits the classic mode
Upon the tender modern frame,
And some do chafe beneath their load,
Some bear it with a look of shame.
Soon over all the games prevail,
Right well the beast doth play his part;
So doth the martyr, too—each wail
Sounds as it issued from the heart!
III.

Meanwhile out of that inner heat


That thrills anon the human kind
And rends the cold, incrusting sheet
Of stale traditions, lies enshrined,
Accords of jealous interest,
Hatreds of race, and bastard rights,
And every influence unblest
The bloom of human love that blights—
Out of the soul’s hot inner cell
Breaks forth implacable a curse,
The curse of him who loveth well—
Of all the curses none is worse.
IV.

Accurs-ed be all they that hate


Their brother, so to serve their God!
Soon had I cursed thy name, O Fate,
Had I not seen thee ready shod,
The besom in thy seasoned hand,
To sweep six centuries of the Turk
Out of a desecrated land!
Woe be to him who stays thy work!
Yea, woe unto the recreant tribe
That hath no legion for the Lord;
That for a warrior sends a scribe
To palter with a prodigal ward!
Where is your manhood, O ye States?
Ye Governments that govern down
All in the soul that elevates!
Ye hypocrites who, prudent, frown
On sympathy that warms the breast,
And boast you of the devilish grace,
Save in the name of interest
Ye meddle with your neighbors not!
Ten fleets to guard a gilded pot,
Not one to lift a bruised race!
V.

Time was when power of sentiment


Fired Europe with a frenzied zeal;
The stars out of their courses went
For what the Christian heart did feel.
Then babes with mail-ed knights did vie
To rescue from the Infidel
The place where once their Lord did lie,
A rended shroud, an empty shell.
Fanatics were they, minds distraught;
And yet meseems did body there
Some energy of noble thought,
Some prescience of a holy care
Of man for man, to be fulfilled
As man grows more and symbol less,
And sympathy no more is killed
By creed’s intolerable duress—
By the duress of creed and greed
And race and rank and worn-out codes.
Awake, O Man, and find thee freed!
Stand up from under thy brute loads!
Be thou thyself and claim descent
From the eternal Great and True!
Were but some dawning glimmer lent
Thy mind of what thou art and who,
Thy spirit with amaze should sink
And sit astonied one whole day,
Then from the vision new life drink,
And, casting its dead past away,
Rise in a glowing golden youth
To share the omnipotence of love,
The immortality of truth!
The quick ideal thy choice should move,
And not the fossiled precedent;
Reason set free should free the heart,
And with thy being’s full consent,
Thy powers no longer vainly spent,
Shouldst thou fulfill thy natal part!
VI.

In vain! in vain! I learned erewhile


Man rises not on high with wings,
But creeps the circuit of a mile
To rise a foot in spiritual things.
Even so, O Christian man! are still
Too few of tutoring leagues behind
To set thee on the little hill
Where common justice rules the mind,
Where plain humanity has sway—
Yea, even on some level higher,
Where pity doth her weeping stay,
And love offended lights a fire
That heateth judgment seven times hot
Against the bigot’s cruel ire,
Which love or reason toucheth not?
By Heaven! hast thou no heart as yet,
I’d think thy nerves would set thee wild
At sight of rapine without let,
Of slaughtered man and maid defiled,
Of homeless mother, starving child,
And of a patriotic race
Crushed in its ancient dwelling place!
VII.

In one regard I plainly see


Thou hast betimes great progress made;
Religious prejudice for thee
Hath in its sepulcher been laid.
It grieves thee not that they who praise
A prophet whom thou countest none,
Afflict a land, from ancient days
Holding the faith which is thine own.
But pride thee not in progress such;
It is the progress of disease,
That holds thee in its numbing clutch
And soon thy vital parts shall freeze.
If thou wert truly tolerant
Thy blood within thy veins would boil
That creed, the worst or best, should plant
Its foot on an unwilling soil.
It is not breadth but policy
That holdeth back the avenging hand;
Of all the Turks the worst is he
Of Christian name in Christian land.
VIII.

O Europe! O America!
If ye but knew this fatal day!
If ye could read the eternal law
Now at the parting of the way!
If ye, beholding thus distressed
This pilgrim, leave him here to die,
Ye are his murderers confessed,
The guilt upon your souls will lie.
T’will follow you through many a year,
Corrupting the sweet tides of life,
Now in insidious blight appear,
And now break forth in horrid strife.
T’will nullify religion’s claims,
T’will mar your literature and art;
T’will choke society’s best aims,
To greed new energy impart.
Nor even so shall ye evade
The dreaded specter of the East;
Until by right or ruin laid
It shall intrude into your feast.
But if ye do the deed of men
And save your brother here half-killed,
Then shall ye be as born again,
Your life with upward impulse filled.
Your better selves once shaken free
Will loath submit to other chains;
And from your deed of charity,
Your own shall be the larger gains.
IX.

O friends of peace, dear brethren mine,


Me of your inner circle name,
Unless the peace which you design
With anarchy is one and same.
It is not war but government
When justice wields the avenging sword;
And force in name of justice spent
Is oil on troubled waters poured.
Where reason is let reason rule,
And law where men submit to laws;
But with the cutthroat ’tis a fool
Attempts to arbitrate his cause.
Nor ends responsibility
Within the nation’s narrow close;
The world is one community,
Each state to all allegiance owes.
And who hath power and doth neglect
To rescue from the oppressor’s hand
The wronged of any race or sect
In Christian or in pagan land—
Who hath the power and lends not aid
Doth sin against the primal right,
Which man not Turk nor Frank hath made
But citizen cosmopolite!
X.
What doeth the Turk in power still
As ends the nineteenth century?
Lacks aught of shame his cup to fill
Of unassuaged iniquity?
Lacks aught of cruelty and blood?
Lacks aught of treachery and lies?
Lacks aught of crime ’gainst womanhood?
Lacks mad fanaticism that plies
All villainies in Allah’s name?
And what redeeming deed or trait
Stands out to mitigate this blame?
On what kind thought does Justice wait?
What seeds of omen good may hide
Deep in the Turkish breast, God knows;
Scarce will they spring while rampant pride
Yields ever fresh return of woes.
Meanwhile thy lightsome hopes to plead,
The cause of justice to defer,
Makes thee a partner well agreed
In the ensuing massacre.
Nor will thy pennyworth of food,
Dispensed with ne’er so pitying dole,
The ruin of a race make good,
Or take the curse from off thy soul.
Master, I pray thee look upon
This vexed youth, my only son;
Behold, a spirit taketh him
And suddenly he crieth out;
It bruiseth every manly limb
And ceaseless harrieth him about—
Now flingeth him into the fire,
Now dasheth him upon the earth;
And plagued with these afflictions dire,
’Twere better he had wanted birth.
And thy disciples did I ask
To cast this grievous demon out;
They could not do so hard a task,
And left our minds of thee in doubt.
But now, canst thou do anything,
Let thy compassion lead thee on;
Have pity and deliverance bring
To this my torn and pining son!
*** END OF THE PROJECT GUTENBERG EBOOK ARMENIA
IMMOLATA ***

Updated editions will replace the previous one—the old editions will
be renamed.

Creating the works from print editions not protected by U.S.


copyright law means that no one owns a United States copyright in
these works, so the Foundation (and you!) can copy and distribute it
in the United States without permission and without paying
copyright royalties. Special rules, set forth in the General Terms of
Use part of this license, apply to copying and distributing Project
Gutenberg™ electronic works to protect the PROJECT GUTENBERG™
concept and trademark. Project Gutenberg is a registered trademark,
and may not be used if you charge for an eBook, except by following
the terms of the trademark license, including paying royalties for use
of the Project Gutenberg trademark. If you do not charge anything
for copies of this eBook, complying with the trademark license is
very easy. You may use this eBook for nearly any purpose such as
creation of derivative works, reports, performances and research.
Project Gutenberg eBooks may be modified and printed and given
away—you may do practically ANYTHING in the United States with
eBooks not protected by U.S. copyright law. Redistribution is subject
to the trademark license, especially commercial redistribution.

START: FULL LICENSE


THE FULL PROJECT GUTENBERG LICENSE
PLEASE READ THIS BEFORE YOU DISTRIBUTE OR USE THIS WORK

To protect the Project Gutenberg™ mission of promoting the free


distribution of electronic works, by using or distributing this work (or
any other work associated in any way with the phrase “Project
Gutenberg”), you agree to comply with all the terms of the Full
Project Gutenberg™ License available with this file or online at
www.gutenberg.org/license.

Section 1. General Terms of Use and


Redistributing Project Gutenberg™
electronic works
1.A. By reading or using any part of this Project Gutenberg™
electronic work, you indicate that you have read, understand, agree
to and accept all the terms of this license and intellectual property
(trademark/copyright) agreement. If you do not agree to abide by all
the terms of this agreement, you must cease using and return or
destroy all copies of Project Gutenberg™ electronic works in your
possession. If you paid a fee for obtaining a copy of or access to a
Project Gutenberg™ electronic work and you do not agree to be
bound by the terms of this agreement, you may obtain a refund
from the person or entity to whom you paid the fee as set forth in
paragraph 1.E.8.

1.B. “Project Gutenberg” is a registered trademark. It may only be


used on or associated in any way with an electronic work by people
who agree to be bound by the terms of this agreement. There are a
few things that you can do with most Project Gutenberg™ electronic
works even without complying with the full terms of this agreement.
See paragraph 1.C below. There are a lot of things you can do with
Project Gutenberg™ electronic works if you follow the terms of this
agreement and help preserve free future access to Project
Gutenberg™ electronic works. See paragraph 1.E below.
1.C. The Project Gutenberg Literary Archive Foundation (“the
Foundation” or PGLAF), owns a compilation copyright in the
collection of Project Gutenberg™ electronic works. Nearly all the
individual works in the collection are in the public domain in the
United States. If an individual work is unprotected by copyright law
in the United States and you are located in the United States, we do
not claim a right to prevent you from copying, distributing,
performing, displaying or creating derivative works based on the
work as long as all references to Project Gutenberg are removed. Of
course, we hope that you will support the Project Gutenberg™
mission of promoting free access to electronic works by freely
sharing Project Gutenberg™ works in compliance with the terms of
this agreement for keeping the Project Gutenberg™ name associated
with the work. You can easily comply with the terms of this
agreement by keeping this work in the same format with its attached
full Project Gutenberg™ License when you share it without charge
with others.

1.D. The copyright laws of the place where you are located also
govern what you can do with this work. Copyright laws in most
countries are in a constant state of change. If you are outside the
United States, check the laws of your country in addition to the
terms of this agreement before downloading, copying, displaying,
performing, distributing or creating derivative works based on this
work or any other Project Gutenberg™ work. The Foundation makes
no representations concerning the copyright status of any work in
any country other than the United States.

1.E. Unless you have removed all references to Project Gutenberg:

1.E.1. The following sentence, with active links to, or other


immediate access to, the full Project Gutenberg™ License must
appear prominently whenever any copy of a Project Gutenberg™
work (any work on which the phrase “Project Gutenberg” appears,
or with which the phrase “Project Gutenberg” is associated) is
accessed, displayed, performed, viewed, copied or distributed:
This eBook is for the use of anyone anywhere in the United
States and most other parts of the world at no cost and with
almost no restrictions whatsoever. You may copy it, give it away
or re-use it under the terms of the Project Gutenberg License
included with this eBook or online at www.gutenberg.org. If you
are not located in the United States, you will have to check the
laws of the country where you are located before using this
eBook.

1.E.2. If an individual Project Gutenberg™ electronic work is derived


from texts not protected by U.S. copyright law (does not contain a
notice indicating that it is posted with permission of the copyright
holder), the work can be copied and distributed to anyone in the
United States without paying any fees or charges. If you are
redistributing or providing access to a work with the phrase “Project
Gutenberg” associated with or appearing on the work, you must
comply either with the requirements of paragraphs 1.E.1 through
1.E.7 or obtain permission for the use of the work and the Project
Gutenberg™ trademark as set forth in paragraphs 1.E.8 or 1.E.9.

1.E.3. If an individual Project Gutenberg™ electronic work is posted


with the permission of the copyright holder, your use and distribution
must comply with both paragraphs 1.E.1 through 1.E.7 and any
additional terms imposed by the copyright holder. Additional terms
will be linked to the Project Gutenberg™ License for all works posted
with the permission of the copyright holder found at the beginning
of this work.

1.E.4. Do not unlink or detach or remove the full Project


Gutenberg™ License terms from this work, or any files containing a
part of this work or any other work associated with Project
Gutenberg™.

1.E.5. Do not copy, display, perform, distribute or redistribute this


electronic work, or any part of this electronic work, without
prominently displaying the sentence set forth in paragraph 1.E.1
with active links or immediate access to the full terms of the Project
Gutenberg™ License.

1.E.6. You may convert to and distribute this work in any binary,
compressed, marked up, nonproprietary or proprietary form,
including any word processing or hypertext form. However, if you
provide access to or distribute copies of a Project Gutenberg™ work
in a format other than “Plain Vanilla ASCII” or other format used in
the official version posted on the official Project Gutenberg™ website
(www.gutenberg.org), you must, at no additional cost, fee or
expense to the user, provide a copy, a means of exporting a copy, or
a means of obtaining a copy upon request, of the work in its original
“Plain Vanilla ASCII” or other form. Any alternate format must
include the full Project Gutenberg™ License as specified in
paragraph 1.E.1.

1.E.7. Do not charge a fee for access to, viewing, displaying,


performing, copying or distributing any Project Gutenberg™ works
unless you comply with paragraph 1.E.8 or 1.E.9.

1.E.8. You may charge a reasonable fee for copies of or providing


access to or distributing Project Gutenberg™ electronic works
provided that:

• You pay a royalty fee of 20% of the gross profits you derive
from the use of Project Gutenberg™ works calculated using the
method you already use to calculate your applicable taxes. The
fee is owed to the owner of the Project Gutenberg™ trademark,
but he has agreed to donate royalties under this paragraph to
the Project Gutenberg Literary Archive Foundation. Royalty
payments must be paid within 60 days following each date on
which you prepare (or are legally required to prepare) your
periodic tax returns. Royalty payments should be clearly marked
as such and sent to the Project Gutenberg Literary Archive
Foundation at the address specified in Section 4, “Information
about donations to the Project Gutenberg Literary Archive
Foundation.”

• You provide a full refund of any money paid by a user who


notifies you in writing (or by e-mail) within 30 days of receipt
that s/he does not agree to the terms of the full Project
Gutenberg™ License. You must require such a user to return or
destroy all copies of the works possessed in a physical medium
and discontinue all use of and all access to other copies of
Project Gutenberg™ works.

• You provide, in accordance with paragraph 1.F.3, a full refund of


any money paid for a work or a replacement copy, if a defect in
the electronic work is discovered and reported to you within 90
days of receipt of the work.

• You comply with all other terms of this agreement for free
distribution of Project Gutenberg™ works.

1.E.9. If you wish to charge a fee or distribute a Project Gutenberg™


electronic work or group of works on different terms than are set
forth in this agreement, you must obtain permission in writing from
the Project Gutenberg Literary Archive Foundation, the manager of
the Project Gutenberg™ trademark. Contact the Foundation as set
forth in Section 3 below.

1.F.

1.F.1. Project Gutenberg volunteers and employees expend


considerable effort to identify, do copyright research on, transcribe
and proofread works not protected by U.S. copyright law in creating
the Project Gutenberg™ collection. Despite these efforts, Project
Gutenberg™ electronic works, and the medium on which they may
be stored, may contain “Defects,” such as, but not limited to,
incomplete, inaccurate or corrupt data, transcription errors, a
copyright or other intellectual property infringement, a defective or
damaged disk or other medium, a computer virus, or computer
codes that damage or cannot be read by your equipment.

1.F.2. LIMITED WARRANTY, DISCLAIMER OF DAMAGES - Except for


the “Right of Replacement or Refund” described in paragraph 1.F.3,
the Project Gutenberg Literary Archive Foundation, the owner of the
Project Gutenberg™ trademark, and any other party distributing a
Project Gutenberg™ electronic work under this agreement, disclaim
all liability to you for damages, costs and expenses, including legal
fees. YOU AGREE THAT YOU HAVE NO REMEDIES FOR
NEGLIGENCE, STRICT LIABILITY, BREACH OF WARRANTY OR
BREACH OF CONTRACT EXCEPT THOSE PROVIDED IN PARAGRAPH
1.F.3. YOU AGREE THAT THE FOUNDATION, THE TRADEMARK
OWNER, AND ANY DISTRIBUTOR UNDER THIS AGREEMENT WILL
NOT BE LIABLE TO YOU FOR ACTUAL, DIRECT, INDIRECT,
CONSEQUENTIAL, PUNITIVE OR INCIDENTAL DAMAGES EVEN IF
YOU GIVE NOTICE OF THE POSSIBILITY OF SUCH DAMAGE.

1.F.3. LIMITED RIGHT OF REPLACEMENT OR REFUND - If you


discover a defect in this electronic work within 90 days of receiving
it, you can receive a refund of the money (if any) you paid for it by
sending a written explanation to the person you received the work
from. If you received the work on a physical medium, you must
return the medium with your written explanation. The person or
entity that provided you with the defective work may elect to provide
a replacement copy in lieu of a refund. If you received the work
electronically, the person or entity providing it to you may choose to
give you a second opportunity to receive the work electronically in
lieu of a refund. If the second copy is also defective, you may
demand a refund in writing without further opportunities to fix the
problem.

1.F.4. Except for the limited right of replacement or refund set forth
in paragraph 1.F.3, this work is provided to you ‘AS-IS’, WITH NO
OTHER WARRANTIES OF ANY KIND, EXPRESS OR IMPLIED,
Welcome to our website – the perfect destination for book lovers and
knowledge seekers. We believe that every book holds a new world,
offering opportunities for learning, discovery, and personal growth.
That’s why we are dedicated to bringing you a diverse collection of
books, ranging from classic literature and specialized publications to
self-development guides and children's books.

More than just a book-buying platform, we strive to be a bridge


connecting you with timeless cultural and intellectual values. With an
elegant, user-friendly interface and a smart search system, you can
quickly find the books that best suit your interests. Additionally,
our special promotions and home delivery services help you save time
and fully enjoy the joy of reading.

Join us on a journey of knowledge exploration, passion nurturing, and


personal growth every day!

ebookbell.com

You might also like