100% found this document useful (6 votes)
331 views

Full Download Quantitative Trading Strategies Using Python: Technical Analysis, Statistical Testing, and Machine Learning Peng Liu PDF DOCX

Trading

Uploaded by

preabmisiti
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (6 votes)
331 views

Full Download Quantitative Trading Strategies Using Python: Technical Analysis, Statistical Testing, and Machine Learning Peng Liu PDF DOCX

Trading

Uploaded by

preabmisiti
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 66

Download Full Version ebookmass - Visit ebookmass.

com

Quantitative Trading Strategies Using Python:


Technical Analysis, Statistical Testing, and
Machine Learning Peng Liu

https://ebookmass.com/product/quantitative-trading-
strategies-using-python-technical-analysis-statistical-
testing-and-machine-learning-peng-liu/

OR CLICK HERE

DOWLOAD NOW

Discover More Ebook - Explore Now at ebookmass.com


Instant digital products (PDF, ePub, MOBI) ready for you
Download now and discover formats that fit your needs...

Machine Learning Guide for Oil and Gas Using Python Hoss
Belyadi

https://ebookmass.com/product/machine-learning-guide-for-oil-and-gas-
using-python-hoss-belyadi/

ebookmass.com

Machine Learning on Geographical Data Using Python 1st


Edition Joos Korstanje

https://ebookmass.com/product/machine-learning-on-geographical-data-
using-python-1st-edition-joos-korstanje/

ebookmass.com

Bayesian Optimization : Theory and Practice Using Python


Peng Liu

https://ebookmass.com/product/bayesian-optimization-theory-and-
practice-using-python-peng-liu/

ebookmass.com

Assembling life : how can life begin on earth and other


habitable planets? David W. Deamer

https://ebookmass.com/product/assembling-life-how-can-life-begin-on-
earth-and-other-habitable-planets-david-w-deamer/

ebookmass.com
Witch Please Ann Aguirre

https://ebookmass.com/product/witch-please-ann-aguirre-2/

ebookmass.com

Essentials of Human Anatomy & Physiology [Global Edition]


Elaine N. Marieb

https://ebookmass.com/product/essentials-of-human-anatomy-physiology-
global-edition-elaine-n-marieb/

ebookmass.com

Kinesthetic Spectatorship in the Theatre: Phenomenology,


Cognition, Movement 1st ed. Edition Stanton B. Garner

https://ebookmass.com/product/kinesthetic-spectatorship-in-the-
theatre-phenomenology-cognition-movement-1st-ed-edition-stanton-b-
garner/
ebookmass.com

The John Doe $5 Million Dollar Donation Campaign Drive The


Fundraiser’S Paradox

https://ebookmass.com/product/the-john-doe-5-million-dollar-donation-
campaign-drive-the-fundraisers-paradox/

ebookmass.com

Foundations of European Politics Catherine E. De Vries &


Sara B. Hobolt & Sven-Oliver Proksch & Jonathan B. Slapin

https://ebookmass.com/product/foundations-of-european-politics-
catherine-e-de-vries-sara-b-hobolt-sven-oliver-proksch-jonathan-b-
slapin/
ebookmass.com
Sensors and Protocols for Industry 4.0: Industrial
Applications of Maker Tech 1st Edition
G.R. Kanagachidambaresan
https://ebookmass.com/product/sensors-and-protocols-for-
industry-4-0-industrial-applications-of-maker-tech-1st-edition-g-r-
kanagachidambaresan/
ebookmass.com
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
Random documents with unrelated
content Scribd suggests to you:
of the system was the clan, the members of which, forming a close
brotherhood, were bound to their lord by ties of affection and fidelity
like those which in Europe theoretically bound the retainer to his
193
lord. This system exerted a great influence upon the moral type. It
developed a martial ideal of character known as Bushido, many of
the virtues of which are almost identical with corresponding virtues in
the European ideal of chivalry. Probably this system has had more to
do with creating in Japan a moral consciousness in many respects
like our own than has any other single agency. To the lack in the
Chinese social system of any institution like Japanese feudalism
may be ascribed in part at least the wide difference which exists
between the moral ideals of the two peoples, especially in regard to
the rank assigned the military virtues.

Confucianism Along with the Chinese classics Confucianism was


