AlgoTrading Review
AlgoTrading Review
AlgoTrading Review
doi:10.1145/ 2500117
Algorithmic
Trading
Review
growing rapidly across
Al gor ith m ic t rad i ng 1,9,13,14 i s
all types of financial instruments, accounting for
over 73% of U.S. equity volumes in 2011 (Reuters and
Bloomberg). This has been a fascinating research
area at University College London, where for eight
years algorithmic trading systems and an Algorithmic
Trading/Risk platform7 have been developed with Stock market data, as visualized by artist
Marius Watz, using a program he created to
leading investment banks/funds. represent the fast-paced “flows” of data as
virtual landscapes.
To tell this story, first we must clarify a number of
closely related computational trading terms that are key insights
Stockspace ( 200 9) , M arius Watz. Cu stom so f t wa re a rt based on
stock ma rket data. Commissioned by Knigh t Ca pita l Group.
• Systematic trading refers to any trading strategy management, and asset allocation.
D evelopers use various types of
that is a “rule-based” systematic/repetitive approach simulations, including backtests and
optimizations, to evaluate and improve
to execution trading behaviors. This is often achieved utility of their algorithms.
n ov e mb e r 2 0 1 3 | vo l. 56 | n o. 1 1 | c om m u n ic at ion s of t he acm 77
review articles
stand how a trade is executed by an Ex- types (market orders, limit orders, stop AT System Components
change, the different types of trading, orders, among others).9 In develop- The trading process (as illustrated by
and the objectives and challenges. ing an AT system, understanding the Figure 2) may be divided into five stages:
Trade execution: Dealers generally market microstructure—the detailed ˲˲ Data access/cleaning: Obtaining
execute their orders through a shared process that governs how trades occur and cleaning (financial, economic, so-
centralized order book that lists the and orders interact in a specific mar- cial) data that will drive AT.
buy and sell orders for a specific secu- ket—is of paramount importance. ˲˲ Pre-trade analysis: Analyzes prop-
rity ranked by price and order arrival The “ideal” AT prerequisites in- erties of assets to identify trading op-
time (generally on a first-in-first-out clude: portunities using market data or finan-
basis). This centralized order-driv- ˲˲ Centralized order book: Shared cial news (data analysis).
en trading system continuously at- centralized order book, listing the buy ˲˲ Trading signal generation: Identi-
tempts to match buy and sell orders. and sell orders. fies the portfolio of assets to be accu-
As shown in Figure 1, the order book ˲˲ Liquid markets: A highly liquid mulated based on the pre-trade analy-
is divided into two parts: buy orders market and typically one suitable for sis (what and when to trade).
on the left ranked highest price at high-frequency trading of securities ˲˲ Trade execution: Executing orders
top and sell orders with lowest price (for example, equities, FX). for the selected asset (how to trade).
at top. Orders are generally listed by ˲˲ Order book depth provides an in- ˲˲ Post-trade analysis: Analyzes the
price and time priority, which means dication of the liquidity and depth (the results of the trading activity, such as
most Exchanges prioritize orders number of buy and sell orders at each the difference between the price when
based on the best price and first-in- price) for that security or currency. a buy/sell decision was made and the
first-out framework. ˲˲ Financial information protocols final execution price (trade analysis).
There are many variants to the order (for example, the Financial Information Although we might think of AT as au-
book model described here. Different eXchange protocol, or FIX) for the com- tomating all stages, much of the activ-
Exchanges will accept different order puter communication of information. ity in the industry is devoted to the data
access/cleaning and pre-trade analysis
Figure 1. Trade order book. stages, with the latter stages of the trad-
ing process being supervised by humans.
Figure 2 illustrates the major
Order Book – ABC Inc. Order Book – ABC Inc.
components of each stage of an AT
Buy Sell Buy Sell system. The pre-trade analysis com-
Quantity Price Price Quantity Quantity Price Price Quantity prises computing analytical features
5,000 99 99 4,000 1,000 99 100 10,000 through three main components: Al-
8,000 98 100 10,000 8,000 98 101 1,000 pha model, the mathematical model
10,000 97 101 1,000 10,000 97 103 15,000 designed to predict the future behav-
15,000 95 103 15,000 15,000 95 104 3,000 ior of the financial instruments that
(a) Before matching a trade (b) After matching a trade
the algorithmic system is intended to
trade; Risk model that evaluates the
levels of exposure/risk associated with
the financial instruments; and Trans-
Figure 2. Components of an AT system. action Cost model that calculates the
(potential) costs associated with trad-
ing the financial instruments.
Data
Research (Real-time/Historical; At the Trading Signal stage, the
Market/non-Market) Portfolio Construction model takes
as its inputs the results of the Alpha
Pre-trade Analysis
model, the Risk model, and the Trans-
Alpha Risk Transaction action Cost model and decides what
Model Model Cost Model
portfolio of financial instruments
should be owned and in what quanti-
ties, in the next time horizon.
Trading Signal
At the Trade Execution stage, af-
ter the trading signal has been gener-
Portfolio Construction Model
ated and the portfolio constructed,
Trade Execution the Execution model performs several
decisions with constraints on (actual)
Execution Model transaction costs and trading dura-
tion: the most general decision is the
Post-trade Analysis Trading Strategy followed by the Venue
and Order type, decisions handled by
smart order routing.
n ov e mb e r 2 0 1 3 | vo l. 56 | n o. 1 1 | c om m u n ic at ion s of t he acm 79
review articles
Figure 3. Alpha models—predicting the future. trates the two principal approaches to
risk that we refer to as:
˲˲ Limiting amount of risk: Limiting
Alpha Model the size of risk is managing the expo-
sure through limiting by penalty or
Quant Style constraint, such as leverage; or calcu-
Theory-driven Empirical Data-driven lating volatility and dispersion; and
(hypothesizing market behavior) (data mining market behavior)
˲˲ Limiting type of risk: Eliminating
Input
whole types of exposure. As with oth-
Price-data Fundamental Sentiment Real-time Historical er models, the approaches subdivide
broadly into Theory-driven and Empiri-
Approach cal using historical data.
In limiting these two, we take care of
Momentum Mean Reversion Yield Growth Quality Market Data Non-market Data optimizing the risk-reward ratio.
Position Weighting all chosen instru- will be followed by additional gains and beta of a stock or portfolio is a number
ments are given equal weighting. vice versa for declining values. describing the correlation of its returns
˲˲ Optimization models use algo- ˲˲ Mean Reversion: A trading strat- with those of the financial market as a
rithms with an objective function that egy assuming prices and returns even- whole.) ‘Long’ and ‘short’ positions are
iterates to a portfolio that gives, for ex- tually move back toward the mean or also managed to eliminate net expo-
ample the highest rate of return. Exam- average. A popular strategy is mean sure through diversification.3,16
ples include the Black-Litterman—a so- reversion (pairs trading) where two his- ˲˲ Statistical arbitrage (“stat arb”)
phisticated optimizer popular with AT.13 torically correlated securities that have is an equity trading strategy that em-
The trade execution stage decides diverged are assumed to converge in ploys time series methods to identify
where, what, and when to trade, requir- the future. relative mispricings between stocks.
ing several decisions with constraints To illustrate trading strategies, we One popular technique is pairs trad-
on (actual) transaction costs and trad- discuss so-called market-neutral and ing; pairs of stocks whose prices tend
ing duration. risk-neutral AT,13,16 defined as: to move together; that is they are iden-
˲˲ Market-neutral strategies are trad- tified as correlated.5,12
Execution Models ing strategies, widely used by hedge The purpose of market-neutrality
The execution model (Figure 6) decides: funds or proprietary traders that go of a portfolio is hedging away risk, cre-
˲˲ Trading venue selects the Exchang- “long” on certain instruments while ated by large collective movements
es where the orders are to be placed, “shorting” others in such a way that the of the market. The idea is that such a
with many securities being potentially portfolio has no net exposure to broad portfolio should not be affected by any
tradable on multiple Exchanges. market moves. The goal is to profit type of such price movement, neither
˲˲ Execution strategies cover sched- from relative mispricings between re- up nor down. To achieve such neutral-
uling of trades, such as the popular Vol- lated instruments. ity, one must simultaneously manage
ume Weighted Average Price (VWAP) ˲˲ Risk-neutral strategies are trading (buying) long and (selling) short posi-
that executes a buy order in a financial strategies insensitive to risk, meaning tions in the market.
instrument (for example, stock), as a strategy, which is indifferent to the
close as possible to its historical trad- risk involved in an investment and is Algorithm System Architecture
ing volume. only concerned about expected return. We now look at the trend following or
˲˲ Order type subdivides in market This strategy type is used by market momentum strategy in more detail us-
orders, where a buy or sell order is to makers concerned more with continu- ing Equities as an example.
be executed by the system immediately ous financial flow rather than risk aver- Momentum strategy. A typical mo-
at current market prices; and limit or- sion/seeking. mentum trading strategy for stocks
ders, where an order to buy a security is For example, in equity markets, aims at capturing trends in stock pric-
specified at no more (or sell at no less) market-neutral strategies take two es. It uses the contention that stocks
than a specific price. forms. with an upward momentum will con-
Finally, post-trade analysis com- ˲˲ Equity market-neutral emphasizes tinue rising and should be bought and
pares the expected and actual per- fundamental stock picking, where a stocks with downward momentum will
formance of the executed trades. portfolio of ‘long’ and ‘short’ positions continue falling and should be sold.
This involves cost measurement and is maintained to be beta neutral. (The We use the nomenclature of “winners”
performance measurement. For ex-
ample, cost can be measured between Figure 6. Execution models—venue, strategy, order type.
the actual realized execution price
achieved and the so-called bench- Execution Model
mark price.
When we use the term an “algorith- NYSE LSE NASDAQ CME LME
mic trading strategy” we are typically
referring to the precise nature of
the entire spectrum of activities em- Execution Strategies
ployed by a software system starting
from pre-trade analysis, model selec- Aggressive/Passive Large/Small Order Scheduling Routing
n ov e mb e r 2 0 1 3 | vo l. 56 | n o. 1 1 | c om m u n ic at ion s of t he acm 81
review articles
Figure 7. Download Yahoo! finance data in Python. incurred consecutive losses or the to-
tal unrealized loss exceeds a predeter-
mined value (another parameter).
-> import ystockquote
-> Input ticker Real-time strategy implementation
-> Input start date and optimization. The basic building
-> Input end date block of our implementation of the mo-
-> Store data in variable “data”
mentum strategy is the unit generating
specific realizations of the trading sce-
Actual Code Fragment from Python: nario for any particular set of control-
ling parameters. Its responsibility is
import ystockquote
to traverse all the concurrent strands
ticker = ‘GOOG’ of stock data day-by-day, calculate the
start = ‘20080520’ scores, grade the stocks, and carry out
end = ‘20080523’
the resulting trades. At the same time
data = ystockquote.get_historical_prices (ticker, start, end) it keeps track of its own stock holding
inventory and current cash balance. Its
output is the time development curve
of the total value of its holdings (stock
Figure 8. Alpha model pseudo code. and cash), for which the Sharpe Ratio
is then calculated. (The Sharpe Ratio is
a measure of the excess return (or risk
-> Choose a look0back period for a specific security [example: 1 hr, 30
mins, 10 mins, 1 min, 30 seconds]
premium) per unit of deviation in an
-> Access tick data for the look-back period investment asset or a trading strategy.)
-> Compute a simple moving average metric [SMA] The strategy runs, described here,
-> In order to calculate SMA we need to select
must be repeated for every combina-
1) Time-scale for historical data (e.g. 1 min)
2) Number of data points to be used in the SMA tion of parameters’ values (different
(e.g. 120 data points) scoring thresholds, investment hori-
-> SMA [60} = {current price + (price 1 min before) + zons) via exhaustive enumeration. Out
(price 2 mins before) + ..... (price 59 mins before)}/60
of this set of all possible realizations,
-> Repeat for all stocks [i.e. all 406 stocks in the S&P500] the optimal strategy, with best Sharpe
Ratio, is then selected.
-> We now have enough data to enter the signal generation stage of the
Alpha Model
Trading System Implementation
We now present a simple AT system
based on momentum, which is market
for the former and “losers” for the lat- we determine the amounts of each neutral and risk neutral, together with
ter. In our implementation of the mo- stock to hold. A simple portfolio con- pseudo-code fragments to illustrate
mentum strategy, we use the Simple struction rule is to invest equal dollar its implementation. We have removed
Moving Average for the last 60 minutes amounts in each stock that needs to be all possible extraneous details with
(SMA) metric to capture upward/down- traded since we do not know how each the goal of making the implementa-
ward trends. stock would perform. After we run the tion easy to understand. For a more
The strategies commence by con- strategy for at least a day, we can com- intricate discussion of momentum
ducting pre-trade analysis on stock pute stock-specific performance met- trading, read Wang and Kochard.17
price data of a specific granularity. rics to invest aggressively in specific Our simple implementation is
Pre-trade analysis usually entails com- stocks that performed well. based on the concept of price mo-
puting the value of one or more tech- Our Trade Execution model as- mentum; that is a tendency of rising
nical indicators. sumes there is a fixed strategy update stocks, the winners, to keep rising,
For the purpose of the strategy pre- cycle where the strategy does the pre- and falling stocks, the losers, to fall
sented here we have used a single tech- trade analysis for the look-back period, further. Momentum, as a property of
nical indicator SMA. The value of SMA scans for trading signals and places the Stock Market, is somewhat con-
is used for signal generation. trades and this sequence of actions is troversial, but its existence in stock
If the stock price for one of the repeated at regular intervals (the most returns has been confirmed by em-
shortlisted stocks exceeds the value of optimal frequency is chosen during pirical studies. The strategy discussed
the SMA, the system generates a buy optimization over multiple back-tests, here will consist of trading stocks
signal and vice versa. This stage is usu- as we will discuss later) Each trade from a broad fixed collection select-
ally called signal generation. During has an investment horizon—the maxi- ed to represent the S&P500 universe.
signal generation the stocks that need mum duration one can hold a position At any time we will hold a portfolio
to be traded get picked via the signals. (a parameter of the strategy) and we of long positions in top winners and
The next phase of the strategy con- may also temporarily withdraw from short positions in bottom losers8 se-
sists of Portfolio construction, where trading any stock whose number of lected from these stocks.
n ov e mb e r 2 0 1 3 | vo l. 56 | n o. 1 1 | c om m u n ic at ion s of t he acm 83
review articles
for simplicity, to remove them entirely. Calculation of Sharpe Ratio financialcomputing.org). We thank
The remaining 406 stocks will form the If we denote by Rt the daily returns, Dan Brown and Jan Grochmalicki, and
initial contents of our trading portfolio. that is, the daily relative (%) changes students contributing to the AT and risk
It must be noted here that, as the of value of our total wealth (the sum platform, and the extensive research
composition of the S&P Index keeps of the trading account, the net value conducted with the banks and funds. We
changing, not all of the stocks we of the portfolio and the current value also thank Trading Technologies, Chi-
picked will necessarily still be part of of the SPX-hedge), then the associated X, and Knight (HotSpotFX) for granting
the Index at the end of our experiment. Sharpe Ratio (SR) is given as us access to their datafeed streams for
However, by insisting on the complete- research; Barclays, Citigroup, BNP Pa-
ness of the pricing information for all SR = mean(Rt) / std(Rt); ribas Fortis, and BAML for their advice
the stocks in our portfolio we ensure and support, Clive Hawkins (Barclays),
they were all actively traded through- where mean(Rt) and std(Rt) are respec- Nick Edwards (Trading Technologies),
out. As the adjustments of the Index tively the average and the standard de- Martin Frewer (BNP Paribas Fortis),
are impossible to monitor, we will ig- viation of the returns calculated over the Kevin Gillespie (HotSpotFX), and Piotr
nore them, as if the Index was frozen. entire training period of our strategy. Karasinski (EBRD).
Our initial trading account starts with As the mean value represents the gains
a unit of wealth, representing $1 million. and the standard deviation conveys the References
1. Chan, E.P. Quantitative Trading: How to Build Your Own
Back-testing. We can divide the back- risk, the maximum value of the Sharpe Algorithmic Trading Business. Wiley Trading, 2009.
testing simulation into two phases. The Ratio offers the best compromise be- 2. Che, S., Li, J., Sheaffer, J., Skadron, K. and Lach, J.
Accelerating compute-intensive applications with GPUs
first five years constitute the in-sample tween the performance and risk. and FPGAs. In Proceedings of the IEEE Symposium on
Application Specific Processors (June 2008).
period, when we train the algorithm, Back-testing results. The strategy 3. Chincarini, L. and Kim, D. Quantitative Equity Portfolio
in order to choose the parameters (for variation with the best Sharpe Ratio and Management: An Active Approach to Portfolio
Construction and Management. McGraw-Hill Library
example: the optimal look-back period, out of sample performance is chosen of Investment & Finance, 2006.
investment horizon, risk thresholds) to be implemented in real time. Back 4. Dunis, C. L., Laws J. and Naïm P. Applied Quantitative
Methods for Trading and Investment. Wiley Finance
giving the best P&L performance. Then, testing is a key step in any algorithmic Series, 2003.
the following year, the out-of-sample strategy construction as without back- 5. Ehrman, D.S. The Handbook of Pairs Trading:
Strategies Using Equities, Options, and Futures. Wiley
period, is the test run used to validate testing we would not know which com- Trading, 2006.
the selected parameters. bination of parameters gives the high- 6. Financial Information eXchange (FIX) Protocol;
http://en.wikipedia.org/wiki/Financial_Information_
In-sample training: Optimization. est profit for a given strategy. eXchange or http://fixprotocol.org/
During this phase, different variations 7. Galas, M., Brown, D. and Treleaven, P. A computational
social science environment for financial/economic
of the strategy are applied to past data. Conclusion experiments. In Proceedings of the Computational
Variations of a strategy can be defined As noted at the outset, the research chal- Social Science Society of the Americas (2012).
8. Jegadeesh, N. and Titman, S. Returns to buying
as the same underlying model with dif- lenges (and the consequences of getting winners and selling losers: Implications for stock
ferent time parameters for computa- it wrong) are still poorly understood. In- market efficiency. J. Finance 48, 1 (Mar. 1993), 65-91.
9. Johnson, B. Algorithmic trading & DMA: An
tion of pre-trade metrics. For example: deed, challenges persist and span data introduction to direct access trading strategies, 2010.
10. Kaufman, P.J. The New Trading Systems and Methods.
the look-back period for computing the handling—cleaning, stream process- Wiley Trading, 2005.
metrics could range from few seconds ing, storage, and using new types such 11. Lo, A. Finance is in need of a technological revolution.
Financial Times, Aug. 27, 2012.
to few hours. A variation can also mean as social data and news for forecasting; 12. Meucci, A. Review of Statistical Arbitrage,
applying the same model with different algorithm behavior—selecting the best Cointegration, and Multivariate Ornstein-Uhlenbeck.
SSRN preprint 1404905, 2010.
time frame for investment horizons of computational statistics and machine 13. Narang, R.K. Inside the Black Box: The Simple Truth
trades. For example: a strategy could learning algorithms, and setting their About Quantitative Trading. Wiley Finance, 2009.
14. Nuti, G., Mirghaemi, M., Treleaven, P. and Yingsaeree,
be tested where the maximum holding variables to optimize performance; al- C. Algorithmic trading. IEEE Computer 44, 11 (Nov.
time for positions is three minutes or gorithms’ interaction—understanding 2011), 61–69.
15. Pardo, R. The Evaluation and Optimization of Trading
30 minutes or an hour. After each varia- the interactions of AT systems within Strategies, Wiley Trading 2008.
tion is applied to past data, the P&L per- a firm and within a market; and high- 16. Stokes, E. Market Neutral Investing. Dearborn Trade
Publishing, 2004.
formance is recorded and the Sharpe performance computing—support of 17. Wang, P. and Kochard, L. Using a Z-score Approach
ratios computed. The strategy variation low-latency trading and the use of novel to Combine Value and Momentum in Tactical Asset
Allocation. SSRN preprint 1726443, 2011.
with the best P&L performance and hardware such as GPUs and FPGAs. 18. Zigrand, J.P., Cliff, D. and Hendershott, T. Financial
Sharpe Ratio is chosen to be applied to We hope this article serves to en- stability and computer based trading. The Future of
Computer Trading in Financial Markets, U.K. Gov., 2011.
the out-of-sample period. courage computer scientists to pursue
There are two adjustable parameters research in the AT area. Our goal was Philip Treleaven ([email protected]) is a professor
controlling the trading in this strategy: to provide a comprehensive presenta- of computer science and head of the U.K. Ph.D. Centre in
˲˲ Time-window used to calculate the Financial Computing at University College London, U.K.
tion of AT systems, including pseudo-
pre-trade metrics. code fragments, and as a case study, a Michal Galas is a Research Fellow and chief programmer
in the U.K. Ph.D. Centre in Financial Computing at
˲˲ Time-frame between portfolio ad- simple market-neutral trend following University College London, U.K.
justments-investment horizon. AT strategy. Vidhi Lalchand is a research student at University
Their optimal values are established College London, U.K.
by looking for the best in-sample strat- Acknowledgments
egy performance, as measured by the This article was produced by the U.K. Copyright held by Owner/Author(s). Publication rights
Sharpe ratio. Centre for Financial Computing (www. licensed to ACM. $15.00
n ov e mb e r 2 0 1 3 | vo l. 56 | n o. 1 1 | c om m u n ic at ion s of t he acm 85