Quantitative Trading Strategies Using Python Technical Analysis Statistical Testing And Machine Learning Pengliu download
Quantitative Trading Strategies Using Python Technical Analysis Statistical Testing And Machine Learning Pengliu download
https://ebookbell.com/product/quantitative-trading-strategies-
using-python-technical-analysis-statistical-testing-and-machine-
learning-pengliu-52168706
https://ebookbell.com/product/quantitative-trading-strategies-
harnessing-the-power-of-quantitative-techniques-to-create-a-winning-
trading-program-1st-edition-lars-kestner-1367392
https://ebookbell.com/product/optimal-trading-strategies-quantitative-
approaches-for-managing-market-impact-and-trading-risk-1st-robert-
kissell-891378
https://ebookbell.com/product/finding-alphas-a-quantitative-approach-
to-building-trading-strategies-1st-edition-igor-tulchinsky-5296488
https://ebookbell.com/product/finding-alphas-a-quantitative-approach-
to-building-trading-strategies-2nd-igor-tulchinsky-et-al-10568410
Algorithmic Trading And Quantitative Strategies 1st Edition Raja Velu
https://ebookbell.com/product/algorithmic-trading-and-quantitative-
strategies-1st-edition-raja-velu-16313960
https://ebookbell.com/product/trader-construction-kit-fundamental-
technical-analysis-risk-management-directional-trading-spreads-
options-quantitative-strategies-execution-position-management-data-
science-programming-2nd-edition-joel-rubano-46138018
https://ebookbell.com/product/quantative-analysis-derivatives-
modeling-and-trading-strategies-yi-tang-1232334
https://ebookbell.com/product/quantitative-trading-how-to-build-your-
own-algorithmic-trading-business-1st-edition-chan-55485234
Quantitative
Trading Strategies
Using Python
Technical Analysis, Statistical Testing,
and Machine Learning
—
Peng Liu
Quantitative Trading
Strategies Using Python
Technical Analysis, Statistical
Testing, and Machine Learning
Peng Liu
Quantitative Trading Strategies Using Python: Technical Analysis, Statistical Testing,
and Machine Learning
Peng Liu
Singapore, Singapore
iii
Table of Contents
iv
Table of Contents
v
Table of Contents
vi
Table of Contents
vii
Table of Contents
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
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.
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
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
5
Chapter 1 Quantitative Trading: An Introduction
6
Chapter 1 Quantitative Trading: An Introduction
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.
8
Chapter 1 Quantitative Trading: An Introduction
9
Chapter 1 Quantitative Trading: An Introduction
• 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.
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.
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.
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.
14
Chapter 1 Quantitative Trading: An Introduction
Let us look at the anatomy of a trade. There are four usual steps involved when
performing a trade:
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.
16
Chapter 1 Quantitative Trading: An Introduction
• Mutual fund
• Pension fund
• Hedge fund
• Insurance company
• Bank
• Corporate nominee
• Start-up investor
• Family business
• Household/individual
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
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
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.
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.
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
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:
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:
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:
The following section will look at visualizing the time series data via
interactive charts.
28
Chapter 1 Quantitative Trading: An Introduction
fig = go.Figure(data=go.Scatter(x=data.index,y=data['Close'],
mode='lines'))
fig.show()
Running the code produces Figure 1-8. Note that the graph is interactive; by hovering
over each point, the corresponding date and closing price come forward.
Figure 1-8. Interactive time series plot of the daily closing price of Microsoft
29
Chapter 1 Quantitative Trading: An Introduction
We can also enrich the graph by overlaying the trading volume information, as
shown in Listing 1-4.
Listing 1-4. Overlaying trading volume in the daily closing price chart
Running the code generates Figure 1-9. Note that the trading volume assumes a
secondary y-axis on the right, by setting secondary_y=True.
Figure 1-9. Visualizing the daily closing price and trading volume of Microsoft
Based on this graph, a few bars stand out, making it difficult to see the line chart.
Let us change it by controlling the magnitude of the secondary y-axis. Specifically, we
can enlarge the total magnitude of the right y-axis to make these bars appear shorter, as
shown in Listing 1-5.
# rescale volume
fig2.update_yaxes(range=[0,500000000],secondary_y=True)
fig2.update_yaxes(visible=True, secondary_y=True)
fig2
30
Chapter 1 Quantitative Trading: An Introduction
Running the code generates Figure 1-10. Now the bars appear shorter given a bigger
range (0 to 500M) of the y-axis on the right.
Figure 1-10. Controlling the magnitude of the daily trading volume as bars
Lastly, let us plot all the price points via candlestick charts. This requires us to pass
in all the price-related information in the DataFrame. The Candlestick() function can
help us achieve this, as shown in Listing 1-6.
Running the code generates Figure 1-11. Each bar represents one day’s summary
points (open, high, low, and close), with the green color indicating an increase in price
and red indicating a decrease in price at the end of the trading day.
31
Chapter 1 Quantitative Trading: An Introduction
Figure 1-11. Visualizing all daily price points of Microsoft as candlestick charts
Notice the sliding window at the bottom. We can use it to zoom in a specific range, as
shown in Figure 1-12. The dates along the x-axis are automatically adjusted as we zoom
in. Also, note that these bars come in groups of five. This is no incidence—there are five
trading days in a week.
Summary
In this chapter, we covered the basics of quantitative trading, covering topics such as
institutional algorithmic trading, major asset classes, derivatives such as options, market
structures, buy-side investors, market making, scalping, and portfolio rebalancing. We
then delved into exploratory data analysis of the stock data, starting with summarizing
the periodic data points using candlestick charts. We also reviewed the practical side of
things, covering data retrieval, analysis, and visualization via interactive charts. These
will serve as the building blocks as we develop different trading strategies later on.
32
Chapter 1 Quantitative Trading: An Introduction
Exercises
• List a few financial instruments and describe the risk and reward
profile.
• Can a model get exposed to the test set data during training?
• What is the payoff function for the issuer of a European call option?
Put option? How is it connected to the payoff function of the buyer?
• Download the stock price data of Apple, plot it as both a line and a
candlestick chart, and analyze its trend.
33
CHAPTER 2
Electronic Market
In this chapter, we delve into the world of electronic markets, which have revolutionized
the way financial instruments are traded. With the rapid advancements in technology
and the widespread adoption of the Internet, electronic markets have largely replaced
traditional, floor-based trading venues, ushering in an era of speed, efficiency, and
accessibility for market participants around the globe.
Electronic markets facilitate the buying and selling of financial instruments,
such as stocks, bonds, currencies, and commodities (covered in Chapter 1), through
computerized systems and networks. They have played a critical role in democratizing
access to financial markets, enabling a broader range of participants, including retail
investors, institutional investors, and high-frequency traders, to engage in trading
activities with ease and transparency. At the heart of electronic markets lies the trading
mechanism, which governs how buy and sell orders are matched, executed, and settled.
Furthermore, electronic markets offer a variety of order types that cater to the diverse
needs and objectives of traders. These order types can be used to achieve specific goals,
such as minimizing market impact, ensuring a desired level of execution, or managing
risk. In this chapter, we will examine the most common types of orders, including market
orders, limit orders, stop orders, and their various iterations.
As we progress through this chapter, readers will gain a comprehensive
understanding of the inner workings of electronic markets, the trading mechanisms that
drive them, and the wide array of order types available to market participants.
35
© Peng Liu 2023
P. Liu, Quantitative Trading Strategies Using Python, https://doi.org/10.1007/978-1-4842-9675-2_2
Chapter 2 Electronic Market
trading instruments could vary a lot, and we use their respective tick sizes to represent
the minimum amount they can move up or down on an exchange. Stocks generally
trade in one-cent tick size increments, currencies in pips (percentage in point or price
interest point), and rates in basis points (bps). When the price grid is such that prices are
arranged from the smallest price to the largest price, it is called the price ladder.
The price ladder plays a crucial role in electronic markets by providing a visual
representation of the order book, which contains a list of all pending buy and sell orders
for a specific trading instrument. The order book is continuously updated in real time,
reflecting the dynamic nature of the market as new orders are placed, modified, or
canceled. Each rung of the price ladder corresponds to a specific price level, with buy
orders (or bids) listed on one side and sell orders (or asks) on the other. The highest bid
and the lowest ask are referred to as the best bid and best ask, respectively, and the gap
between them is known as the bid-ask spread.
Market participants can use the information provided by the price ladder and order
book to gain valuable insights into a particular trading instrument’s supply and demand
dynamics. This data can help traders identify potential trading opportunities, assess
liquidity, and gauge the depth of the market at various price levels. For instance, large
clusters of orders at specific price points may indicate significant support or resistance
levels, while a thinning order book might suggest a lack of liquidity and increased price
volatility. By carefully analyzing the price ladder and order book, traders can make
more informed decisions and develop strategies that take advantage of the prevailing
market conditions. Additionally, understanding the role of tick sizes in the price grid is
crucial for traders when placing orders, managing risk, and executing trades, as even
small changes in tick sizes can have a substantial impact on the potential profit or loss of
a trade.
Electronic Order
The rise of electronic trading has brought about significant improvements in the
efficiency, speed, and accessibility of financial markets. Transactions that once
took minutes or hours to complete can now be executed in milliseconds or even
microseconds, thanks to the power of high-speed networks and advanced computer
algorithms. As a result, market participants can take advantage of fleeting trading
opportunities, react more swiftly to market news, and benefit from tighter bid-ask
spreads, which translate into lower transaction costs.
36
Chapter 2 Electronic Market
From an investor’s perspective, making a trade via a computer system is simple and
easy. However, the complex process behind the scenes sits on top of an impressive array
of technology. What was once associated with shouting traders and wild hand gestures
in open outcry markets has now become more closely associated with computerized
trading strategies.
When you place an order to trade a financial instrument, the complex technology
enables your brokerage to interact with all the securities exchanges looking to execute
the trade. Those exchanges simultaneously interact with all the brokerages to facilitate
trading activities.
For example, the Singapore Exchange (SGX), a Singaporean investment holding
company, acts through its central depository (CDP) as a central counterparty to all
matched trades (mainly securities) executed on the SGX ST Trading Engine, as well as
privately negotiated married trades that are reported to the clearing house for clearing
on the trade date. Being a central counterparty (CCP), CDP assumes the role of the seller
to the buying clearing member and buyer to the selling clearing member. CDP, therefore,
takes the buyer’s credit risks and assumes the seller’s delivery risks. This interposing
of CDP as the CCP eliminates settlement uncertainty for market participants. SGX
37
Chapter 2 Electronic Market
38
Chapter 2 Electronic Market
Agency orders can be held or not held. Held orders are those when the broker has
an obligation to a client to fill the order. Market-not-held orders are institutional orders
where the trader hires a broker-dealer to execute the order. Working on an order means a
broker-dealer takes some time to fill the order.
Understanding the differences between proprietary and agency trading is essential
for market participants to navigate the complex world of financial markets. While
proprietary trading focuses on generating profits through active market participation,
agency trading emphasizes the execution of client orders in the best possible manner,
ensuring that the interests of clients are at the forefront of the broker’s actions.
• Price precedence: Orders with better prices are given priority over
orders with worse prices. In the case of buy orders, higher bids have
precedence, while for sell orders, lower asks are prioritized. This rule
ensures that market participants who are willing to buy at higher
prices or sell at lower prices get their orders executed first.
39
Chapter 2 Electronic Market
• Time precedence: If two or more orders have the same price, the
order that was placed earlier takes precedence. This rule, also known
as the “first-come, first-served” principle, rewards traders who
submit their orders earlier, ensuring that they are not disadvantaged
by others submitting orders at the same price later.
There are three common types of orders that an electronic exchange sees: limit
orders, market orders, and cancelation orders. Limit orders must include information
such as the limit price, order size, and trade direction (buy or sell). Market orders must
include the order size and trade direction. A cancelation order cancels a standing limit
order entirely or reduces its order size.
Note that some exchanges, such as the London Stock Exchange and the NYSE Group,
support functionality to allow traders to specify whether their limit orders are to be
displayed or not on the limit order book (LOB). This is called lit (displayed) or unlit (not
displayed). In that case, the limit order must have at least the following:
• Limit price
• Order size
• Trade direction
• Display or non-display
Several common order precedence rules are considered for execution. For the
order type precedence, market orders always rank above limit orders. For the price
precedence, a more competitive price rule is. The display precedence takes the form
of lit or unlit preference, and the time precedence observes the time of arrival for
the orders.
The rule used by most exchanges is the price/display/time precedence rule to
determine the priority of execution. Specifically, the highest bids and lowest offers
always execute before lower bids and higher offers. Among equally priced orders,
40
Random documents with unrelated
content Scribd suggests to you:
The Project Gutenberg eBook of Armenia immolata
This ebook is for the use of anyone anywhere in the United States
and most other parts of the world at no cost and with almost no
restrictions whatsoever. You may copy it, give it away or re-use it
under the terms of the Project Gutenberg License included with this
ebook or online at www.gutenberg.org. If you are not located in the
United States, you will have to check the laws of the country where
you are located before using this eBook.
Language: English
ARMENIA IMMOLATA.
HYeONations
YE! Ho ye! all Europe, ho!
hear and patronize!
Unequalled realistic show
On the World stage we advertise!
Our repertoire will render flat
Your little operas and plays,
Your wagers of the ball and bat,
Your hunting rides, and all the craze
Of wheel and sail on land and main—
Yea, even tame the bulls of Spain!
Revival ours of classic sports,
Now with a brilliance to be seen
Which, should it reach the heavenly courts,
Would turn the eyes of Nero green!
To-day comes forth the Turkish beast,
Three days kept hungry in his den,
On the Armenian slave to feast,
Who meets him arm-ed with a pen!
Sure we shall win your approbation,—
There, France and Russia on the right—
The cost not a consideration;—
The Triple Friends shall have the sight
Here from the left, and in the center
Let Britain spread her cloth of gold!
All in between ye small folk enter—
America shall stand and scold!
Now all right merrily shall chime.
Ye knightly gentlemen, compose
Your little quarrels for the time;
Somewhat to reason each man owes,
And to the general happiness;
Your feuds shall suffer no abate
For an altruistical recess.
Now come ye all and come in state!
II.
O Europe! O America!
If ye but knew this fatal day!
If ye could read the eternal law
Now at the parting of the way!
If ye, beholding thus distressed
This pilgrim, leave him here to die,
Ye are his murderers confessed,
The guilt upon your souls will lie.
T’will follow you through many a year,
Corrupting the sweet tides of life,
Now in insidious blight appear,
And now break forth in horrid strife.
T’will nullify religion’s claims,
T’will mar your literature and art;
T’will choke society’s best aims,
To greed new energy impart.
Nor even so shall ye evade
The dreaded specter of the East;
Until by right or ruin laid
It shall intrude into your feast.
But if ye do the deed of men
And save your brother here half-killed,
Then shall ye be as born again,
Your life with upward impulse filled.
Your better selves once shaken free
Will loath submit to other chains;
And from your deed of charity,
Your own shall be the larger gains.
IX.
Updated editions will replace the previous one—the old editions will
be renamed.
1.D. The copyright laws of the place where you are located also
govern what you can do with this work. Copyright laws in most
countries are in a constant state of change. If you are outside the
United States, check the laws of your country in addition to the
terms of this agreement before downloading, copying, displaying,
performing, distributing or creating derivative works based on this
work or any other Project Gutenberg™ work. The Foundation makes
no representations concerning the copyright status of any work in
any country other than the United States.
1.E.6. You may convert to and distribute this work in any binary,
compressed, marked up, nonproprietary or proprietary form,
including any word processing or hypertext form. However, if you
provide access to or distribute copies of a Project Gutenberg™ work
in a format other than “Plain Vanilla ASCII” or other format used in
the official version posted on the official Project Gutenberg™ website
(www.gutenberg.org), you must, at no additional cost, fee or
expense to the user, provide a copy, a means of exporting a copy, or
a means of obtaining a copy upon request, of the work in its original
“Plain Vanilla ASCII” or other form. Any alternate format must
include the full Project Gutenberg™ License as specified in
paragraph 1.E.1.
• You pay a royalty fee of 20% of the gross profits you derive
from the use of Project Gutenberg™ works calculated using the
method you already use to calculate your applicable taxes. The
fee is owed to the owner of the Project Gutenberg™ trademark,
but he has agreed to donate royalties under this paragraph to
the Project Gutenberg Literary Archive Foundation. Royalty
payments must be paid within 60 days following each date on
which you prepare (or are legally required to prepare) your
periodic tax returns. Royalty payments should be clearly marked
as such and sent to the Project Gutenberg Literary Archive
Foundation at the address specified in Section 4, “Information
about donations to the Project Gutenberg Literary Archive
Foundation.”
• You comply with all other terms of this agreement for free
distribution of Project Gutenberg™ works.
1.F.
1.F.4. Except for the limited right of replacement or refund set forth
in paragraph 1.F.3, this work is provided to you ‘AS-IS’, WITH NO
OTHER WARRANTIES OF ANY KIND, EXPRESS OR IMPLIED,
Welcome to our website – the perfect destination for book lovers and
knowledge seekers. We believe that every book holds a new world,
offering opportunities for learning, discovery, and personal growth.
That’s why we are dedicated to bringing you a diverse collection of
books, ranging from classic literature and specialized publications to
self-development guides and children's books.
ebookbell.com