introduced into Japan about the middle of the sixth century of our
era, and being in perfect accord with the native system of Shinto and
with the Japanese ways of thinking, this cult of ancestors tended to
reënforce native ethical tendencies and thus contributed essentially
to make the virtues of filial obedience and reverence for superiors
prominent in the growing type of character.

Buddhism Buddhism was introduced into Japan in the sixth


century of our era. Its incoming had deep import for the moral life of
the Japanese people. It inculcated the gentler virtues, exerting here
in this respect, as elsewhere in the Far East,—save in China, where
it too quickly became shockingly degenerate,—an influence like that
exerted by Christianity in the Western world. It helped to make
gentleness, courtesy, and tenderness distinctive traits of the
Japanese character. Through the regard which it instilled for dumb
animals it placed the whole lower world of animal life under the
194
protection of the moral sentiment.

Western A little more than a generation ago the civilization of


civilization
Japan came into vital contact with the civilization of
the West. Almost every element of the old Japanese culture has felt
the modifying effect of this contact. The political, the economic, the
social, the domestic, and the religious institutions have undergone or
are undergoing great changes. These changes in these departments
of life and thought have caused, as such changes always do,
important modifications in ethical sentiments and convictions. Of all
the influences which for more than two thousand years have been at
work shaping and molding the moral ideal of the Japanese nation,
those now entering from the Occidental world will doubtless leave
the deepest impress upon the ethical type.
In a still more direct way is this contact of Japan with Western
civilization resulting in important consequences for Japanese
morality. Christian ethics, like Buddhist ethics, is making a strong
appeal to certain classes of Japanese society. The result is what in
an earlier chapter was designated as a “mingling of moralities” and
the creation of a new composite conscience.

II. The Ideal

Bushido The heart of Japanese morality is to be sought in


195
Bushido, the ethics of the samurai. We shall best
understand this moral code by thinking of it as the Japanese ideal of
chivalry or, perhaps better, as a blending of the Western chivalric,
Spartan, and Stoic ideals of goodness and nobility, since in the list of
virtues making up the Bushido ideal we find several of the cardinal
virtues entering into each of these three distinct types of character.
As we have already intimated, Bushido is an ideal of excellence
which grew up out of the root of Japanese feudalism, just as the
Western ideal of chivalry developed out of European feudalism. It
was essentially an ideal of knighthood, the prime virtue of which was
personal loyalty to one’s superior. Fealty to one’s chief was made so
dominant a virtue that it overshadowed all other virtues. In the
defense or in the service of his lord a samurai might commit, without
offense to his sense of moral right, practically any crime, such as
blackmailing, lying, treachery, or even murder.
Grouped about this cardinal virtue of loyalty were the other
knightly virtues of courage, fidelity to the plighted word, liberality,
self-sacrifice, gratitude, courtesy, and benevolence. Liberality, or
free-handedness, was carried to such an extreme as to become a
defect of character. The true samurai must have no thought of
economy and money-making. “Ignorance of the value of different
196
coins was a token of good breeding.” To handle money was
thought degrading.
In one respect the code of honor of the Japanese knight was
wholly unlike that of the Western knight. It did not include any special
duty to woman. “Neither God nor the ladies inspired any enthusiasm
in the samurai’s breast.”
The Spartan element in the samurai code appears particularly in
the training of the youth. The boy was taught always to act from
motives of duty. He was denied every comfort. His clothing and his
diet were coarse. He was allowed no fire in the winter. “If his feet
were numbed by frost, he would be told to run about in the snow to
make them warm.” To accustom him to the sight of blood, he was
taken to see the execution of criminals; and to banish foolish fear
from his mind, he was forced to visit alone at night the place of
197
execution.
The Stoic element in the ideal appears in the high place assigned
to the virtue of self-control. The samurai, like the Stoic, must
suppress all signs of his emotions. Like the Stoic, too, he must have
courage to live or courage to die, as enjoined by duty. And his code
of honor taught him what true courage is: “It is true courage to live
198
when it is right to live, and to die only when it is right to die.”
This samurai ideal of character constitutes, as we shall see, a
molding force in the moral life of Japan. Bushido, it is true, died with
199
the passing of feudalism, but the spirit of Bushido lived on. The
samurai’s sense of honor and of duty became the inheritance of the
Japanese people. This great bequest of honor and valor and of all
samurai virtues is, in the words of the author of the Soul of Japan,
but “a trust to the nation, and the summons of the present is to guard
this heritage, nor to bate one jot of the ancient spirit; the summons of
the future will be so to widen its scope as to apply it in all walks and
200
relations of life.”

The virtue of The belief in the divine origin of the imperial house
loyalty to the
Emperor, or
of Japan makes loyalty to the Emperor the supreme
patriotism 201
duty. During the ascendancy of feudalism this duty,
in so far as the samurai class was concerned, was, it is true,
overshadowed by the duty of loyalty to one’s immediate feudal
superior. The sentiment due the Emperor was intercepted by the
daimyos. But in theory loyalty to the imperial house has ever been
the paramount virtue of the Japanese. The Emperor’s command is to
his subjects as the command of God to us, and obedience must be
perfect and unquestioning. So dominant is the place assigned this
virtue of loyalty to the head of the nation that the Japanese moralist
seems almost to make morality consist in this single virtue, as if “to
fear the Emperor and to keep his commandments” were the full duty
202
of man.
This sentiment of the people toward the imperial family renders
the government a sort of theocracy. Hence patriotism with the
Japanese is in large measure a religious feeling. Indeed, patriotism
has been called the religion of the Japanese. It is this virtue, exalted
to a degree which the world has never seen surpassed, which has
contributed more than any other quality of the Japanese character to
make Japan a great nation and to give her the victory over a
powerful foe in one of the most gigantic wars of modern times.

Family ethics If the first duty of the Japanese is to his Emperor,


his second is to his parents. In Japanese phrase, the two virtues of
loyalty and filial piety are “the two wheels of the chariot of Japanese
203
ethics.” Shinto and Confucianism, as we have seen, have both
contributed to the fostering in children of the moral sentiments of
grateful love, reverence, and obedience toward parents and all
ancestors living and dead. The Japanese regard the high place
assigned to these filial duties in the standard of character as a mark
204
of the vast superiority of their morality to ours. The sentiments of
filial affection and reverence, coloring as they do the whole moral
life, lend to Japanese society an ethical cast which places it in many
respects in strong contrast to the social order of the Western nations,
and makes it difficult for the Japanese to understand us and for us to
205
understand them.

Woman as wife As respects the position of woman the family ethics


and as mother
of Japan are the family ethics of the East. In a work
from every page of which breathes the spirit of the Orient, a
Japanese writer, dwelling upon the difference between the ethical
sentiments respecting family relationships which have been evoked
by the different social environments of the East and the West, says:
“In the East woman has always been worshiped as the mother, and
all those honors which the Christian knight brought in homage to his
206
ladylove, the samurai laid at his mother’s feet.”
Lafcadio Hearn, touching upon this same feature of the family
ethics of the Japanese, declares that the Bible text, “For this cause
shall a man leave his father and mother and shall cleave unto his
wife,” is, to their way of thinking and feeling, “one of the most
207
immoral sentences ever written.”
In another important respect does the domestic morality of the
Japanese differ essentially from that of the Christian West. The
family is not strictly monogamous, as with us. The moral sense of the
208
Japanese discerns nothing wrong in polygamy or concubinage.
As respects the whole relation of marriage, the Japanese appear to
be in about the same stage of evolution as had been reached by the
Hebrews at the time of Abraham.
A chief virtue of the Japanese women in all their relations is
obedience to the one—whether father, or husband, or son—to whom
obedience is due. It is the setting of this duty before all other duties
that causes the Japanese women sometimes to do what appears to
us immoral, but which seems to them truest piety and noblest self-
209
sacrifice. In loyalty to duty, as they interpret duty, they maintain a
210
standard rarely surpassed by the women of any land.

Suicide Suicide is infrequent among savage and barbarian


regarded as a
virtuous act
races, but is common among all peoples in an
advanced stage of civilization. It is not so much the
fact itself of self-destruction that claims the attention of the historian
of morals, as the light in which the act is viewed; that is, whether it is
considered a virtuous or a reprehensible deed.
Now the Japanese regard suicide, if prompted by a good motive,
as a justifiable and noble act. The motives with them for the deed are
various, as in the case of other peoples, but among these motives is
one which discloses the existence among the Japanese of a
sentiment unknown or almost unknown among ourselves. The deed
is often committed in the way of making a solemn protest against
something disapproved of in the conduct or acts of others. Thus
when the Japanese government after war with China in 1898
acceded to the demands of Russia, France, and Germany
respecting the recession to China of certain territories on the
Continent, forty men in the Japanese army, by way of protest,
211
committed suicide “in the ancient way.”
Tyrannicide is also looked upon by the Japanese as an heroic and
praiseworthy deed, provided the person committing the act makes
clear the self-sacrificing and patriotic character of his motives by at
once taking his own life.

Low estimation A marked defect of the moral standard of the


of the virtue of
truthfulness
Japanese is the low place assigned to the virtue of
truthfulness. Among the Japanese, to call a person a
liar is not to apply to him a term of reproach, but rather to pay him a
pleasant compliment as a person of tact and shrewdness.
This lack of reverence for truth probably springs in part from the
virtue of politeness as a root. The extreme emphasis laid upon
courtesy as the sign and expression of reverence and loyalty toward
superiors fosters the general habit of saying things which are
pleasant and agreeable whether they are true or not. This
complacent disregard of truth in social intercourse would seem to
have dulled the sense of obligation of truth-speaking in other
relations.

III. Some Significant Facts in the Moral


History of Japan

General The Japanese knightly ideal, which, as we have


influence of the
said, constitutes the heart and core of theoretical
ideal of Bushido
Japanese morality, has a history somewhat like that of
the ideal of European knighthood. It was a lofty ideal very imperfectly
realized, yet realized to such a degree as to make it a chief motive
212
force in the political and social life of Japan for several centuries.
It left a permanent impress upon the moral consciousness of the
Japanese nation, an impress certainly deeper and more enduring
than that left by the ideal of European chivalry upon the moral
consciousness of the peoples of Western Europe. New Japan is
directly or indirectly the creation of Japanese knighthood.
We have seen that loyalty to his chief was the preëminent virtue
of the samurai. Upon the downfall of feudalism this loyalty was
transferred to the Emperor. The spirit of the samurai came to inspire
the Japanese nation. Since the time when the loyalty of Scottish
clansmen to their chief was transferred to Scottish royalty, there has
not been seen a more remarkable example of the absolute devotion
of a people to their sovereign than that exhibited to-day by the
people of Japan.
The samurai were taught to despise the love of gain, and thus
these knights of Japan were strangers to those vices which spring
from the love of money. To this circumstance may be ascribed the
fact that the statesmen of Japan, who almost invariably are of the
samurai class, have been so notably free from venality and
213
corruption.
Finally, Bushido held aloft a high standard of truthfulness. The
true samurai regarded an oath as a derogation of his honor. It cannot
be affirmed that this Bushido virtue of veracity has yet become the
inheritance of the mercantile and peasant classes of Japan, but it
has at least been retained by the samurai as a class, and is working
to-day like leaven in the mass of Japanese society.

The Bushido There are two remarkable passages in recent


code in action
Japanese history which well illustrate in what way and
to what degree the spirit of the samurai, “the spirit of not living unto
one’s self,” has become an inspiration to the whole Japanese nation.
The first passage has to do with the Russo-Japanese War of 1904–
1905, which on the part of Japan was a struggle for national
existence. It was the samurai morality, a morality of loyalty, of valor,
of selflessness, of fidelity to duty, that formed a chief element of the
strength of Japan in that critical juncture of the nation’s life. The
Bushido code of honor showed itself equal to the Spartan code in
creating a race of invincible warriors. Since the Spartan Leonidas
and his companions died for Greece in the pass of Thermopylæ
there has been no sublimer exhibition of fortitude and self-devotion
in a great cause than that shown by Japanese soldiers in the
trenches before Port Arthur and on the battlefields of Manchuria.
This war for national independence also afforded proof of how the
gentle virtue of Japanese knighthood, courteous generosity to the
vanquished, has passed as a noble legacy to the nation at large; for
as an eminent Japanese statesman affirms, “In the tender care
bestowed upon our stricken adversary of the battlefield will be found
214
the ancient courtesy of the samurai.”
The second passage shows the morality of the
The moral samurai in competition with the morality of the
standard of the common Japanese shopman. Now the morality of the
samurai in
competition with
plebeian Japanese trader is about on a level with that
that of the 215
plebeian trader
of the ancient Greek shopkeeper. And a chief
cause of his low moral standard is the same, namely,
the general disesteem in which the trader’s business has been held.
This social stigma has resulted in the mercantile business being left
in the hands of the lowest class socially, intellectually, and
216
morally. The great mass of the people have from time immemorial
been engaged in the honorable business of agriculture; while the
samurai class, as we have seen, regarded it as degrading to engage
in trade or even to handle money. In these circumstances it was
inevitable that the mercantile class should evolve a very low code of
business ethics; for, as the author of Bushido very justly observes,
“put a stigma on a calling and its followers adjust their morals to it.”
The strictly class character of this loose commercial morality is
shown by the experience of the samurai after the abolition of
feudalism in 1868. Upon that event many of them engaged in
mercantile business, carrying with them their high moral standard,
with results pathetically depicted by Nitobé in these words: “Those
who had eyes to see could not weep enough, those who had hearts
to feel could not sympathize enough, with the fate of many a noble
and honest samurai who signally and irrevocably failed in his new
and unfamiliar field of trade and industry, through sheer lack of
shrewdness in coping with his artful plebeian rival.... It will be long
before it will be recognized how many fortunes were wrecked in the
attempt to apply Bushido ethics to business methods, but it was
soon apparent to every observing mind that the ways of wealth were
217
not the ways of honor.” About ninety-nine out of every hundred
samurai who ventured into business are said to have failed.
This passage out of the history of New Japan carries with it
various lessons, but particularly does it teach how unjust it is to
218
judge the morality of a people by the morality of a class.
Notwithstanding the disastrous outcome of their first venture into
the mercantile field, the samurai still remain in business, so that
there is going on to-day in Japan in the commercial domain a
competition between two moral standards. The triumph of the
standard of the samurai over that of the plebeian trader would mean
the development in Japan of a matchless business morality, which,
in the increasing closeness of commercial relations between the
East and the West, might well act cleansingly on our own business
219
ethics.

Moral education The rapid transformation in the institutions and


in the schools;
the Imperial
ideas of Old Japan after the revolution of 1868 created
Rescript a crisis in the moral life of the Japanese people. The
old basis of the national morality was destroyed.
Reverence for the Confucian teachings was lost. Respect for
ancestral customs was seriously impaired. Moral anarchy impended.
In this critical juncture some proposed that Buddhism, others that
Christianity, should be made the basis of the moral code.
Especially in the schools was the urgency of the need of some
new sanction for morality felt, because moral instruction and training
have always formed an essential part of the education of the youth of
Japan. The Japanese have ever believed that it is possible to mold
the character of the nation by education. “With us,” says a native
writer, “education has meant moral education more than anything
220
else for centuries.” “The object of teaching,” says the official
regulations for teaching in elementary schools, “is to cultivate the
moral nature of children and to guide them in the practice of
221
virtues.” Because of this central place assigned moral education
in the work of the schools, the necessity for removing all uncertainty
as to what should be inculcated was all the more exigent.
To meet the crisis the following imperial rescript was issued—
certainly one of the most remarkable state papers ever promulgated:

“Know ye, our subjects:


“Our imperial ancestors have founded our Empire on a basis
broad and everlasting and have deeply and firmly implanted
virtue; our subjects, ever united in loyalty and filial piety, have
from generation to generation illustrated the beauty thereof. This
is the glory and the fundamental character of our Empire, and
herein also lies the source of our education. Ye, our subjects, be
filial to your parents, affectionate to your brothers and sisters; as
husbands and wives be harmonious; as friends true; bear
yourselves in modesty and moderation; extend your
benevolence to all; pursue learning and cultivate arts, and
thereby develop intellectual faculties and perfect moral powers;
furthermore, advance public good and promote common
interests; always respect the Constitution and observe the laws;
should emergency arise, offer yourselves courageously to the
state; and thus guard and maintain the prosperity of our imperial
throne coeval with heaven and earth. So shall ye not only be our
good and faithful subjects, but render illustrious the best
traditions of your forefathers.
“The way here set forth is indeed the teaching bequeathed by
our imperial ancestors, to be observed alike by their
descendants and the subjects, infallible for all ages and true in
all places. It is our wish to lay it to heart in all reverence, in
common with you, our subjects, that we may all thus attain to the
same virtue.
“The 30th day of the 10th month of the 23d year of Meiji”
222
[1890].

It would be almost impossible to exaggerate the influence of this


imperial edict. “Our whole moral education,” affirms Baron Kikuchi,
“consists in instilling into the minds of our children the proper
223
appreciation of the spirit of this rescript.” The children learn it by
heart just as the Roman children committed to memory the Twelve
Tables of the laws.
Japanese believe that the effect of this instruction upon the
national character, reënforcing the ancestral virtues of loyalty and
224
devotion to duty, was exhibited in the recent war with Russia.
A noteworthy feature of the rescript is that it is simply a
reaffirmation of the teachings of the ancient moralists and the ethical
traditions of the fathers—an inculcation of those virtues of loyalty and
filial piety which the Japanese people have held in esteem and
practiced from generation to generation.
A second feature of the edict which arrests attention is the
universalistic and secular character of the morality inculcated. The
virtues enjoined are universal benevolence, loyalty to duty, and self-
devotion to the common good—a morality of the universal human
heart and conscience, a morality, as the edict declares, good for all
ages and for all places.

Japanese The foregoing anticipates and gives answer to the


morals and
Western
questions: What will be the effect upon Japanese
civilization morality of those changes now going on in the life and
thought of Japan through contact with the civilization
of the West? What will be the effect upon Japanese public morality
when the common belief in the divine descent of the Emperor, which
is the root from which springs the primal duty of loyalty, is
undermined, as modern science is certain to undermine it? What will
be the effect upon Japanese domestic morality when Occidental
conceptions of the family and of woman’s place in it come to modify,
as they seem likely to do, those ideas and sentiments which from
time immemorial have formed the basis of the family ethics of the
East? What will be the ethical consequences when Western science
renders obsolete the Shinto learning and the Confucian classics,
which have hitherto formed the basis of so large a part of Japanese
morality? What will be the effect upon the ancient ideal of character
of the adoption of Christian ideas and teachings in place of those
which have so long nourished the ethical feelings and sentiments of
the Japanese people?
That the intrusion into the ancient culture of Japan of these
various elements of Western civilization has deep import for
Japanese morality cannot be made a matter of doubt. In the new
environment, so different from that in the midst of which the ancient
ideal of goodness was developed, this ideal must inevitably undergo
important changes. Some of those qualities of character which have
so long held high places in the ideal of excellence will cease to
evoke the old-time homage, while other qualities at present assigned
low places in the standard will be exalted. Virtues now practically
unrecognized by the Japanese as virtues, but which among us are
highly esteemed moral qualities, will certainly be incorporated in the
modified ideal, giving it a new cast, yet probably without changing
fundamentally the type; for the moral life of the Japanese people is
too virile and too essentially sound to permit us to think that the new
influences now coming in will produce such radical changes in the
ethical feelings and convictions of the race as to result in a repetition
of what happened upon the entrance of Christianity into the morally
decadent Greco-Roman world—the displacement of the old ideal of
character by a new and essentially different ideal.
CHAPTER VII
THE ETHICAL IDEALS OF INDIA

PART I. THE ETHICS OF


BRAHMANISM—A CLASS MORALITY

I. Historical and Speculative Basis of the


System

The conception As in Judea so in India the conception formed of


of the First the Supreme Being reacted potently upon morality.
Cause​— ​
Brahma Hence in naming the influences under which the moral
ideal of Brahmanism was molded we must speak first
of the Indian conception of the First Cause.
The Aryan conquerors of India originally held notions of the gods
in general like those held by their kinsmen, the early Greeks and
Romans. When they entered India they were ancestor worshipers
and polytheists. They had earth gods and sky gods. The gods of the
celestial phenomena gradually acquired ascendancy. Then, as in
Egypt, there came a tendency toward unity. The various gods came
to be looked upon by the loftier minds as merely different
225
manifestations of one primal being.
It is right at this point that we find the great antithesis between
Indian modes of thought and those of all or almost all other peoples.
When the thinkers of Egypt, of the Semitic lands, of Persia, of
Greece and Rome, had at last through reflection evolved the lofty
conception of a single great First Cause, they endowed this cause
with conscious personal life. This mode of thought is our heritage
from the past. It is to us almost or quite impossible to conceive of
conscious personal life as springing from an unconscious impersonal
cause. Hence we place behind the manifold phenomena of the
universe a conscious personal being as the origin and source of all
226
things and all life.
It is wholly different with the thinkers of India. They seem to be
able to postulate as the beginning of things an impersonal cause, a
cause without perception, thought, or consciousness. They affirm
that out of unconsciousness consciousness arises. They teach that
out of Brahma, the unconscious, impersonal, passionless One,
emanate all material worlds and sentient beings, gods as well as
men.
How profoundly this conception of the First Cause has reacted on
the ethical speculations of the Hindu sages and on the moral life of
India will appear a little further on.

The god Brahma But this incomprehensible, unconscious,


(Brahman)
passionless Brahma is not the Brahma of the popular
faith. The masses and even the philosophers themselves must have
something more concrete. So this impersonal, neuter Brahma is
conceived as giving existence to the personal, masculine God
Brahma (Brahman), “the progenitor of all worlds, the first-born
227
among beings.”
It is very necessary for the student of Brahmanic ethics to keep in
mind the distinction between the uncreated, unconditioned,
impersonal Brahma and the created, conditioned, personal Brahma,
since there is here laid the foundation of a double goal for rational
moral striving: the goal of the ascetic whose ultimate aim is
deliverance from individual existence and absorption into the
absolute, unchangeable, impersonal Brahma, which means a state
of eternal unconsciousness—dreamless sleep; and the goal of the
multitude, whose hope and aim is blissful, though temporary, union
with the personal Brahma in the heaven of the mortal, conditioned
228
gods.

The system of The ethical evolution in India was also profoundly


castes
influenced by a prehistoric event, namely, the
subjection of the original non-Aryan population of the land by an
intruding Aryan people. As a result of the long and bitter struggle the
two races became separated by a sharp line of race prejudice and
hatred. The dark-skinned natives were reduced to a state of
servitude or dependence upon their conquerors. Intermarriages
between the two races were strictly prohibited, and thus the
population of the conquered districts of the peninsula became
divided into two sharply defined classes. These constituted a model
upon which Indian society was framed. Other classes were formed,
and these gradually hardened into castes, that is, into classes
between which marriages were prohibited. Four great castes arose:
namely, priests or Brahmans, warriors and rulers, peasants and
merchants, and sudras. Below these castes were the pariahs, or
outcasts, made up of the most degraded of the natives. As time
passed, still other divisions were formed, every occupation coming to
constitute the basis of a new caste, till society was stratified like a
geologic deposit.
Religion came in to consecrate this division of the people into
229
privileged and nonprivileged classes. The sacred scriptures
declare that the Brahmans sprang from the mouth of Brahma, the
warriors from his arms, the peasants and traders from his thighs, and
230
the sudras from his feet.
No institution known among men ever exercised a more fateful
and sinister influence upon morality than this caste system has
exercised upon the morality of the peoples of India. The rooted belief
and dogma of the natural inequality of men has made Brahmanic
ethics a thing of grades and classes, and has thus rendered
impossible the evolution of a true morality, which requires for its
basis genuine sentiments of equality and brotherhood.
We easily realize the importance for morality of a
The doctrine of belief in a life after death. But a belief in preëxistence
transmigration may exert an even greater influence upon the moral
231
code of a people than a belief in post-existence.
Now the morality of the Hindus has been molded by both these
doctrines, for according to the teachings of Brahmanism a man has
lived through many lives before his “birth,” and may wander through
“ten thousand millions of existences” after death has freed him from
232
his present body. The class and the condition into which he is
born here on earth is believed to be determined by the sum total of
his merits or demerits earned in preceding existences. As a result of
sin he may in his next birth be reborn in a lower caste, or may be
imprisoned in some animal or vegetable form. He may pass a
thousand times through the bodies of spiders, snakes, and lizards,
and hundreds of times through the forms of grasses, shrubs, and
creepers. And all this experience may come after the soul has
passed through dreadful and innumerable hells for vast cycles of
233
years.
This transmigration theory was framed by the thinkers of India to
explain among other things the seemingly unjust inequalities of
234
human life. It afforded an explanation why one man should be
born a Brahman and another a sudra, one born in a hovel and
another in a palace, by conceiving the place of every person born
into the world as being determined by the manner of his life in former
235
existences.
It is unnecessary to dwell upon the profound influence which this
doctrine of transmigration, or round of births, has exerted upon the
moral life of India. The tendency of this theory, as soon as
elaborated, was to render still more intolerable the position of the
lower castes, particularly that of the sudras, since it made their low
place and hard lot to be the merited punishment of crimes and
misdoings in previous lives; while at the same time it fed the pride
and enhanced the arrogance of the Brahmans, since their superior
lot was, according to the theory, attributable to merit acquired in
other existences. Thus did the theory tend to give a more sinister
aspect to the baneful caste system, to make it appear a part of the
unchangeable order of things, and to render impossible the growth of
any other than a class morality.

Indian Hardly less important than the doctrine of


pessimism
transmigration for Hindu morality is the Indian
conception of life—of all individual, conscious existence whether
here on earth or in other worlds—as inseparable from misery, pain,
decay, and death.
The Aryan immigrants into India seem to have been, like their
kinsmen the Greeks, a light-hearted folk, filled with a strong joy in
life. But as in their journeyings they pressed southward into the
valleys of the Indus and the Ganges and came under the influences
of the hot, depressing climate, and of an oppressive social and
236
political system, they appeared to have lost their buoyant spirits.
The skies seemed less bright and life less worth living, and, weary of
it all, they at last came to regard eternal death, annihilation, as the
greatest of boons.
This pessimistic view of the world and of life, as we shall see a
little further on, forms the basis of large sections of Indian ethics,
since it makes the ultimate goal of rational or moral effort to be the
getting rid of conscious existence.

The conception Another conception which has exerted a profound


of sacrifice
influence upon the religious ethics of Brahmanism is
that respecting sacrifice. This conception is that the gods need
sustenance, and can only exist through the gifts and offerings made
237
to them by men. “The gods live by sacrifice” say the sacred
scriptures; “the sun would not rise if the priests did not make
sacrifice.”
To understand this teaching we must connect it with the belief of
primitive man that the spirits of the dead have absolute need of meat
and drink offerings at the hands of the living, and remember that in
India there is no sharp distinction drawn between the gods and the
souls of men. The gods, like the spirits of the dead, are dependent
for life and strength upon the offerings laid on their altars. Without
these gifts they would die or pine away, and all the movements of the
238
universe controlled by them would cease.
From this conception of the gods came the emphasis laid by
Brahmanism upon sacrifice, and the prominence given the religious
duty of bringing rich gifts to the priests and keeping the altars of the
239
gods heaped with food.

II. The Various Moral Standards

A class morality The fundamental fact of Brahmanic morality is that


as a result of the caste system it is a class morality;
that is, there is a different moral standard or code for each of the
different castes.
In the account given in the Laws of Manu of the origin of the four
chief castes, the occupation and the duties of each class are
carefully prescribed. To the Brahman was assigned teaching and
offering sacrifice; to the warriors and rulers the protection of the
people; to the peasants and merchants the tilling of the ground and
trading; and to the sudras—“One occupation only,” reads the sacred
law, “is prescribed to the sudra, to serve meekly the other three
240
castes.”
241
The Brahman is by right the lord of the whole creation. His
name must express something auspicious, but the first part of the
sudra’s name must express something contemptible, and the second
242
part must be a word denoting service.
For a man of a lower caste to affect equality with a person of a
higher caste is a crime: “If a man of an inferior caste, proudly
affecting an equality with a man of superior caste, should travel by
his side on the road, or sit or sleep upon the same carpet with him,
the magistrate shall take a fine from the man of inferior caste to the
243
extent of his ability.”
For a Brahman to explain to a sudra the sacred Vedas is a sin:
“Let him [the Brahman] not give to a sudra advice nor the remnants
of his meal ...; nor let him explain the sacred law to such a man; ...
for he who explains the sacred law to such ... will sink together with
244
that man into hell.”
In the matter of punishments for crimes the laws are grossly
unequal, the punishment of a person of inferior caste being always
more severe than that of a person of a superior caste for the same
offense. Thus for a crime punishable with death if committed by a
person of an inferior caste, tonsure only is ordained if committed by
245
a Brahman; for a Brahman must never be slain, “though he have
246
committed all horrible crimes.” There is no crime in all the world
247
as great as that of slaying a Brahman.
A knowledge of the inequality of these sacred laws of the
Brahmans and the burdensomeness of this caste morality as it
pressed upon the lower classes is necessary to an understanding of
the rise and rapid spread of Buddhism, and the fervor with which its
teachings of equality and brotherhood were embraced by the
masses of Brahmanic India.

The highest Of the different standards of morality of the several


moral
excellence
castes that of the Brahman is of course the highest.
attainable in The study of the sacred books is for him the chief duty.
general only by “Let him,” says the sacred law, “without tiring daily
Brahmans
mutter the Veda at the proper time; for that is one’s
248
highest duty; all other observances are secondary duties.”
249
Knowledge of the Veda destroys guilt as fire consumes fuel.
Among the secondary duties are observance of the rules of
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.

Let us accompany you on the journey of exploring knowledge and


personal growth!

ebookmass.com

You might also like