text
stringlengths
0
4.57k
92 Figure 10. 1: Time series plots of AREX and WLL Figure 10. 2: Scatter plot of AREX and WLL prices Python Implementation We will now use Python libraries to test for a cointegrating relationship between AREX and WLL for the period of Jan 1st 2012 to Jan 1st 2013. We will use Yahoo Finance for the data source and Statsmodels to carry out the ADF test, as above. The first task is to create a new file, cadf. py, and import the necessary libraries. The code makes use of Num Py, Matplotlib, Pandas and Statsmodels. In order to correctly label the axes
93 Figure 10. 3: Residual plot of AREX and WLL linear combination and download data from Yahoo Finance via pandas, we import the matplotlib. dates module and the pandas. io. data module. We also make use of the Ordinary Least Squares (OLS) function from pandas: #!/usr/bin/python #-*-coding: utf-8-*-# cadf. py import datetime import numpy as np import matplotlib. pyplot as plt import matplotlib. dates as mdates import pandas as pd import pandas. io. data as web import pprint import statsmodels. tsa. stattools as ts from pandas. stats. api import ols The first function, plot_price_series, takes a pandas Data Frame as input, with to columns given by the placeholder strings "ts1" and "ts2". These will be our pairs equities. The function simply plots the two price series on the same chart. This allows us to visually inspect whether any cointegration may be likely. We use the Matplotlib dates module to obtain the months from the datetime objects. Then we create a figure and a set of axes on which to apply the labelling/plotting. Finally, we plot the figure: # cadf. py def plot _price _series(df, ts1, ts2): months = mdates. Month Locator() # every month fig, ax = plt. subplots() ax. plot(df. index, df[ts1], label=ts1)
94 ax. plot(df. index, df[ts2], label=ts2) ax. xaxis. set _major _locator(months) ax. xaxis. set _major _formatter(mdates. Date Formatter('%b %Y')) ax. set _xlim(datetime. datetime(2012, 1, 1), datetime. datetime(2013, 1, 1)) ax. grid(True) fig. autofmt _xdate() plt. xlabel('Month/Year') plt. ylabel('Price ($)') plt. title('%s and %s Daily Prices' % (ts1, ts2)) plt. legend() plt. show() The second function, plot_scatter_series, plots a scatter plot of the two prices. This allows us to visually inspect whether a linear relationship exists between the two series and thus whether it is a good candidate for the OLS procedure and subsequent ADF test: # cadf. py def plot _scatter _series(df, ts1, ts2): plt. xlabel('%s Price ($)' % ts1) plt. ylabel('%s Price ($)' % ts2) plt. title('%s and %s Price Scatterplot' % (ts1, ts2)) plt. scatter(df[ts1], df[ts2]) plt. show() The third function, plot_residuals, is designed to plot the residual values from the fitted linear model of the two price series. This function requires that the pandas Data Frame has a "res" column, representing the residual prices: # cadf. py def plot _residuals(df): months = mdates. Month Locator() # every month fig, ax = plt. subplots() ax. plot(df. index, df["res"], label="Residuals") ax. xaxis. set _major _locator(months) ax. xaxis. set _major _formatter(mdates. Date Formatter('%b %Y')) ax. set _xlim(datetime. datetime(2012, 1, 1), datetime. datetime(2013, 1, 1)) ax. grid(True) fig. autofmt _xdate() plt. xlabel('Month/Year') plt. ylabel('Price ($)') plt. title('Residual Plot') plt. legend() plt. plot(df["res"]) plt. show() Finally, the procedure is wrapped up in a __main__ function. The first task is to download the OHLCV data for both AREX and WLL from Yahoo Finance. Then we create a separate Data Frame, df, using the same index as the AREX frame to store both of the adjusted closing price values. We then plot the price series and the scatter plot. After the plots are complete the residuals are calculated by calling the pandas ols function on the WLL and AREX series. This allows us to calculate the βhedge ratio. The hedge ratio is then used to create a "res" column via the formation of the linear combination of both WLL and AREX.
95 Finally the residuals are plotted and the ADF test is carried out on the calculated residuals. We then print the results of the ADF test: # cadf. py if__name __== " __main __": start = datetime. datetime(2012, 1, 1) end = datetime. datetime(2013, 1, 1) arex = web. Data Reader("AREX", "yahoo", start, end) wll = web. Data Reader("WLL", "yahoo", start, end) df = pd. Data Frame(index=arex. index) df["AREX"] = arex["Adj Close"] df["WLL"] = wll["Adj Close"] # Plot the two time series plot _price _series(df, "AREX", "WLL") # Display a scatter plot of the two time series plot _scatter _series(df, "AREX", "WLL") # Calculate optimal hedge ratio "beta" res = ols(y=df['WLL'], x=df["AREX"]) beta _hr = res. beta. x # Calculate the residuals of the linear combination df["res"] = df["WLL"]-beta _hr*df["AREX"] # Plot the residuals plot _residuals(df) # Calculate and output the CADF test on the residuals cadf = ts. adfuller(df["res"]) pprint. pprint(cadf) The output of the code (along with the Matplotlib plots) is as follows: (-2. 9607012342275936, 0. 038730981052330332, 0, 249, {'1%':-3. 4568881317725864, '10%':-2. 5729936189738876, '5%':-2. 8732185133016057}, 601. 96849256295991) It can be seen that the calculated test statistic of-2. 96 is smaller than the 5% critical value of-2. 87, which means that we can reject the null hypothesis that there isn't a cointegrating relationship at the 5% level. Hence we can conclude, with a reasonable degree of certainty, that AREX and WLL possess a cointegrating relationship, at least for the time period sample considered. We will use this pair in subsequent chapters to create an actual trading strategy using an implemented event-driven backtesting system.
96 10. 4 Why Statistical Testing? Fundamentally, as far as algorithmic trading is concerned, the statistical tests outlined above are only as useful as the profits they generate when applied to trading strategies. Thus, surely it makes sense to simply evaluate performance at the strategy level, as opposed to the price/time series level? Why go to the trouble of calculating all of the above metrics when we can simply use trade level analysis, risk/reward measures and drawdown evaluations? Firstly, any implemented trading strategy based on a time series statistical measure will have a far larger sample to work with. This is simply because when calculating these statistical tests, we are making use of each barof information, rather than each trade. There will be far less round-trip trades than bars and hence the statistical significance of any trade-level metrics will be far smaller. Secondly, any strategy we implement will depend upon certain parameters, such as look-back periods for rolling measures or z-score measures for entering/exiting a trade in a mean-reversion setting. Hence strategy level metrics are only appropriate for these parameters, while the statistical tests are valid for the underlying time series sample. In practice we want to calculate both sets of statistics. Python, via the statsmodels and pandas libraries, make this extremely straightforward. The additional effort is actually rather minimal!
Chapter 11 Forecasting In this chapter we will create a statistically robust process for forecasting financial time series. These forecasts will form the basis for further automated trading strategies. We will expand on thetopicof Statistical Learningdiscussedinthepreviouschaptersanduseagroupof classification algorithms to help us predict market direction of financial time series. Within this chapter we will be making use of Scikit-Learn, a statistical machine learning library for Python. Scikit-learn contains "ready-made" implementations of many machine learn-ing techniques. Not only does this save us a great deal of time in implementing our trading algorithms, but it minimises the risk of bugs introduced by our own code. It also allows addi-tional verification against machine learning libraries written in other packages such as R or C++. This gives us a great deal of confidence if we need to create our own custom implementation, for reasons of execution speed, say. We will begin by discussing ways of measuring forecaster performance for the particular case of machine learning techniques used. Then we will consider the predictive factors that can be used in forecasting techniques and how to choose good factors. Then we will consider various supervised classifier algorithms. Finally, we will attempt to forecast the daily direction of the S&P500, which will later form the basis of an algorithmic trading strategy. 11. 1 Measuring Forecasting Accuracy Before we discuss choices of predictor and specific classification algorithms we must discuss their performance characteristics and how to evaluate them. The particular class of methods that we are interested in involves binary supervised classification. That is, we will attempt to predict whether the percentage return for a particular future day is positive or negative (i. e. whether our financial asset has risen or dropped in price). In a production forecaster, using a regression-type technique, we would be very concerned with the magnitude of this prediction and the deviations of the prediction from the actual value. To assess the performance of these classifiers we can make use of the following two measures, namely the Hit-Rate and Confusion Matrix. 11. 1. 1 Hit Rate The simplest question that we could ask of our supervised classifier is "How many times did we predict the correct direction, as a percentage of all predictions?". This motivates the definition of thetraining hit rate is given by the following formula[9]: 1 nn∑ j=1I(yj= ˆyj) (11. 1) Where ˆyjis the prediction (up or down) for the jth time period (e. g. a day) using a particular classifier. I(yj= ˆyj)is theindicator function and is equal to 1 if yj= ˆyjand 0 ifyj̸= ˆyj. 97
98 Hence the hit rate provides a percentage value as to the number of times a classifier correctly predicted the up or down direction. Scikit-Learn provides a method to calculate the hit rate for us as part of the classification/-training process. 11. 1. 2 Confusion Matrix Theconfusion matrix (orcontingency table ) is the next logical step after calculating the hit rate. It is motivated by asking "How many times did we predict up correctly and how many times did we predict down correctly? Did they differ substantially?". For instance, it might turn out that a particular algorithm is consistently more accurate at predicting "down days". This motivates a strategy that emphasises shorting of a financial asset to increase profitability. A confusion matrix characterises this idea by determining the false positive rate (known statistically as a Type I error) and false negative rate (known statistically as a Type II error) for a supervised classifier. For the case of binary classification (up or down) we will have a 2x2 matrix: (UTUF DFDT) Where UTrepresents correctly classified up periods, UFrepresents incorrectly classified up periods (i. e. classified as down), DFrepresents incorrectly classified down periods (i. e. classified as up) and DTrepresents correctly classified down periods. In addition to the hit rate, Scikit-Learn provides a method to calculate the confusion matrix for us as part of the classification/training process. 11. 2 Factor Choice Oneofthemostcrucialaspectsofassetpriceforecastingischoosingthefactorsusedaspredictors. There are a staggering number of potential factors to choose and this can seem overwhelming to an individual unfamiliar with financial forecasting. However, even simple machine learning techniques will produce relatively good results when used with well-chosen factors. Note that the converse is not often the case. "Throwing an algorithm at a problem" will usually lead to poor forecasting accuracy. Factorchoiceiscarriedoutbytryingtodeterminethefundamentaldriversofassetmovement. In the case of the S&P500 it is clear that the 500 constituents, in a weighted manner, will be fundamental drivers of the price, by definition! Clearly we would know the exact price of the S&P500 series if we knew the instantaneous value of its constituents, but is there any predictive power in using the prior history of returns for each constituent in predicting the series itself? Alternatively, could we consider exchange rates with countries that carry out a lot of trade with the US as drivers of the price? We could even consider more fundamental economic and corporate factors such as interest rates, inflation, quarterly earnings. The accuracy of the forecaster will in large part be due to the skill of the modeller in deter-mining the right factors prior to carrying out model fitting. 11. 2. 1 Lagged Price Factors and Volume The first type of factor that is often considered in forecasting a time series are prior historical values of the time series itself. Thus a set of pfactors could be easily obtained by creating plags of the time series close price. Consider a daily time series. For each particular current day k, the factors would be the historical daily values at time periods k-1,k-2,...,k-p. In addition to the price series itself we can also incorporate traded volume as an indicator, since it is provided when using OHLCV data (as is obtained from Yahoo Finance, Google Finance or Quandl for instance). Thus we can create a p+ 1-dimensional feature vector for each day of the time series, which incorporates the ptime lags and the volume series. This naturally leads
99 to a set of pairs (Xk,yk)representing the p+ 1-dimensional feature vector Xkat daykand the actual current closing price on day k,yk. This is all we need to begin a supervised classification exercise. Below we will consider such a lagged time series for the S&P500 and apply multiple machine learning techniques to see if we can forecast its direction. 11. 2. 2 External Factors Whilelaggedtimeseriesandvolumeinformationareagoodstartingpointfortimeseriesanalysis, we are far from restricted to such data. There are a vast amount of macroeconomic time series and asset prices series on which to consider forecasts. For instance we may wish to provide a long-termforecastofcommoditiespricesbasedonweatherpatterns, orascertainforeignexchange price direction movements via international interest rate movements. If such a relationship between series can be ascertained and shown to be statistically signifi-cant, then we are at the point of being able to consider a robust trading model. We won't dwell on such relationships too much here, as our goal is to introduce the idea of modelling and ma-chine learning techniques. It is easy enough to form hypotheses about economic relationships and obtain the time series data either from a repository such as Quandl, or directly from government statistics websites. 11. 3 Classification Models Thefieldofmachinelearningisvastandtherearemanymodelstochoosefrom, particularlyinthe realm of supervised classification. New models are being introduced on a monthly basis through the academic literature. It would be impractical to provide an exhaustive list of supervised classifiers in this chapter, rather we will consider some of the more popular techniques from the field. 11. 3. 1 Logistic Regression The first technique we will consider is logistic regression (LR). In our case we are going to use logistic regression to measures the relationship between a binary categorical dependent variable (i. e. "up" or "down" periods) and multiple independent continuous variables, such as the lagged percentage returns of a financial asset. Thelogisticregressionmodelprovidesthe probability thataparticularsubsequenttimeperiod will be categorised as "up" or "down". Thus the model introduces a parameter, namely the probability threshold for classifying whether a subsequent time period is "up" or "down". Below, we will take this threshold to be 50% (i. e. 0. 5), but it can certainly be modified to produce alternative predictions. Logistic regression is based on the logistic formula to model the probability of obtaining an "up" day (Y=U) based on the continuous factors. In this case, consider the situation where we are interested in predicting the subsequent time period from the previous two lagged returns, which we will denote by ( L1,L2). The formula below gives the probability for having an up day, given that we have observed the returns on the previous time periods, L1and L2: p(Y=U|L1,L2) =eβ0+β1L1+β2L2 1 +eβ0+β1L1+β2L2(11. 2) The logistic function is used instead of a linear function (i. e. in linear regression) because it provides a probability between [0,1]for all values of L1and L2. In a linear regression setting it is possible to obtain negative probabilities for these continuous variables so we need another function. To fit the model (i. e. estimate the βicoefficients) the maximum likelihood method is used. Fortunately for us the implementation of the fitting and prediction of the logistic regression
100 model is already handled by the Scikit-Learn library. The technique will be outlined below when we attempt to forecast the direction of the S&P500. 11. 3. 2 Discriminant Analysis Discriminant analysis is an alternative statistical technique to logistic regression. While logistic regression is less restrictive in its assumptions than discriminant analysis, it can give greater predictive performance if the more restrictive assumptions are met. We will now consider a linear method and a non-linear method of discriminant analysis. Linear Discriminant Analysis In logistic regression we model the probability of seeing an "up" time period, given the previous two lagged returns ( P(Y=U|L1,L2)) as a conditional distribution of the response Ygiven the predictors Li, using a logistic function. In Linear Discriminant Analysis (LDA) the distribution of the Livariables are modelled separately, given Y, and P(Y=U|L1,L2)is obtained via Bayes' Theorem. Essentially, LDA results from assuming that predictors are drawn from a multivariate Gaus-sian distribution. After calculating estimates for the parameters of this distribution, the param-eters can be inserted into Bayes' Theorem in order to make predictions about which class an observation belongs to. One important mathematical assumption of LDA is that all classes(e. g. "up" and "down") share the same covariance matrix. I won't dwell on the formulae for estimating the distribution or posterior probabilities that are needed to make predictions, as once again scikit-learn handles this for us. Quadratic Discriminant Analysis Quadratic Discriminant Analysis (QDA) is closely reed to LDA. The significant difference is that each class can now possess its own covariance matrix. QDA generally performs better when the decision boundaries are non-linear. LDA generally performsbetterwhentherearefewertrainingobservations(i. e. whenneedingtoreducevariance). QDA, on the other hand, performs well when the training set is large (i. e. variance is of less concern). The use of one or the other ultimately comes down to the bias-variance trade-off. As with LR and LDA, Scikit-Learn takes care of the QDA implementation so we only need to provide it with training/test data for parameter estimation and prediction. 11. 3. 3 Support Vector Machines In order to motivate Support Vector Machines (SVM) we need to consider the idea of a classi-fier that separates different classes via a linear separating boundary. If such a straightforward separation existed then we could create a supervised classifier solely based on deciding whether new features lie above or below this linear classifying plane. In reality, such separations rarely exist in quantitative trading situations and as such we need to consider soft margin classifiers or Support Vector Classifiers (SVC). SVCs work by attempting to locate a linear separation boundary in feature space that cor-rectly classifies most, but not all, of the training observations by creating an optimal separation boundary between the two classes. Sometimes such a boundary is quite effective if the class separation is mostly linear. However, other times such separations are not possible and it is necessary to utilise other techniques. The motivation behind the extension of a SVC is to allow non-linear decision boundaries. This is the domain of the Support Vector Machine (SVM). The major advantage of SVMs is that they allow a non-linear enlargening of the feature space to include significant non-linearity, while still retaining a significant computational efficiency, using a process known as the "kernel trick". SVMs allow non-linear decision boundaries via many different choices of "kernel". In partic-ular, instead of using a fully linear separating boundary as in the SVC, we can use quadratic
101 polynomials, higher-order polynomials or even radial kernals to describe non-linear boundaries. Thisgivesusasignificantdegreeofflexibility, attheever-presentexpenseofbiasinourestimates. We will use the SVM below to try and partition feature space (i. e. the lagged price factors and volume) via a non-linear boundary that allows us to make reasonable predictions about whether the subsequent day will be an up move or a down move. 11. 3. 4 Decision Trees and Random Forests Decision trees are a supervised classification technique that utilise a tree structure to partition the feature space into recursive subsets via a "decision" at each node of the tree. For instance one could ask if yesterday's price was above or below a certain threshold, which immediately partitions the feature space into two subsets. For each of the two subsets one could then ask whether the volume was above or below a threshold, thus creating four separate subsets. This process continues until there is no more predictive power to be gained by partitioning. A decision tree provides a naturally interpretable classification mechanism when compared to the more "black box" opaque approaches of the SVM or discriminant analysers and hence are a popular supervised classification technique. Ascomputationalpowerhasincreased,anewmethodofattackingtheproblemofclassification has emerged, that of ensemble learning. The basic idea is simple. Create a large quantity of classifiers from the same base model and train them all with varying parameters. Then combine the results of the prediction in an average to hopefully obtain a prediction accuracy that is greater than that brought on by any of the individual constituents. One of the most widespread ensemble methods is that of a Random Forest, which takes multiple decision tree learners (usually tens of thousands or more) and combines the predic-tions. Such ensembles can often perform extremely well. Scikit-Learn handily comes with a Random Forest Classifier (RFC) class in its ensemble module. The two main parameters of interest for the RFC are n_estimators, which describes how many decision trees to create, and n_jobs, which describes how many processing cores to spread the calculations over. We will discuss these settings in the implementation section below. 11. 3. 5 Principal Components Analysis All of the above techniques outlined above belong in the supervised classification domain. An alternative approach to performing classification is to not supervise the training procedure and instead allow an algorithm to ascertain "features" on its own. Such methods are known as unsupervised learning techniques. Common use cases for unsupervised techniques include reducing the number of dimensions of a problem to only those considered important, discovering topics among large quantities of text documents or discovering features that may provide predictive power in time series analysis. Of interest to us in this section is the concept of dimensionality reduction, which aims to identifythemostimportantcomponentsinasetoffactorsthatprovidethemostpredictability. In particular we are going to utilise an unsupervised technique known as Principal Components Analysis (PCA) to reduce the size of the feature space prior to use in our supervised classifiers. The basic idea of a PCA is to transform a set of possibly correlated variables (such as with time series autocorrelation) into a set of linearly uncorrelated variables known as the principal components. Such principal components are ordered according to the amount of variance they describe, in an orthogonal manner. Thus if we have a very high-dimensional feature space (10+ features), then we could reduce the feature space via PCA to perhaps 2 or 3 principal components that provide nearly all of the variability in the data, thus leading to a more robust supervised classifier model when used on this reduced dataset. 11. 3. 6 Which Forecaster? In quantitative financial situations where there is an abundance of training data one should consider using a model such as a Support Vector Machine (SVM). However, SVMs suffer from lack of interpretibility. This is not the case with Decision Trees and Random Forest ensembles.
102 The latter are often used to preserve interpretability, something which "black box" classifiers such as SVM do not provide. Ultimately when the data is so extensive (e. g. tick data) it will matter very little which classifier is ultimately used. At this stage other factors arise such as computational efficiency and scalability of the algorithm. The broad rule-of-thumb is that a doubling of training data will provide a linear increase in performance, but as the data size becomes substantial, this improvement reduces to a sublinear increase in performance. The underlying statistical and mathematical theory for supervised classifiers is quite involved, but the basic intuition on each classifier is straightforward to understand. Also-note that each of the following classifiers will have a different set of assumptions as to when they will work best, so if you find a classifier performing poorly, it may be because the data-set being used violates one of the assumptions used to generate the theory. Naive Bayes Classifier While we haven't considered a Naive Bayes Classifier in our examples above, I wanted to include a discussion on it for completeness. Naive Bayes (specifically Multinomial Naive Bayes-MNB) is good to use when a limited data set exists. This is because it is a high-bias classifier. The major assumption of the MNB classifier is that of conditional independence. Essentially this means that it is unable to discern interactions between individual features, unless they are specifically added as extra features. For example, consider a document classification situation, which appears in financial settings when trying to carry out sentiment analysis. The MNB could learn that individual words such as "cat"and"dog"couldrespectivelyrefertodocumentspertainingtocatsanddogs, butthephrase "cats and dogs" (British slang for raining heavily) would not be considered to be meteorological by the classifier! The remedy to this would be to treat "cats and dogs" as an extra feature, specifically, and then associate that to a meteorological category. Logistic Regression Logistic regression provides some advantages over a Naive Bayes model in that there is less concern about correlation among features and, by the nature of the model, there is a probabilistic interpretation to the results. This is best suited to an environment where it is necessary to use thresholds. For instance, we might wish to place a threshold of 80% (say) on an "up" or "down" result in order for it to be correctly selected, as opposed to picking the highest probability category. In the latter case, the prediction for "up" could be 51% and the prediction for "down" could be 49%. Setting the category to "up" is not a very strong prediction in this instance. Decision Tree and Random Forests Decision trees (DT) partition a space into a hierarchy of boolean choices that lead to a categori-sation or grouping based on the the respective decisions. This makes them highly interpretable (assuming a "reasonable" number of decisions/nodes in the tree!). DT have many benefits, including the ability to handle interactions between features as well as being non-parametric. Theyarealsousefulincaseswhereitisnotstraightforward(orimpossible)tolinearlyseparate data into classes (which is a condition required of support vector machines). The disadvantage of using individual decision trees is that they are prone to overfitting (high variance). This problem is solved using a random forest. Random forests are actually some of the "best" classifiers when used in machine learning competitions, so they should always be considered. Support Vector Machine Support Vector Machines (SVM), while possessing a complicated fitting procedure, are actually relatively straightforward to understand. Linear SVMs essentially try to partition a space using linear separation boundaries, into multiple distinct groups. For certain types of data this can workextremelywellandleadstogoodpredictions. However, alotofdataisnotlinearly-separable and so linear SVMs can perform poorly here.
103 The solution is to modify the kernel used by the SVM, which has the effect of allowing non-linear decision boundaries. Thus they are quite flexible models. However, the right SVM boundary needs to be chosen for the best results. SVM are especially good in text classification problems with high dimensionality. They are disadvantaged by their computational complexity, difficulty of tuning and the fact the the fitted model is difficult to interpret. 11. 4 Forecasting Stock Index Movement The S&P500 is a weighted index of the 500 largest publicly traded companies by market capi-talisation in the US stock market. It is often utilised as an equities benchmark. Many derivative products exist in order to allow speculation or hedging on the index. In particular, the S&P500 E-Mini Index Futures Contract is an extremely liquid means of trading the index. In this section we are going to use a set of classifiers to predict the direction of the closing price at day kbased solely on price information known at day k-1. An upward directional move means that the closing price at kis higher than the price at k-1, while a downward move implies a closing price at klower than at k-1. If we can determine the direction of movement in a manner that significantly exceeds a 50% hit rate, with low error and a good statistical significance, then we are on the road to forming a basic systematic trading strategy based on our forecasts. 11. 4. 1 Python Implementations Fortheimplementationoftheseforecasterswewillmakeuseof Num Py, Pandasand Scikit-Learn, which were installed in the previous chapters. The first step is to import the relevant modules and libraries. We're going to import the Logistic Regression, LDA, QDA, Linear SVC (a linear Support Vector Machine), SVC (a non-linear Support Vector Machine) and Random Forest classifiers for this forecast: #!/usr/bin/python #-*-coding: utf-8-*-# forecast. py from __future __import print _function import datetime import numpy as np import pandas as pd import sklearn from pandas. io. data import Data Reader from sklearn. ensemble import Random Forest Classifier from sklearn. linear _model import Logistic Regression from sklearn. lda import LDA from sklearn. metrics import confusion _matrix from sklearn. qda import QDA from sklearn. svm import Linear SVC, SVC Now that the libraries are imported, we need to create a pandas Data Frame that contains the laggedpercentagereturnsforapriornumberofdays(defaultingtofive). create _lagged _series will take a stock symbol (as recognised by Yahoo Finance) and create a lagged Data Frame across the period specified. The code is well commented so it should be straightforward to see what is going on: def create _lagged _series(symbol, start _date, end _date, lags=5): """ This creates a Pandas Data Frame that stores the
104 percentage returns of the adjusted closing value of a stock obtained from Yahoo Finance, along with a number of lagged returns from the prior trading days (lags defaults to 5 days). Trading volume, as well as the Direction from the previous day, are also included. """ # Obtain stock information from Yahoo Finance ts = Data Reader( symbol, "yahoo", start _date-datetime. timedelta(days=365), end_date ) # Create the new lagged Data Frame tslag = pd. Data Frame(index=ts. index) tslag["Today"] = ts["Adj Close"] tslag["Volume"] = ts["Volume"] # Create the shifted lag series of prior trading period close values for iinrange(0, lags): tslag["Lag%s" % str(i+1)] = ts["Adj Close"]. shift(i+1) # Create the returns Data Frame tsret = pd. Data Frame(index=tslag. index) tsret["Volume"] = tslag["Volume"] tsret["Today"] = tslag["Today"]. pct _change() *100. 0 # If any of the values of percentage returns equal zero, set them to # a small number (stops issues with QDA model in Scikit-Learn) for i,x inenumerate(tsret["Today"]): if(abs(x) < 0. 0001): tsret["Today"][i] = 0. 0001 # Create the lagged percentage returns columns for iinrange(0, lags): tsret["Lag%s" % str(i+1)] = \ tslag["Lag%s" % str(i+1)]. pct _change() *100. 0 # Create the "Direction" column (+1 or-1) indicating an up/down day tsret["Direction"] = np. sign(tsret["Today"]) tsret = tsret[tsret. index >= start _date] return tsret We tie the classification procedure together with a __main __function. In this instance we're going to attempt to forecast the US stock market direction in 2005, using returns data from 2001 to 2004. Firstly we create a lagged series of the S&P500 using five lags. The series also includes trading volume. However, we are going to restrict the predictor set to use only the first two lags. Thus we are implicitly stating to the classifier that the further lags are of less predictive value. As an aside, this effect is more concretely studied under the statistical concept of autocorrelation, although this is beyond the scope of the book. After creating the predictor array Xand the response vector y, we can partition the arrays into atraining and atestset. The former subset is used to actually train the classifier, while the latter is used to actually test the performance. We are going to split the training and testing set on the 1st January 2005, leaving a full trading years worth of data (approximately 250 days) for
105 the testing set. Once we create the training/testing split we need to create an array of classification models, each of which is in a tuple with an abbreviated name attached. While we have not set any param-eters for the Logistic Regression, Linear/Quadratic Discriminant Analysers or Linear Support Vector Classifier models, we have used a set of default parameters for the Radial Support Vector Machine (RSVM) and the Random Forest (RF). Finally we iterate over the models. We train (fit) each model on the training data and then make predictions on the testing set. Finally we output the hit rate and the confusion matrix for each model: if__name __== " __main __": # Create a lagged series of the S&P500 US stock market index snpret = create _lagged _series( "^GSPC", datetime. datetime(2001,1,10), datetime. datetime(2005,12,31), lags=5 ) # Use the prior two days of returns as predictor # values, with direction as the response X = snpret[["Lag1","Lag2"]] y = snpret["Direction"] # The test data is split into two parts: Before and after 1st Jan 2005. start _test = datetime. datetime(2005,1,1) # Create training and test sets X_train = X[X. index < start _test] X_test = X[X. index >= start _test] y_train = y[y. index < start _test] y_test = y[y. index >= start _test] # Create the (parametrised) models print ("Hit Rates/Confusion Matrices:\n") models = [("LR", Logistic Regression()), ("LDA", LDA()), ("QDA", QDA()), ("LSVC", Linear SVC()), ("RSVM", SVC( C=1000000. 0, cache _size=200, class _weight=None, coef0=0. 0, degree=3, gamma=0. 0001, kernel='rbf', max_iter=-1, probability=False, random _state=None, shrinking=True, tol=0. 001, verbose=False) ), ("RF", Random Forest Classifier( n_estimators=1000, criterion='gini', max_depth=None, min _samples _split=2, min_samples _leaf=1, max _features='auto', bootstrap=True, oob _score=False, n _jobs=1, random _state=None, verbose=0) )] # Iterate through the models for min models : # Train each of the models on the training set m[1]. fit(X _train, y _train)
106 # Make an array of predictions on the test set pred = m[1]. predict(X _test) # Output the hit-rate and the confusion matrix for each model print ("%s:\n%0. 3f" % (m[0], m[1]. score(X _test, y _test))) print ("%s\n" % confusion _matrix(pred, y _test)) 11. 4. 2 Results The output from all of the classification models is as follows. You will likely see different values on the RF (Random Forest) output as it is inherently stochastic in its construction: Hit Rates/Confusion Matrices: LR: 0. 560 [[ 35 35] [ 76 106]] LDA: 0. 560 [[ 35 35] [ 76 106]] QDA: 0. 599 [[ 30 20] [ 81 121]] LSVC: 0. 560 [[ 35 35] [ 76 106]] RSVM: 0. 563 [[ 9 8] [102 133]] RF: 0. 504 [[48 62] [63 79]] Note that all of the hit rates lie between 50% and 60%. Thus we can see that the lagged variables are not hugely indicative of future direction. However, if we look at the quadratic discriminant analyser we can see that its overall predictive performance on the test set is just under 60%. The confusion matrix for this model (and the others in general) also states that the true positive rate for the "down" days is much higher than the "up" days. Thus if we are to create a trading strategy based off this information we could consider restricting trades to short positions of the S&P500 as a potential means of increasing profitability. In later chapters we will use these models as a basis of a trading strategy by incorporating them directly into the event-driven backtesting framework and using a direct instrument, such as an exchange traded fund (ETF), in order to give us access to trading the S&P500.
Part V Performance and Risk Management 107
Chapter 12 Performance Measurement Performance measurement is an absolutely crucial component of algorithmic trading. Without assessment of performance, along with solid record keeping, it is difficult, if not impossible, to determine if our strategy returns have been due to luck or due to some actual edge over the market. In order to be successful in algorithmic trading it is necessary to be aware of all of the factors that can affect the profitability of trades, and ultimately strategies. We should be constantly tryingtofindimprovementsinallaspectsofthealgorithmictradingstack. Inparticularweshould always be trying to minimise our transaction costs (fees, commission and slippage), improve our software and hardware, improve the cleanliness of our data feeds and continually seek out new strategies to add to a portfolio. Performance measurement in all these areas provides a yardstick upon which to measure alternatives. Ultimately, algorithmic trading is about generating profits. Hence it is imperative that we measure the performance, at multiple levels of granularity, of how and why our system is pro-ducing these profits. This motivates performance assessment at the level of trades, strategies and portfolios. In particular we are looking out for: Whether the systematic rules codified by the strategy actually produce a consistent return and whether the strategy possesses positive performance in the backtests. Whetherastrategymaintainsthispositiveperformanceinaliveimplementationorwhether it needs to be retired. The ability to compare multiple strategies/portfolios such that we can reduce the opportu-nity cost associated with allocating a limited amount of trading capital. The particular items of quantitative analysis of performance that we will be interested in are as follows: Returns-The most visible aspect of a trading strategy concerns the percentage gain since inception, either in a backtest or a live trading environment. The two major performance measures here are Total Return and Compound Annual Growth Rate (CAGR). Drawdowns-Adrawdown is a period of negative performance, as defined from a prior high-water mark, itself defined as the previous highest peak on a strategy or portfolio equity curve. We will define this more concretely below, but you can think of it for now as a (somewhat painful!) downward slope on your performance chart. Risk-Risk comprises many areas, and we'll spend significant time going over them in the following chapter, but generally it refers to both risk of capital loss, such as with drawdowns, and volatility of returns. The latter usually being calculated as an annualised standard deviation of returns. Risk/Reward Ratio-Institutional investors are mainly interested with risk-adjusted returns. Since higher volatility can often lead to higher returns at the expense of greater 109
110 drawdowns, they are always concerned with how much risk is being taken on per unit of return. Consequently a range of performance measures have been invented to quantify this aspect of strategy performance, namely the Sharpe Ratio, Sortino Ratio and CALMAR Ratio, among others. The out of sample Sharpe is often the first metric to be discussed by institutional investors when discussing strategy performance. Trade Analysis-The previous measures of performance are all applicable to strategies andportfolios. It is also instructive to look at the performance of individual trades and many measures exist to characterise their performance. In particular, we will quantity the number of winning/losing trades, mean profit per trade and win/loss ratio among others. Trades are the most granular aspect of an algorithmic strategy and hence we will begin by discussing trade analysis. 12. 1 Trade Analysis The first step in analysing any strategy is to consider the performance of the actual trades. Such metrics can vary dramatically between strategies. A classic example would be the difference in performance metrics of a trend-following strategy when compared to a mean-reverting strategy. Trend-following strategies usually consist of many losing trades, each with a likely small loss. The lesser quantity of profitable trades occur when a trend has been established and the performance from these positive trades can significantly exceed the losses of the larger quantity of losing trades. Pair-trading mean-reverting strategies display the opposing character. They generally consist of many small profitable trades. However, if a series does not mean revert in the manner expected then the long/short nature of the strategy can lead to substantial losses. This could potentially wipe out the large quantity of small gains. It is essential to be aware of the nature of the trade profile of the strategy and your own psychological profile, as the two will need to be in alignment. Otherwise you will find that you may not be able to persevere through a period of tough drawdown. We now review the statistics that are of interest to us as the trade level. 12. 1. 1 Summary Statistics When considering our trades, we are interested in the following set of statistics. Here "period" refers to the time period covered by the trading bar containing OHLCV data. For long-term strategies it is often the case that daily bars are used. For higher frequency strategies we may be interested in hourly or minutely bars. Total Profit/Loss (Pn L)-The total Pn L straightforwardly states whether a particular trade has been profitable or not. Average Period Pn L-The avg. period Pn L states whether a bar, on average, generates a profit or loss. Maximum Period Profit-The largest bar-period profit made by this trade so far. Maximum Period Loss-The largest bar-period loss made by this trade so far. Note that this says nothing about future maximum period loss! A future loss could be much larger than this. Average Period Profit-The average over the trade lifetime of all profitable periods. Average Period Loss-The average over the trade lifetime of all unprofitable periods. Winning Periods-The count of all winning periods. Losing Periods-The count of all losing periods. Percentage Win/Loss Periods-The percentage of all winning periods to losing periods. Will differ markedly for trend-following and mean-reverting type strategies.
111 Thankfully, it is straightforward to generate this information from our portfolio output and so the need for manual record keeping is completely eliminated. However, this leads to the danger that we never actually stop to analyse the data! It is imperative that trades are evaluated at least once or twice a month. Doing so is a useful early warning detection system that can help identify when strategy performance begins to degrade. It is often much better than simply considering the cumulative Pn L alone. 12. 2 Strategy and Portfolio Analysis Trade-level analysis is extremely useful in longer-term strategies, particularly with strategies that employ complex trades, such as those that involve derivatives. For higher-frequency strategies, we will be less interested in any individual trade and instead will want to consider the perfor-mance measures of the strategy instead. Obviously for longer-term strategies, we are equally as interested in the overall strategy performance. We are primarily interested in the following three key areas: Returns Analysis-The returns of a strategy encapsulate the concept of profitability. In institutional settings they are generally quoted net of fees and so provide a true picture of how much money was made on money invested. Returns can be tricky to calculate, especially with cash inflows/outflows. Risk/Reward Analysis-Generally the first consideration that external investors will have in a strategy is its out of sample Sharpe Ratio (which we describe below). This is an industry standard metric which attempts to characterise how much return was achieved per unit of risk. Drawdown Analysis-In an institutional setting, this is probably the most important of the three aspects. The profile and extent of the drawdowns of a strategy, portfolio or fund form a key component in risk management. We'll define drawdowns below. Despite the fact that I have emphasised their institutional performance, as a retail trader these are still highly important metrics and with suitable risk management (see next chapter) will form the basis of a continual strategy evalation procedure. 12. 2. 1 Returns Analysis The most widely quoted figures when discussing strategy performance, in both institutional and retail settings, are often total return,annual returns andmonthly returns. It is extremely common to see a hedge fund performance newsletter with a monthly return "grid". In addition, everybody will want to know what the "return" of the strategy is. Total return is relatively straightforward to calculate, at least in a retail setting with no external investors or cash inflows/outflows. In percentage terms it is simply calculated as: rt= (Pf-Pi)/Pi×100 (12. 1) Wherertis the total return, Pfis the final portfolio dollar value and Piis the initial portfolio value. We are mostly interested in nettotal return, that is the value of the portfolio/fund after all trading/business costs have been deducted. Note that this formula is only applicable to long-only un-leveraged portfolios. If we wish to add in short selling or leverage we need to modify how we calculate returns because we are technically trading on a larger borrowed portfolio than that used here. This is known as a margin portfolio. For instance, consider the case where a trading strategy has gone long 1,000 USD of one asset and then shorted 1,000 USD of another asset. This is a dollar-neutral portfolio and the total notional traded is 2,000 USD. If 200 USD was generated from this strategy then gross return on this notional is 10%. It becomes more complex when you factor in borrowing costs and interest rates to fund the margin. Factoring in these costs leads to the net total return, which is the value that is often quoted as "total return".
112 Equity Curve The equity curve is often one of the most emphasised visualisations on a hedge fund performance report-assuming the fund is doing well! It is a plot of the portfolio value of the fund over time. In essence it is used to show how the account has grown since fund inception. Equally, in a retail setting it is used to show growth of account equity through time. See Fig 12. 2. 1 for a typical equity curve plot: Figure 12. 1: Typical intraday strategy equity curve What is the benefit of such a plot? In essence it gives a "flavour" as to the past volatility of the strategy, as well as a visual indication of whether the strategy has suffered from prolonged periods of plateau or even drawdown. It essentially provides answers as to how the total return figure calculated at the end of the strategy trading period was arrived at. In an equity curve we are seeking to determine how unusual historical events have shaped the strategy. For instance, a common question asks if there was excess volatility in the strategy around 2008. Another question might concern its consistency of returns. One must be extremely careful with interpretation of equity curves as when marketed they are generally shown as "upward sloping lines". Interesting insight can be gained via truncation of such curves, which can emphasise periods of intense volatility or prolonged drawdown that may otherwise not seem as severe when considering the whole time period. Thus an equity curve needs to be considered in context with other analysis, in particular risk/reward analysis and drawdown analysis. 12. 2. 2 Risk/Reward Analysis As we alluded to above the concept of risk-to-reward analysis is extremely important in an institutional setting. This does not mean that as a retail investor we can ignore the concept. You should pay significant attention to risk/reward metrics for your strategy as they will have a significant impact on your drawdowns, leverage and overall compound growth rate.
113 These concepts will be expanded on in the next chapter on Risk and Money Management. For now we will discuss the common ratios, and in particular the Sharpe Ratio, which is ubiquitous as a comparative measure in quantitative finance. Since it is held in such high regard across institutionalised quantitative trading, we will go into a reasonable amount of detail. Sharpe Ratio Consider the situation where we are presented with two strategies possessing identical returns. How do we know which one contains more risk? Further, what do we even mean by "more risk"? In finance, we are often concerned with volatility of returns and periods of drawdown. Thus if one of these strategies has a significantly higher volatility of returns we would likely find it less attractive, despite the fact that its historical returns might be similar if not identical. These problems of strategy comparison and risk assessment motivate the use of the Sharpe Ratio. William Forsyth Sharpe is a Nobel-prize winning economist, who helped create the Capital Asset Pricing Model (CAPM) and developed the Sharpe Ratio in 1966 (later updated in 1994). The Sharpe Ratio Sis defined by the following relation: S=E(Ra-Rb)√ Var(Ra-Rb)(12. 2) Where Rais the period return of the asset or strategy and Rbis the period return of a suitable benchmark, such as a risk-free interest rate. The ratio compares the mean average of the excess returns of the asset or strategy with the standard deviation of those excess returns. Thus a lower volatility of returns will lead to a greater Sharpe ratio, assuming identical mean returns. The "Sharpe Ratio" often quoted by those carrying out trading strategies is the annualised Sharpe, the calculation of which depends upon the trading period of which the returns are measured. Assuming there are Ntrading periods in a year, the annualised Sharpe is calculated as follows: SA=√ NE(Ra-Rb)√ Var(Ra-Rb) Note that the Sharpe ratio itself MUST be calculated based on the Sharpe of that particular time period type. For a strategy based on trading period of days, N= 252(as there are 252 trading days in a year, not 365), and Ra,Rbmust be the daily returns. Similarly for hours N= 252×6. 5 = 1638, not N= 252×24 = 6048, since there are only 6. 5 hours in a trading day (at least for most US equities markets!). The formula for the Sharpe ratio above alludes to the use of a benchmark. A benchmark is used as a "yardstick" or a "hurdle" that a particular strategy must overcome for it to worth consideration. For instance, a simple long-only strategy using US large-cap equities should hope to beat the S&P500 index on average, or match it for less volatility, otherwise what is to be gained by not simply investing in the index at far lower management/performance fees? The choice of benchmark can sometimes be unclear. For instance, should a sector Exhange Traded Fund (ETF) be utilised as a performance benchmark for individual equities, or the S&P500 itself? Why not the Russell 3000? Equally should a hedge fund strategy be benchmark-ing itself against a market index or an index of other hedge funds? There is also the complication of the "risk free rate". Should domestic government bonds be used? A basket of international bonds? Short-term or long-term bills? A mixture? Clearly there are plenty of ways to choose a benchmark. The Sharpe ratio generally utilises the risk-free rate and often, for US equities strategies, this is based on 10-year government Treasury bills. In one particular instance, for market-neutral strategies, there is a particular complication regarding whether to make use of the risk-free rate or zero as the benchmark. The market index itself should not be utilised as the strategy is, by design, market-neutral. The correct choice for a market-neutral portfolio is not to substract the risk-free rate because it is self-financing. Since you gain a credit interest, Rf, from holding a margin, the actual calculation for returns
114 is:(Ra+Rf)-Rf=Ra. Hence there is no actual subtraction of the risk-free rate for dollar neutral strategies. Despite the prevalence of the Sharpe ratio within quantitative finance, it does suffer from some limitations. The Sharpe ratio is backward looking. It only accounts for historical returns distribution and volatility, not those occurring in the future. When making judgements based on the Sharpe ratio there is an implicit assumption that the past will be similar to the future. This is evidently not always the case, particular under market regime changes. The Sharperatiocalculationassumesthatthereturnsbeingusedarenormallydistributed(i. e. Gaussian ). Unfortunately, marketsoftensufferfromkurtosisabovethatofanormaldistribution. Essentially the distribution of returns has "fatter tails" and thus extreme events are more likely to occur than a Gaussian distribution would lead us to believe. Hence, the Sharpe ratio is poor at characterising tail risk. This can be clearly seen in strategies which are highly prone to such risks. For instance, the sale of call options aka "pennies under a steam roller". A steady stream of option premia are generated by the sale of call options over time, leading to a low volatility of returns, with a strong excess returns above a benchmark. In this instance the strategy would possess a high Sharpe ratio based on historical data. However, it does not take into account that such options may becalled, leading to significant drawdowns or even wipeout in the equity curve. Hence, as with any measure of algorithmic trading strategy performance the Sharpe ratio cannot be used in isolation. Although this point might seem obvious to some, transaction costs MUST be included in the calculation of Sharpe ratio in order for it to be realistic. There are countless examples of trading strategies that have high Sharpes, and thus a likelihood of great profitability, only to be reduced to low Sharpe, low profitability strategies once realistic costs have been factored in. This means making use of the net returns when calculating in excess of the benchmark. Hence transaction costs must be factored in upstream of the Sharpe ratio calculation. One obvious question that has remained unanswered thus far is "What is a good Sharpe Ratio for a strategy?". This is actually quite a difficult question to answer because each investor has a differing risk profile. The general rule of thumb is that quantitative strategies with annualised Sharpe Ratio S < 1should not often be considered. However, there are exceptions to this, particularly in the trend-following futures space. Quantitative funds tend to ignore any strategies that possess a Sharpe ratios S < 2. One prominent quantitative hedge fund that I am familiar with wouldn't even consider strategies that had Sharpe ratios S <3while in research. As a retail algorithmic trader, if you can achieve an out of sample (i. e. live trading!) Sharpe ratio S >2then you are doing very well. The Sharpe ratio will often increase with trading frequency. Some high frequency strategies will have high single (and sometimes low double) digit Sharpe ratios, as they can be profitable almost every day and certainly every month. These strategies rarely suffer from catastrophic risk (in the sense of great loss) and thus minimise their volatility of returns, which leads to such high Sharpe ratios. Be aware though that high-frequency strategies such as these can simply cease to function very suddenly, which is another aspect of risk not fully reflected in the Sharpe ratio. Let's now consider some actual Sharpe examples. We will start simply, by considering a long-only buy-and-hold of an individual equity then consider a market-neutral strategy. Both of these examples have been carried out with Pandas. The first task is to actually obtain the data and put it into a Pandas Data Frame object. In the prior chapter on securities master implementation with Python and My SQL we created a system for achieving this. Alternatively, we can make use of this simpler code to grab Google Finance data directly and put it straight into a Data Frame. At the bottom of this script I have created a function to calculate the annualised Sharpe ratio based on a time-period returns stream: #!/usr/bin/python #-*-coding: utf-8-*-# sharpe. py from __future __import print _function
115 import datetime import numpy as np import pandas as pd import pandas. io. data as web def annualised _sharpe(returns, N=252): """ Calculate the annualised Sharpe ratio of a returns stream based on a number of trading periods, N. N defaults to 252, which then assumes a stream of daily returns. The function assumes that the returns are the excess of those compared to a benchmark. """ return np. sqrt(N) *returns. mean() / returns. std() Now that we have the ability to obtain data from Google Finance and straightforwardly calculate the annualised Sharpe ratio, we can test out a buy and hold strategy for two equities. We will use Google (GOOG) from Jan 1st 2000 to Jan 1st 2013. We can create an additional helper function that allows us to quickly see buy-and-hold Sharpe across multiple equities for the same (hardcoded) period: def equity _sharpe(ticker): """ Calculates the annualised Sharpe ratio based on the daily returns of an equity ticker symbol listed in Google Finance. The dates have been hardcoded here for brevity. """ start = datetime. datetime(2000,1,1) end = datetime. datetime(2013,1,1) # Obtain the equities daily historic data for the desired time period # and add to a pandas Data Frame pdf = web. Data Reader(ticker, 'google', start, end) # Use the percentage change method to easily calculate daily returns pdf['daily _ret'] = pdf['Close']. pct _change() # Assume an average annual risk-free rate over the period of 5% pdf['excess _daily _ret'] = pdf['daily _ret']-0. 05/252 # Return the annualised Sharpe ratio based on the excess daily returns return annualised _sharpe(pdf['excess _daily _ret']) For Google, the Sharpe ratio for buying and holding is 0. 703: >>> equity _sharpe('GOOG') 0. 70265563285799615 Now we can try the same calculation for a market-neutral strategy. The goal of this strategy is to fully isolate a particular equity's performance from the market in general. The simplest way to achieve this is to go short an equal amount (in dollars) of an Exchange Traded Fund (ETF) that is designed to track such a market. The most obvious choice for the US large-cap equities market is the S&P500 index, which is tracked by the SPDR ETF, with the ticker of SPY. To calculate the annualised Sharpe ratio of such a strategy we will obtain the historical prices for SPY and calculate the percentage returns in a similar manner to the previous stocks, with
116 the exception that we will not use the risk-free benchmark. We will calculate the net daily returnswhich requires subtracting the difference between the long and the short returns and then dividing by 2, as we now have twice as much trading capital. Here is the Python/pandas code to carry this out: def market _neutral _sharpe(ticker, benchmark): """ Calculates the annualised Sharpe ratio of a market neutral long/short strategy inolving the long of 'ticker' with a corresponding short of the 'benchmark'. """ start = datetime. datetime(2000, 1, 1) end = datetime. datetime(2013, 1, 1) # Get historic data for both a symbol/ticker and a benchmark ticker # The dates have been hardcoded, but you can modify them as you see fit! tick = web. Data Reader(ticker, 'google', start, end) bench = web. Data Reader(benchmark, 'google', start, end) # Calculate the percentage returns on each of the time series tick['daily _ret'] = tick['Close']. pct _change() bench['daily _ret'] = bench['Close']. pct _change() # Create a new Data Frame to store the strategy information # The net returns are (long-short)/2, since there is twice # the trading capital for this strategy strat = pd. Data Frame(index=tick. index) strat['net _ret'] = (tick['daily _ret']-bench['daily _ret'])/2. 0 # Return the annualised Sharpe ratio for this strategy return annualised _sharpe(strat['net _ret']) For Google, the Sharpe ratio for the long/short market-neutral strategy is 0. 832: >>> market _neutral _sharpe('GOOG', 'SPY') 0. 83197496084314604 We will now briefly consider other risk/reward ratios. Sortino Ratio The Sortino ratio is motivated by the fact that the Sharpe ratio captures both upward and downward volatility in its denominator. However, investors (and hedge fund managers) are generally not too bothered when we have significant upward volatility! What is actually of interest from a risk management perspective is downward volatility and periods of drawdown. Thus the Sortino ratio is defined as the mean excess return divided by the mean downside deviation: Sortino =E(Ra-Rb)√ Var(Ra-Rb)d(12. 3) The Sortino is sometimes quoted in an institutional setting, but is certainly not as prevalent as the Sharpe ratio. CALMAR Ratio One could also argue that investors/traders are concerned solely with the maximum extent of the drawdown, rather than the average drawdown. This motivates the CALMAR (CALifornia
117 Managed Accounts Reports) ratio, also known as the Drawdown ratio, which provides a ratio of mean excess return to the maximum drawdown: CALMAR =E(Ra-Rb) max. drawdown(12. 4) Once again, the CALMAR is not as widely used as the Sharpe ratio. 12. 2. 3 Drawdown Analysis In my opinion the concept of drawdown is the most important aspect of performance measure-ment for an algorithmic trading system. Simply put, if your account equity is wiped out then none of the other performance metrics matter! Drawdown analysis concerns the measurement of drops in account equity from previous high water marks. A high water mark is defined as the last account equity peak reached on the equity curve. In an institutional setting the concept of drawdown is especially important as most hedge funds are remunerated only when the account equity is continually creating new high water marks. That is, a fund manager is not paid a performance fee while the fund remains "under water", i. e. the account equity is in a period of drawdown. Most investors would be concerned at a drawdown of 10% in a fund, and would likely redeem their investment once a drawdown exceeds 30%. In a retail setting the situation is very different. Individuals are likely to be able to suffer deeper drawdowns in the hope of gaining higher returns. Maximum Drawdown and Duration The two key drawdown metrics are the maximum drawdown and thedrawdown duration. The first describes the largest percentage drop from a previous peak to the current or previous trough in account equity. It is often quoted in an institutional setting when trying to market a fund. Retail traders should also pay significant attention to this figure. The second describes the actual duration of the drawdown. This figure is usually quoted in days, but higher frequency strategies might use a more granular time period. In backtests these measures provide someidea of how a strategy mightperform in the future. Theoverallaccountequitycurvemightlookquiteappealingafteracalculatedbacktest. However, anupwardequitycurvecaneasilymaskhowdifficultpreviousperiodsofdrawdownmightactually have been to experience. When a strategy begins dropping below 10% of account equity, or even below 20%, it requires significant willpower to continue with the strategy, despite the fact that the strategy may have historically, at least in the backtests, been through similar periods. This is a consistent issue with algorithmic trading and systematic trading in general. It naturally motivates the need to set prior drawdown boundaries and specific rules, such as an account-wide "stop loss" that will be carried out in the event of a drawdown breaching these levels. Drawdown Curve While it is important to be aware of the maximum drawdown and drawdown duration, it is significantly more instructive to see a time series plot of the strategy drawdown over the trading duration. Fig 12. 2. 3 quite clearly shows that this particular strategy suffered from a relatively sustained period of drawdown beginning in Q3 of 2010 and finishing in Q2 of 2011, reaching a maximum drawdown of 14. 8%. While the strategy itself continued to be significantly profitable over the long term, this particular period would have been very difficult to endure. In addition, this is the maximum historical drawdown that has occured to date. The strategy may be subject to an even greater drawdown in the future. Thus it is necessary to consider drawdown curves, as with other historical looking performance measures, in the context with which they have been generated, namely via historical, and not future, data.
118 Figure 12. 2: Typical intraday strategy drawdown curve In the following chapter we will consider the concept of quantitative risk management and describe techniques that can help us to minimise drawdowns and maximise returns, all the while keeping to a reasonable degree of risk.
Chapter 13 Risk and Money Management This chapter is concerned with managing risk as applied to quantitative trading strategies. This usually comes in two flavours, firstly identifying and mitigating internal and external factors that can affect the performance or operation of an algorithmic trading strategy and secondly, how to optimally manage the strategy portfolio in order to maximise growth rate and minimise account drawdowns. In the first section we will consider different sources of risk (both intrinsic and extrinsic) that might affect the long-term performance of an algorithmic trading business-either retail or institutional. In the second section we will look at money management techniques that can simultaneously protect our portfolio from ruin and also attempt to maximise the long-term growth rate of equity. In the final section we consider institutional-level risk management techniques that can easily be applied in a retail setting to help protect trading capital. 13. 1 Sources of Risk The are numerous sources of risk that can have an impact on the correct functioning of an algorithmic trading strategy. "Risk" is usually defined in this context to mean chance of account losses. However, I am going to define it in a much broader context to mean any factor that provides a degree of uncertainty and could affect the performance of our strategies or portfolio. The broad areas of risk that we will consider include Strategy Risk,Portfolio Risk, Market Risk,Counterparty Risk and Operational Risk. 13. 1. 1 Strategy Risk Strategy risk, or model risk, encompasses the class of risks that arise from the design and imple-mentation of a trading strategy based on a statistical model. It includes all of the previous issues we have discussed in the Successful Backtesting chapter, such as curve-fitting, survivorship bias and look-ahead bias. It also includes other topics related directly to the statistical analysis of the strategy model. Any statistical model is based on assumptions. These assumptions are sometimes not consid-ered in proper depth or ignored entirely. This means that the statistical model based upon these assumptions may be inappropriate and hence lead to poor predictive or inferential capability. A general example occurs in the setting of linear regression. Linear regression makes the assump-tion that the response data are homoscedastic (i. e. the responses have a constant variance in their errors). If this is not the case then linear regression provides less precision in the estimates of parameters. Many quantitative strategies make use of descriptive statistics of historical price data. In particular, they will often use moments of the data such as the mean, variance, skew and kurtosis of strategy returns. Such models (including the Kelly Criterion outlined below) generally rely on these moments being constant in time. Under a market regime change these moments can be 119
120 drastically altered and hence lead to degradation of the model. Models with "rolling parameters" are usually utilised in order to mitigate this issue. 13. 1. 2 Portfolio Risk A Portfolio contains one or more strategies. Thus it is indirectly subject to Strategy Risk as outlined above. In addition there are specific risks that occur at the portfolio level. These are usually only considered in an institutional setting or in a high-end retail setting where portfolio tracking is being carried out on a stable of trading strategies. When regressing portfolio returns to a set of factors, such as industry sectors, asset classes or groups of financial entities it is possible to ascertain if the portfolio is heavily "loaded" into a particular factor. For instance, an equities portfolio may be extremely heavy on technology stocks and thus is extremely exposed to any issues that affect the tech sector as a whole. Hence it is often necessary-at the portfolio level-to override particular strategies in order to account for overloaded factor risk. This is often a more significant concern in an institutional setting where there is more capital to be allocated and the preservation of capital takes precedence to the long-term growth rate of the capital. However, it should certainly be considered even as a retail algorithmic trading investor. Another issue that is largely an institutional issue (unless trading more illiquid assets) are limits on daily trading volume. For retail traders, executing strategies in the large-cap or com-modities futures markets, there is no real concern regarding market impact. However, in less liquid instruments one has to be careful to not be trading a significant percentage of the daily traded volume, due to potential market impact and thus invalidation of a previously backtested trading model (which often do not take into account market impact). To avoid this it is necessary to calculate the average daily volume (using a mean over a loopback period, for instance) and stay within small percentage limits of this figure. Running a portfolio of strategies brings up the issue of strategy correlation. Correlations can be estimated via statistical techniques such as the Pearson Product Moment Correlation Coefficient. However, correlation itself is not a static entity and is also subject to swift change, especially under market-wide liquidity constraints, often known as financial contagion. In gen-eral, strategies should be designed to avoid correlation with each other by virtue of differing asset classes or time horizons. Rolling correlations can be estimated over a large time-period and should be a standard part of your backtest, if considering a portfolio approach. 13. 1. 3 Counterparty Risk Counterparty risk is generally considered a form of credit risk. It is the risk that a counterpart will not pay an obligation on a financial asset under which they are liable. There is an entire subset of quantitative finance related to the pricing of counterpart risk hedging instruments, but this is not of primary interest to us as retail algorithmic traders. We are more concerned with the risk of default from suppliers such as an exchange or brokerage. While this may seem academic, I can personally assure you that these issues are quite real! In an institutional setting I have experienced first hand a brokerage bankruptcy under conditions that meant not all of the trading capital was returned. Thus I now factor such risks into a portfolio. The suggested means of mitigating this issue is to utilise multiple brokerages, although when trading under margin this can make the trading logistics somewhat tricky. Counterparty risk is generally more of a concern in an institutional setting so I won't dwell on it too much here! 13. 1. 4 Operational Risk Operation risk encompasses sources of risk from within a fund or trading operational infrastruc-ture, including business/entrepreneurial risk, IT risk and external regulatory or legal changes. These topics aren't often discussed in any great depth, which I believe is somewhat short-sighted since they have the potential to completely halt a trading operation permanently.
121 Infrastructure risk is often associated with information technology systems and other related trading infrastructure. This also includes employee risk (such as fraud, sudden departure). As the scale of an infrastructure grows so does the likelihood of the "single point of failure" (SPOF). This is a critical component in the trading infrastructure that, under malfunction, can lead to a catastrophe halting of the entire operation. In the IT sense, this is usually the consequence of a badly thought out architecture. In a non-IT sense this can be the consequence of a badly designed organisation chart. Theseissuesarestillentirelyrelevantfortheretailtrader. Often, an IT/tradinginfrastructure can end up being "patchy" and "hacked together". In addition, poor record keeping and other administrative failures can lead to huge potential tax burdens. Thankfully, "cloud" architecture provides the ability for redundancy in systems and automation of processes can lead to solid administrative habits. This type of behaviour, that is consideration of risks from sources other than the market and the strategy, can often make the difference between a successful long-term algorithmic trader and the individual who gives up due to catastrophic operation breakdown. An issue that affects the hedge fund world is that of reporting and compliance. Post-2008 legislation has put a heavy burden on asset management firms, which can have a large impact on their cash-flow and operating expenditure. For an individual thinking of incorporating such a firm, in order to expand a strategy or run with external funds, it is prudent to keep on top of the legislation and regulatory environment, since it is somewhat of a "moving target". 13. 2 Money Management This section deals with one of the most fundamental concepts in trading-both discretionary and algorithmic-namely, money management. A naive investor/trader might believe that the only important investment objective is to simply make as much money as possible. However the reality of long-term trading is more complex. Since market participants have differing risk preferences and constraints there are many objectives that investors may possess. Many retail traders consider the onlygoal to be a continual increase of account equity, with little or no consideration given to the "risk" of a strategy that achieves this growth. More sophis-ticated retail investors measure account drawdowns, and depending upon their risk preferences, may be able to cope with a substantial drop in account equity (say 50%). The reason they can deal with a drawdown of this magnitude is that they realise, quantitatively, that this behaviour may be optimal for the long-term growth rate of the portfolio, via the use of leverage. An institutional investor is likely to consider risk in a different light. Often institutional investors have mandated maximum drawdowns (say 20%), with significant consideration given to sector allocation and average daily volume limits. They would be additional constraints on the "optimisation problem" of capital allocation to strategies. These factors might even be more important than maximising the long-term growth rate of the portfolio. Thus we are in a situation where we can strike a balance between maximising long-term growth rate via leverage and minimising our "risk" by trying to limit the duration and extent of the drawdown. The major tool that will help us achieve this is called the Kelly Criterion. 13. 2. 1 Kelly Criterion Withinthissectionthe Kelly Criterionisgoingtobeourtooltocontrolleverageof, andallocation towards, a set of algorithmic trading strategies that make up a multi-strategy portfolio. We will define leverage as the ratio of the size of a portfolio to the actual account equity within that portfolio. To make this clear we can use the analogy of purchasing a house with a mortgage. Your down payment (or "deposit" for those of us in the UK!) constitutes your account equity, while the down payment plus the mortgage value constitutes the equivalent of the size of a portfolio. Thus a down payment of 50,000 USD on a 200,000 USD house (with a mortgage of 150,000 USD) constitutes a leverage of (150000 + 50000) /50000 = 4. Thus in this instance you would be 4x leveraged on the house. A margin account portfolio behaves similarly. There is a "cash" component and then more stock can be borrowed on margin, to provide the leverage. Before we state the Kelly Criterion specifically I want to outline the assumptions that go into its derivation, which have varying degrees of accuracy:
122 Each algorithmic trading strategy will be assumed to possess a returns stream that is normally distributed (i. e. Gaussian ). Further, each strategy has its own fixedmean and standard deviation of returns. The formula assumes that these mean and std values do not change, i. e. that they are same in the past as in the future. This is clearly not the case with most strategies, so be aware of this assumption. The returns being considered here are excess returns, which means they are net of all financing costs such as interest paid on margin and transaction costs. If the strategy is being carried out in an institutional setting, this also means that the returns are net of management and performance fees. Allofthetradingprofitsarereinvestedandnowithdrawalsofequityarecarriedout. Thisis clearly not as applicable in an institutional setting where the above mentioned management fees are taken out and investors often make withdrawals. Allofthestrategiesarestatisticallyindependent(thereisnocorrelationbetweenstrategies) and thus the covariance matrix between strategy returns is diagonal. Now we come to the actual Kelly Criterion! Let's imagine that we have a set of Nalgorithmic trading strategies and we wish to determine both how to apply optimal leverage per strategy in order to maximise growth rate (but minimise drawdowns) and how to allocate capital between each strategy. If we denote the allocation between each strategy ias a vector fof length N, s. t. f= (f1,...,f N), then the Kelly Criterion for optimal allocation to each strategy fiis given by: fi=µi/σ2 i (13. 1) Whereµiare the mean excess returns and σiare the standard deviation of excess returns for a strategyi. This formula essentially describes the optimal leverage that should be applied to each strategy. While the Kelly Criterion figives us the optimal leverage and strategy allocation, we still need to actually calculate our expected long-term compounded growth rate of the portfolio, which we denote by g. The formula for this is given by: g=r+S2/2 (13. 2) Whereris the risk-free interest rate, which is the rate at which you can borrow from the broker, and Sis the annualised Sharpe Ratio of the strategy. The latter is calculated via the annualised mean excess returns divided by the annualised standard deviations of excess returns. See the previous chapter on Performance Measurement for details on the Sharpe Ratio. A Realistic Example Let's consider an example in the single strategy case ( i= 1). Suppose we go long a mythical stock XYZ that has a mean annual return of m= 10. 7%and an annual standard deviation of σ= 12. 4%. In addition suppose we are able to borrow at a risk-free interest rate of r= 3. 0%. This implies that the mean excess returns are µ=m-r= 10. 7-3. 0 = 7. 7%. This gives us a Sharpe Ratio of S= 0. 077/0. 124 = 0. 62. With this we can calculate the optimal Kelly leverage via f=µ/σ2= 0. 077/0. 1242= 5. 01. Thus the Kelly leverage says that for a 100,000 USD portfolio we should borrow an additional 401,000 USD to have a total portfolio value of 501,000 USD. In practice it is unlikely that our brokerage would let us trade with such substantial margin and so the Kelly Criterion would need to be adjusted. We can then use the Sharpe ratio Sand the interest rate rto calculate g, the expected long-term compounded growth rate. g=r+S2/2 = 0. 03 + 0. 622/2 = 0. 22, i. e. 22%. Thus we shouldexpecta return of 22% a year from this strategy.
123 Kelly Criterion in Practice It is important to be aware that the Kelly Criterion requires a continuous rebalancing of capital allocation in order to remain valid. Clearly this is not possible in the discrete setting of actual trading and so an approximation must be made. The standard "rule of thumb" here is to update the Kelly allocation once a day. Further, the Kelly Criterion itself should be recalculated periodically, using a trailing mean and standard deviation with a lookback window. Again, for a strategy that trades roughly once a day, this lookback should be set to be on the order of 3-6 months of daily returns. Here is an example of rebalancing a portfolio under the Kelly Criterion, which can lead to some counter-intuitive behaviour. Let's suppose we have the strategy described above. We have used the Kelly Criterion to borrow cash to size our portfolio to 501,000 USD. Let's assume we make a healthy 5% return on the following day, which boosts our account size to 526,050 USD. The Kelly Criterion tells us that we should borrow moreto keep the same leverage factor of 5. 01. In particular our account equity is 126,050 USD on a portfolio of 526,050, which means that the current leverage factor is 4. 17. To increase it to 5. 01, we need to borrow an additional 105,460 USD in order to increase our account size to 631,510. 5 USD (this is 5. 01×126050). Now consider that the following day we lose 10% on our portfolio (ouch!). This means that the total portfolio size is now 568,359. 45 USD ( 631510. 5×0. 9). Our total account equity is now 62,898. 95 USD ( 126050-631510. 45×0. 1). This means our current leverage factor is 568359. 45/62898. 95 = 9. 03. Hence we need to reduce our account by selling253,235. 71 USD of stock in order to reduce our total portfolio value to 315,123. 73 USD, such that we have a leverage of 5. 01 again ( 315123. 73/62898. 95 = 5. 01). Hence we have boughtinto a profit and soldinto a loss. This process of selling into a loss may be extremely emotionally difficult, but it is mathematically the "correct" thing to do, assuming that the assumptions of Kelly have been met! It is the approach to follow in order to maximise long-term compounded growth rate. You may have noticed that the absolute values of money being re-allocated between days were rather severe. This is a consequence of both the artificial nature of the example and the extensive leverage employed. 10% loss in a day is not particularly common in higher-frequency algorithmic trading, but it does serve to show how extensive leverage can be on absolute terms. Since the estimation of means and standard deviations are always subject to uncertainty, in practice many traders tend to use a more conservative leverage regime such as the Kelly Criterion divided by two, affectionately known as "half-Kelly". The Kelly Criterion should really be considered as an upper bound of leverage to use, rather than a direct specification. If this advice is not heeded then using the direct Kelly value can lead to ruin (i. e. account equity disappearing to zero) due to the non-Gaussian nature of the strategy returns. Should You Use The Kelly Criterion? Every algorithmic trader is different and the same is true of risk preferences. When choosing to employ a leverage strategy (of which the Kelly Criterion is one example) you should consider the risk mandates that you need to work under. In a retail environment you are able to set your own maximum drawdown limits and thus your leverage can be increased. In an institutional setting you will need to consider risk from a very different perspective and the leverage factor will be one component of a much larger framework, usually under many other constraints. 13. 3 Risk Management 13. 3. 1 Value-at-Risk Estimating the risk of loss to an algorithmic trading strategy, or portfolio of strategies, is of extreme importance for long-term capital growth. Many techniques for risk management have been developed for use in institutional settings. One technique in particular, known as Value at Risk or Va R, will be the topic of this section.
124 We will be applying the concept of Va R to a single strategy or a set of strategies in order to help us quantify risk in our trading portfolio. The definition of Va R is as follows: Va R provides an estimate, under a given degree of confidence, of the size of a loss from a portfolio over a given time period. In this instance "portfolio" can refer to a single strategy, a group of strategies, a trader's book, a prop desk, a hedge fund or an entire investment bank. The "given degree of confidence" will be a value of, say, 95% or 99%. The "given time period" will be chosen to reflect one that would lead to a minimal market impact if a portfolio were to be liquidated. For example, a Va R equal to 500,000 USD at 95% confidence level for a time period of a day would simply state that there is a 95% probability of losing no more than 500,000 USD in the following day. Mathematically this is stated as: P(L≤-5. 0×105) = 0. 05 (13. 3) Or, more generally, for loss Lexceeding a value Va Rwith a confidence level cwe have: P(L≤-Va R ) = 1-c (13. 4) The "standard" calculation of Va R makes the following assumptions: Standard Market Conditions-Va R is not supposed to consider extreme events or "tail risk", rather it is supposed to provide the expectation of a loss under normal "day-to-day" operation. Volatilities and Correlations-Va R requires the volatilities of the assets under consid-eration, as well as their respective correlations. These two quantities are tricky to estimate and are subject to continual change. Normality of Returns-Va R, in its standard form, assumes the returns of the asset or portfolioare normally distributed. Thisleadstomorestraightforwardanalyticalcalculation, but it is quite unrealistic for most assets. 13. 4 Advantages and Disadvantages Va R is pervasive in the financial industry, hence you should be familiar with the benefits and drawbacks of the technique. Some of the advantages of Va R are as follows: Va R is very straightforward to calculate for individual assets, algo strategies, quant port-folios, hedge funds or even bank prop desks. The time period associated with the Va R can be modified for multiple trading strategies that have different time horizons. Different values of Va R can be associated with different forms of risk, say broken down by asset class or instrument type. This makes it easy to interpret where the majority of portfolio risk may be clustered, for instance. Individual strategies can be constrained as can entire portfolios based on their individual Va R. Va R is straightforward to interpret by (potentially) non-technical external investors and fund managers. However, Va R is not without its disadvantages: Va R does not discuss the magnitude of the expected loss beyond the value of Va R, i. e. it will tell us that we are likely to see a loss exceeding a value, but not how much it exceeds it.
125 It does not take into account extreme events, but only typical market conditions. Since it uses historical data (it is rearward-looking) it will not take into account future market regime shifts that can change volatilities and correlations of assets. Va R should not be used in isolation. It should always be used with a suite of risk management techniques, such as diversification, optimal portfolio allocation and prudent use of leverage. Methods of Calculation As of yet we have not discussed the actual calculation of Va R, either in the general case or a concrete trading example. There are three techniques that will be of interest to us. The first is the variance-covariance method (using normality assumptions), the second is a Monte Carlo method (based on an underlying, potentially non-normal, distribution) and the third is known as historical bootstrapping, which makes use of historical returns information for assets under consideration. In this section we will concentrate on the Variance-Covariance Method. Variance-Covariance Method Consider a portfolio of Pdollars, with a confidence level c. We are considering daily returns, with asset (or strategy) historical standard deviation σand meanµ. Then the daily Va R, under the variance-covariance method for a single asset (or strategy) is calculated as: P-(P(α(1-c) + 1)) (13. 5) Whereαis the inverse of the cumulative distribution function of a normal distribution with meanµand standard deviation σ. Wecan usethe Sci Pyandpandas librariesin ordertocalculate thesevalues. If weset P= 106 andc= 0. 99, we can use the Sci Py ppf method to generate the values for the inverse cumulative distribution function to a normal distribution with µandσobtained from some real financial data, in this case the historical daily returns of Citi Group (we could easily substitute the returns of an algorithmic strategy in here): #!/usr/bin/python #-*-coding: utf-8-*-# var. py from __future __import print _function import datetime import numpy as np import pandas. io. data as web from scipy. stats import norm def var_cov_var(P, c, mu, sigma): """ Variance-Covariance calculation of daily Value-at-Risk using confidence level c, with mean of returns mu and standard deviation of returns sigma, on a portfolio of value P. """ alpha = norm. ppf(1-c, mu, sigma) return P-P *(alpha + 1)
126 if__name __== " __main __": start = datetime. datetime(2010, 1, 1) end = datetime. datetime(2014, 1, 1) citi = web. Data Reader("C", 'yahoo', start, end) citi["rets"] = citi["Adj Close"]. pct _change() P = 1e6 # 1,000,000 USD c = 0. 99 # 99% confidence interval mu = np. mean(citi["rets"]) sigma = np. std(citi["rets"]) var = var _cov_var(P, c, mu, sigma) print ("Value-at-Risk: $%0. 2f" % var) The calculated value of Va R is given by: Value-at-Risk: $56503. 12 Va R is an extremely useful and pervasive technique in all areas of financial management, but it is not without its flaws. David Einhorn, the renowned hedge fund manager, has famously described Va R as "an airbag that works all the time, except when you have a car accident. " Indeed, you should always use Va R as an augmentation to your risk management overlay, not as a single indicator!
Part VI Automated Trading 127
Chapter 14 Event-Driven Trading Engine Implementation This chapter provides an implementation for a fully self-contained event-driven backtest system written in Python. In particular this chapter has been written to expand on the details that are usually omitted from other algorithmic trading texts and papers. The following code will allow you to simulate high-frequency (minute to second) strategies across the forecasting, momentum and mean reversion domains in the equities, foreign exchange and futures markets. With extensive detail comes complexity, however. The backtesting system provided here requires many components, each of which are comprehensive entities in themselves. The first step is thus to outline what event-driven software is and then describe the components of the backtester and how the entire system fits together. 14. 1 Event-Driven Software Before we delve into development of such a backtester we need to understand the concept of event-driven systems. Video games provide a natural use case for event-driven software and provide a straightforward example to explore. A video game has multiple components that interact with each other in a real-time setting at high framerates. This is handled by running the entire set of calculations within an "infinite" loop known as the event-loop or game-loop. At each tick of the game-loop a function is called to receive the latest event, which will have been generated by some corresponding prior action within the game. Depending upon the nature of the event, which could include a key-press or a mouse click, some subsequent action is taken, which will either terminate the loop or generate some additional events. The process will then continue. Here is some example pseudo-code: while True: # Run the loop forever new_event = get _new_event() # Get the latest event # Based on the event type, perform an action ifnew_event. type == "LEFT _MOUSE _CLICK": open _menu() elif new_event. type == "ESCAPE _KEY_PRESS": quit _game() elif new_event. type == "UP _KEY_PRESS": move _player _north() #... and many more events redraw _screen() # Update the screen to provide animation tick(50) # Wait 50 milliseconds 129
130 The code is continually checking for new events and then performing actions based on these events. In particular it allows the illusion of real-time response handling because the code is continually being looped and events checked for. As will become clear this is precisely what we need in order to carry out high frequency trading simulation. 14. 1. 1 Why An Event-Driven Backtester? Event-driven systems provide many advantages over a vectorised approach: Code Reuse-An event-driven backtester, by design, can be used for both historical backtesting and live trading with minimal switch-out of components. This is not true of vectorised backtesters where all data must be available at once to carry out statistical analysis. Lookahead Bias-With an event-driven backtester there is no lookahead bias as market data receipt is treated as an "event" that must be acted upon. Thus it is possible to "drip feed" an event-driven backtester with market data, replicating how an order management and portfolio system would behave. Realism-Event-driven backtesters allow significant customisation over how orders are executed and transaction costs are incurred. It is straightforward to handle basic market and limit orders, as well as market-on-open (MOO) and market-on-close (MOC), since a custom exchange handler can be constructed. Althoughevent-drivensystemscomewithmanybenefitstheysufferfromtwomajordisadvan-tages over simpler vectorised systems. Firstly they are significantly more complex to implement and test. There are more "moving parts" leading to a greater chance of introducing bugs. To mitigate this proper software testing methodology such as test-driven development can be em-ployed. Secondly they are slower to execute compared to a vectorised system. Optimal vectorised operations are unable to be utilised when carrying out mathematical calculations. 14. 2 Component Objects To apply an event-driven approach to a backtesting system it is necessary to define our compo-nents (or objects) that will handle specific tasks: Event-The Event is the fundamental class unit of the event-driven system. It contains a type (such as "MARKET", "SIGNAL", "ORDER" or "FILL") that determines how it will be handled within the event-loop. Event Queue-The Event Queue is an in-memory Python Queue object that stores all of the Event sub-class objects that are generated by the rest of the software. Data Handler-The Data Handler is an abstract base class (ABC) that presents an inter-face for handling both historical or live market data. This provides significant flexibility as the Strategy and Portfolio modules can thus be reused between both approaches. The Data Handler generates a new Market Event upon every heartbeat of the system (see below). Strategy-The Strategy is also an ABC that presents an interface for taking market data and generating corresponding Signal Events, which are ultimately utilised by the Portfolio object. A Signal Event contains a ticker symbol, a direction (LONG or SHORT) and a timestamp. Portfolio-This is a class hierarchy which handles the order management associated with current and subsequent positions for a strategy. It also carries out risk management across the portfolio, including sector exposure and position sizing. In a more sophisticated implementation this could be delegated to a Risk Management class. The Portfolio takes Signal Events from the Queue and generates Order Events that get added to the Queue.
131 Execution Handler-The Execution Handler simulates a connection to a brokerage. The job of the handler is to take Order Events from the Queue and execute them, either via a simulated approach or an actual connection to a liver brokerage. Once orders are executed the handler creates Fill Events, which describe what was actually transacted, including fees, commission and slippage (if modelled). Backtest-All of these components are wrapped in an event-loop that correctly handles all Event types, routing them to the appropriate component. Despite the quantity of components, this is quite a basic model of a trading engine. There is significant scope for expansion, particularly in regard to how the Portfolio is used. In addition differing transaction cost models might also be abstracted into their own class hierarchy. 14. 2. 1 Events The first component to be discussed is the Event class hierarchy. In this infrastructure there are four types of events which allow communication between the above components via an event queue. They are a Market Event, Signal Event, Order Event and Fill Event. Event The parent class in the hierarchy is called Event. It is a base class and does not provide any functionality or specific interface. Since in many implementations the Event objects will likely develop greater complexity it is thus being "future-proofed" by creating a class hierarchy. #!/usr/bin/python #-*-coding: utf-8-*-# event. py from __future __import print _function class Event(object): """ Event is base class providing an interface for all subsequent (inherited) events, that will trigger further events in the trading infrastructure. """ pass Market Event Market Events are triggered when the outer while loop of the backtesting system begins a new "heartbeat". It occurs when the Data Handler object receives a new update of market data for any symbols which are currently being tracked. It is used to trigger the Strategy object generating new trading signals. The event object simply contains an identification that it is a market event, with no other structure. # event. py class Market Event(Event): """ Handles the event of receiving a new market update with corresponding bars. """ def __init __(self):
132 """ Initialises the Market Event. """ self. type = 'MARKET' Signal Event The Strategy object utilises market data to create new Signal Events. The Signal Event contains a strategy ID, a ticker symbol, a timestamp for when it was generated, a direction (long or short) and a "strength" indicator (this is useful for mean reversion strategies). The Signal Events are utilised by the Portfolio object as advice for how to trade. # event. py class Signal Event(Event): """ Handles the event of sending a Signal from a Strategy object. This is received by a Portfolio object and acted upon. """ def __init __(self, strategy _id, symbol, datetime, signal _type, strength): """ Initialises the Signal Event. Parameters: strategy _id-The unique identifier for the strategy that generated the signal. symbol-The ticker symbol, e. g. 'GOOG'. datetime-The timestamp at which the signal was generated. signal _type-'LONG' or 'SHORT'. strength-An adjustment factor "suggestion" used to scale quantity at the portfolio level. Useful for pairs strategies. """ self. type = 'SIGNAL' self. strategy _id = strategy _id self. symbol = symbol self. datetime = datetime self. signal _type = signal _type self. strength = strength Order Event When a Portfolio object receives Signal Events it assesses them in the wider context of the port-folio, in terms of risk and position sizing. This ultimately leads to Order Events that will be sent to an Execution Handler. The Order Event is slightly more complex than a Signal Event since it contains a quantity field in addition to the aforementioned properties of Signal Event. The quantity is determined by the Portfolio constraints. In addition the Order Event has a print_order() method, used to output the information to the console if necessary. # event. py class Order Event(Event): """ Handles the event of sending an Order to an execution system. The order contains a symbol (e. g. GOOG), a type (market or limit),
133 quantity and a direction. """ def __init __(self, symbol, order _type, quantity, direction): """ Initialises the order type, setting whether it is a Market order ('MKT') or Limit order ('LMT'), has a quantity (integral) and its direction ('BUY' or 'SELL'). Parameters: symbol-The instrument to trade. order _type-'MKT' or 'LMT' for Market or Limit. quantity-Non-negative integer for quantity. direction-'BUY' or 'SELL' for long or short. """ self. type = 'ORDER' self. symbol = symbol self. order _type = order _type self. quantity = quantity self. direction = direction def print _order(self): """ Outputs the values within the Order. """ print ( "Order: Symbol=%s, Type=%s, Quantity=%s, Direction=%s" % (self. symbol, self. order _type, self. quantity, self. direction) ) Fill Event When an Execution Handler receives an Order Event it must transact the order. Once an order has been transacted it generates a Fill Event, which describes the cost of purchase or sale as well as the transaction costs, such as fees or slippage. The Fill Event is the Event with the greatest complexity. It contains a timestamp for when an order was filled, the symbol of the order and the exchange it was executed on, the quantity of shares transacted, the actual price of the purchase and the commission incurred. The commission is calculated using the Interactive Brokers commissions. For US API orders this commission is 1. 30 USD minimum per order, with a flat rate of either 0. 013 USD or 0. 08 USD per share depending upon whether the trade size is below or above 500 units of stock. # event. py class Fill Event(Event): """ Encapsulates the notion of a Filled Order, as returned from a brokerage. Stores the quantity of an instrument actually filled and at what price. In addition, stores the commission of the trade from the brokerage. """ def __init __(self, timeindex, symbol, exchange, quantity, direction, fill _cost, commission=None):
134 """ Initialises the Fill Event object. Sets the symbol, exchange, quantity, direction, cost of fill and an optional commission. If commission is not provided, the Fill object will calculate it based on the trade size and Interactive Brokers fees. Parameters: timeindex-The bar-resolution when the order was filled. symbol-The instrument which was filled. exchange-The exchange where the order was filled. quantity-The filled quantity. direction-The direction of fill ('BUY' or 'SELL') fill _cost-The holdings value in dollars. commission-An optional commission sent from IB. """ self. type = 'FILL' self. timeindex = timeindex self. symbol = symbol self. exchange = exchange self. quantity = quantity self. direction = direction self. fill _cost = fill _cost # Calculate commission ifcommission is None: self. commission = self. calculate _ib_commission() else : self. commission = commission def calculate _ib_commission(self): """ Calculates the fees of trading based on an Interactive Brokers fee structure for API, in USD. This does not include exchange or ECN fees. Based on "US API Directed Orders": https://www. interactivebrokers. com/en/index. php? f=commission&p=stocks2 """ full _cost = 1. 3 ifself. quantity <= 500: full _cost = max(1. 3, 0. 013 *self. quantity) else :# Greater than 500 full _cost = max(1. 3, 0. 008 *self. quantity) return full _cost 14. 2. 2 Data Handler One of the goals of an event-driven trading system is to minimise duplication of code between the backtesting element and the live execution element. Ideally it would be optimal to utilise the same signal generation methodology and portfolio management components for both historical
135 testing and live trading. In order for this to work the Strategy object which generates the Signals, and the Portfolio object which provides Orders based on them, must utilise an identical interface to a market feed for both historic and live running. This motivates the concept of a class hierarchy based on a Data Handler object, which gives all subclasses an interface for providing market data to the remaining components within the system. In this way any subclass data handler can be "swapped out", without affecting strategy or portfolio calculation. Specific example subclasses could include Historic CSVData Handler, Quandl Data Handler, Se-curities Master Data Handler, Interactive Brokers Market Feed Data Handler etc. In this chapter we are only going to consider the creation of a historic CSV data handler, which will load intraday CSV data for equities in an Open-Low-High-Close-Volume-Open Interest set of bars. This can then be used to "drip feed" on a bar-by-bar basis the data into the Strategy and Portfolio classes on every heartbeat of the system, thus avoiding lookahead bias. The first task is to import the necessary libraries. Specifically it will be necessary to im-port pandas and the abstract base class tools. Since the Data Handler generates Market Events, event. py is also needed as described above. #!/usr/bin/python #-*-coding: utf-8-*-# data. py from __future __import print _function from abc import ABCMeta, abstractmethod import datetime import os, os. path import numpy as np import pandas as pd from event import Market Event The Data Handler is an abstract base class (ABC), which means that it is impossible to instantiate an instance directly. Only subclasses may be instantiated. The rationale for this is that the ABC provides an interface that all subsequent Data Handler subclasses must adhere to thereby ensuring compatibility with other classes that communicate with them. We make use of the __metaclass__ property to let Python know that this is an ABC. In addition we use the @abstractmethod decorator to let Python know that the method will be overridden in subclasses (this is identical to a pure virtual method in C++). There are six methods listed for the class. The first two methods, get_latest_bar and get_latest_bars, are used to retrieve a recent subset of the historical trading bars from a stored list of such bars. These methods come in handy within the Strategy and Portfolio classes, due to the need to constantly be aware of current market prices and volumes. The following method, get_latest_bar_datetime, simply returns a Python datetime object that represents the timestamp of the bar (e. g. a date for daily bars or a minute-resolution object for minutely bars). The following two methods, get_latest_bar_value and get_latest_bar_values, are conve-nience methods used to retrieve individual values from a particular bar, or list of bars. For instance it is often the case that a strategy is only interested in closing prices. In this instance we can use these methods to return a list of floating point values representing the closing prices of previousbars, ratherthanhavingtoobtainitfromthelistofbarobjects. Thisgenerallyincreases efficiency of strategies that utilise a "lookback window", such as those involving regressions. The final method, update_bars, provides a "drip feed" mechanism for placing bar infor-mation on a new data structure that strictly prohibits lookahead bias. This is one of the key differences between an event-driven backtesting system and one based on vectorisation. Notice that exceptions will be raised if an attempted instantiation of the class occurs:
136 # data. py class Data Handler(object): """ Data Handler is an abstract base class providing an interface for all subsequent (inherited) data handlers (both live and historic). The goal of a (derived) Data Handler object is to output a generated set of bars (OHLCVI) for each symbol requested. This will replicate how a live strategy would function as current market data would be sent "down the pipe". Thus a historic and live system will be treated identically by the rest of the backtesting suite. """ __metaclass __= ABCMeta @abstractmethod def get_latest _bar(self, symbol): """ Returns the last bar updated. """ raise Not Implemented Error("Should implement get _latest _bar()") @abstractmethod def get_latest _bars(self, symbol, N=1): """ Returns the last N bars updated. """ raise Not Implemented Error("Should implement get _latest _bars()") @abstractmethod def get_latest _bar_datetime(self, symbol): """ Returns a Python datetime object for the last bar. """ raise Not Implemented Error("Should implement get_latest _bar_datetime()") @abstractmethod def get_latest _bar_value(self, symbol, val _type): """ Returns one of the Open, High, Low, Close, Volume or OI from the last bar. """ raise Not Implemented Error("Should implement get_latest _bar_value()") @abstractmethod def get_latest _bars _values(self, symbol, val _type, N=1): """ Returns the last N bar values from the latest _symbol list, or N-k if less available. """ raise Not Implemented Error("Should implement get_latest _bars _values()")
137 @abstractmethod def update _bars(self): """ Pushes the latest bars to the bars _queue for each symbol in a tuple OHLCVI format: (datetime, open, high, low, close, volume, open interest). """ raise Not Implemented Error("Should implement update _bars()") In order to create a backtesting system based on historical data we need to consider a mecha-nism for importing data via common sources. We've discussed the benefits of a Securities Master Database in previous chapters. Thus a good candidate for making a Data Handler class would be to couple it with such a database. However, for clarity in this chapter, I want to discuss a simpler mechanism, that of importing (potentially large) comma-separated variable (CSV) files. This will allow us to focus on the mechanics of creating the Data Handler, rather than be concerned with the "boilerplate" code of connecting to a database and using SQL queries to grab data. Thus we are going to define the Historic CSVData Handler subclass, which is designed to process multiple CSV files, one for each traded symbol, and convert these into a dictionary of pandas Data Frames that can be accessed by the previously mentioned bar methods. The data handler requires a few parameters, namely an Event Queue on which to push Market Event information to, the absolute path of the CSV files and a list of symbols. Here is the initialisation of the class: # data. py class Historic CSVData Handler(Data Handler): """ Historic CSVData Handler is designed to read CSV files for each requested symbol from disk and provide an interface to obtain the "latest" bar in a manner identical to a live trading interface. """ def __init __(self, events, csv _dir, symbol _list): """ Initialises the historic data handler by requesting the location of the CSV files and a list of symbols. It will be assumed that all files are of the form 'symbol. csv', where symbol is a string in the list. Parameters: events-The Event Queue. csv_dir-Absolute directory path to the CSV files. symbol _list-A list of symbol strings. """ self. events = events self. csv _dir = csv _dir self. symbol _list = symbol _list self. symbol _data = {} self. latest _symbol _data = {} self. continue _backtest = True self. _open _convert _csv_files()
138 The handler is will look for files in the absolute directory csv_dir and try to open them with the format of "SYMBOL. csv", where SYMBOL is the ticker symbol (such as GOOG or AAPL). The format of the files matches that provided by Yahoo Finance, but is easily modified to handle additional data formats, such as those provided by Quandl or DTN IQFeed. The opening of the files is handled by the _open_convert_csv_files method below. One of the benefits of using pandas as a datastore internally within the Historic CSVData-Handler is that the indexes of all symbols being tracked can be merged together. This allows missing data points to be padded forward, backward or interpolated within these gaps such that tickers can be compared on a bar-to-bar basis. This is necessary for mean-reverting strategies, for instance. Notice the use of the union and reindex methods when combining the indexes for all symbols: # data. py def _open _convert _csv_files(self): """ Opens the CSV files from the data directory, converting them into pandas Data Frames within a symbol dictionary. For this handler it will be assumed that the data is taken from Yahoo. Thus its format will be respected. """ comb _index = None for sinself. symbol _list: # Load the CSV file with no header information, indexed on date self. symbol _data[s] = pd. io. parsers. read _csv( os. path. join(self. csv _dir, '%s. csv' % s), header=0, index _col=0, parse _dates=True, names=[ 'datetime', 'open', 'high', 'low', 'close', 'volume', 'adj _close' ] ). sort() # Combine the index to pad forward values ifcomb _index is None: comb _index = self. symbol _data[s]. index else : comb _index. union(self. symbol _data[s]. index) # Set the latest symbol _data to None self. latest _symbol _data[s] = [] # Reindex the dataframes for sinself. symbol _list: self. symbol _data[s] = self. symbol _data[s]. \ reindex(index=comb _index, method='pad'). iterrows() The _get_new_bar method creates a generator to provide a new bar. This means that subsequent calls to the method will yielda new bar until the end of the symbol data is reached: # data. py def _get_new_bar(self, symbol): """ Returns the latest bar from the data feed. """ for binself. symbol _data[symbol]:
139 yield b The first abstract methods from Data Handler to be implemented are get_latest_bar and get_latest_bars. These method simply provide either a bar or list of the last Nbars from the latest_symbol_data structure: # data. py def get_latest _bar(self, symbol): """ Returns the last bar from the latest _symbol list. """ try: bars _list = self. latest _symbol _data[symbol] except Key Error: print ("That symbol is not available in the historical data set. ") raise else : return bars _list[-1] def get_latest _bars(self, symbol, N=1): """ Returns the last N bars from the latest _symbol list, or N-k if less available. """ try: bars _list = self. latest _symbol _data[symbol] except Key Error: print ("That symbol is not available in the historical data set. ") raise else : return bars _list[-N:] The next method, get_latest_bar_datetime, queries the latest bar for a datetime object representing the "last market price": def get_latest _bar_datetime(self, symbol): """ Returns a Python datetime object for the last bar. """ try: bars _list = self. latest _symbol _data[symbol] except Key Error: print ("That symbol is not available in the historical data set. ") raise else : return bars _list[-1][0] Thenexttwomethodsbeingimplementedareget_latest_bar_valueandget_latest_bar_values. Both methods make use of the Python getattr function, which queries an object to see if a par-ticular attribute exists on an object. Thus we can pass a string such as "open" or "close" to getattr and obtain the value direct from the bar, thus making the method more flexible. This stops us having to write methods of the type get_latest_bar_close, for instance: def get_latest _bar_value(self, symbol, val _type): """ Returns one of the Open, High, Low, Close, Volume or OI values from the pandas Bar series object. """
140 try: bars _list = self. latest _symbol _data[symbol] except Key Error: print ("That symbol is not available in the historical data set. ") raise else : return getattr(bars _list[-1][1], val _type) def get_latest _bars _values(self, symbol, val _type, N=1): """ Returns the last N bar values from the latest _symbol list, or N-k if less available. """ try: bars _list = self. get _latest _bars(symbol, N) except Key Error: print ("That symbol is not available in the historical data set. ") raise else : return np. array([getattr(b[1], val _type) for binbars _list]) The final method, update_bars, is the second abstract method from Data Handler. It simply generates a Market Event that gets added to the queue as it appends the latest bars to the latest_symbol_data dictionary: # data. py def update _bars(self): """ Pushes the latest bar to the latest _symbol _data structure for all symbols in the symbol list. """ for sinself. symbol _list: try: bar = next(self. _get_new_bar(s)) except Stop Iteration: self. continue _backtest = False else : ifbar is not None: self. latest _symbol _data[s]. append(bar) self. events. put(Market Event()) Thus we have a Data Handler-derived object, which is used by the remaining components to keep track of market data. The Strategy, Portfolio and Execution Handler objects all require the current market data thus it makes sense to centralise it to avoid duplication of storage between these classes. 14. 2. 3 Strategy AStrategy object encapsulates all calculation on market data that generate advisory signals to a Portfolio object. Thus all of the "strategy logic" resides within this class. I have opted to separate out the Strategy and Portfolio objects for this backtester, since I believe this is more amenable to the situation of multiple strategies feeding "ideas" to a larger Portfolio, which then can handle its own risk (such as sector allocation, leverage). In higher frequency trading, the strategy and portfolio concepts will be tightly coupled and extremely hardware dependent. This is well beyond the scope of this chapter, however! At this stage in the event-driven backtester development there is no concept of an indicator orfilter, such as those found in technical trading. These are also good candidates for creating
141 a class hierarchy but are beyond the scope of this chapter. Thus such mechanisms will be used directly in derived Strategy objects. The strategy hierarchy is relatively simple as it consists of an abstract base class with a single pure virtual method for generating Signal Event objects. In order to create the Strategy hierarchy it is necessary to import Num Py, pandas, the Queueobject (which has become queue in Python 3), abstract base class tools and the Signal Event : #!/usr/bin/python #-*-coding: utf-8-*-# strategy. py from __future __import print _function from abc import ABCMeta, abstractmethod import datetime try: import Queue as queue except Import Error: import queue import numpy as np import pandas as pd from event import Signal Event The Strategy abstract base class simply defines a pure virtual calculate _signals method. In derived classes this is used to handle the generation of Signal Event objects based on market data updates: # strategy. py class Strategy(object): """ Strategy is an abstract base class providing an interface for all subsequent (inherited) strategy handling objects. The goal of a (derived) Strategy object is to generate Signal objects for particular symbols based on the inputs of Bars (OHLCV) generated by a Data Handler object. This is designed to work both with historic and live data as the Strategy object is agnostic to where the data came from, since it obtains the bar tuples from a queue object. """ __metaclass __= ABCMeta @abstractmethod def calculate _signals(self): """ Provides the mechanisms to calculate the list of signals. """ raise Not Implemented Error("Should implement calculate _signals()")
142 14. 2. 4 Portfolio This section describes a Portfolio object that keeps track of the positions within a portfolio and generates orders of a fixed quantity of stock based on signals. More sophisticated portfolio objects could include risk management and position sizing tools (such as the Kelly Criterion). In fact, in the following chapters we will add such tools to some of our trading strategies to see how they compare to a more "naive" portfolio approach. The portfolio order management system is possibly the most complex component of an event-driven backtester. Its role is to keep track of all current market positions as well as the market value of the positions (known as the "holdings"). This is simply an estimate of the liquidation value of the position and is derived in part from the data handling facility of the backtester. In addition to the positions and holdings management the portfolio must also be aware of risk factors and position sizing techniques in order to optimise orders that are sent to a brokerage or other form of market access. Unfortunately, Portfolio and Order Management Systems (OMS) can become rather complex! Thus I've made a decision here to keep the Portfolio object relatively straightforward, so that you can understand the key ideas and how they are implemented. The nature of an object-oriented design is that it allows, in a natural way, the extension to more complex situations later on. Continuing in the vein of the Eventclass hierarchy a Portfolio object must be able to handle Signal Event objects, generate Order Event objects and interpret Fill Event objects to update positions. Thus it is no surprise that the Portfolio objects are often the largest component of event-driven systems, in terms of lines of code (LOC). We create a new file portfolio. py and import the necessary libraries. These are the same as most of the other class implementations, with the exception that Portfolio is NOT going to be an abstract base class. Instead it will be normal base class. This means that it can be instantiated and thus is useful as a "first go" Portfolio object when testing out new strategies. Other Portfolios can be derived from it and override sections to add more complexity. For completeness, here is the performance. py file: #!/usr/bin/python #-*-coding: utf-8-*-# performance. py from __future __import print _function import numpy as np import pandas as pd def create _sharpe _ratio(returns, periods=252): """ Create the Sharpe ratio for the strategy, based on a benchmark of zero (i. e. no risk-free rate information). Parameters: returns-A pandas Series representing period percentage returns. periods-Daily (252), Hourly (252 *6. 5), Minutely(252 *6. 5*60) etc. """ return np. sqrt(periods) *(np. mean(returns)) / np. std(returns) def create _drawdowns(pnl): """ Calculate the largest peak-to-trough drawdown of the Pn L curve as well as the duration of the drawdown. Requires that the pnl_returns is a pandas Series.
143 Parameters: pnl-A pandas Series representing period percentage returns. Returns: drawdown, duration-Highest peak-to-trough drawdown and duration. """ # Calculate the cumulative returns curve # and set up the High Water Mark hwm = [0] # Create the drawdown and duration series idx = pnl. index drawdown = pd. Series(index = idx) duration = pd. Series(index = idx) # Loop over the index range for tinrange(1, len(idx)): hwm. append(max(hwm[t-1], pnl[t])) drawdown[t]= (hwm[t]-pnl[t]) duration[t]= (0 ifdrawdown[t] == 0 else duration[t-1]+1) return drawdown, drawdown. max(), duration. max() Here is the import listing for the Portfolio. py file. We need to import the floorfunction from themathlibrary in order to generate integer-valued order sizes. We also need the Fill Event and Order Event objects since the Portfolio handles both. Notice also that we are adding two ad-ditional functions, create_sharpe_ratio and create_drawdowns, both from the performance. py file described above. #!/usr/bin/python #-*-coding: utf-8-*-# portfolio. py from __future __import print _function import datetime from math import floor try: import Queue as queue except Import Error: import queue import numpy as np import pandas as pd from event import Fill Event, Order Event from performance import create _sharpe _ratio, create _drawdowns The initialisation of the Portfolio object requires access to the bars Data Handler, the events Event Queue, a start datetime stamp and an initial capital value (defaulting to 100,000 USD). The Portfolio is designed to handle position sizing and current holdings, but will carry out trading orders in a "dumb" manner by simply sending them directly to the brokerage with a predeterminedfixedquantitysize, irrespectiveofcashheld. Theseareallunrealisticassumptions, but they help to outline how a portfolio order management system (OMS) functions in an event-driven fashion.
144 The portfolio contains the all_positions andcurrent _positions members. The former storesalistofallprevious positions recordedatthetimestampofamarketdataevent. Aposition is simply the quantity of the asset held. Negative positions mean the asset has been shorted. The latter current_positions dictionary stores contains the current positions for the last market bar update, for each symbol. In addition to the positions data the portfolio stores holdings, which describe the current marketvalueof the positions held. "Current market value" in this instance means the closing price obtained from the current market bar, which is clearly an approximation, but is reasonable enough for the time being. all_holdings stores the historical list of all symbol holdings, while current _holdings stores the most up to date dictionary of all symbol holdings values: # portfolio. py class Portfolio(object): """ The Portfolio class handles the positions and market value of all instruments at a resolution of a "bar", i. e. secondly, minutely, 5-min, 30-min, 60 min or EOD. The positions Data Frame stores a time-index of the quantity of positions held. The holdings Data Frame stores the cash and total market holdings value of each symbol for a particular time-index, as well as the percentage change in portfolio total across bars. """ def __init __(self, bars, events, start _date, initial _capital=100000. 0): """ Initialises the portfolio with bars and an event queue. Also includes a starting datetime index and initial capital (USD unless otherwise stated). Parameters: bars-The Data Handler object with current market data. events-The Event Queue object. start _date-The start date (bar) of the portfolio. initial _capital-The starting capital in USD. """ self. bars = bars self. events = events self. symbol _list = self. bars. symbol _list self. start _date = start _date self. initial _capital = initial _capital self. all _positions = self. construct _all_positions() self. current _positions = dict( (k,v) for k, v in\ [(s, 0) for sinself. symbol _list] ) self. all _holdings = self. construct _all_holdings() self. current _holdings = self. construct _current _holdings() The following method, construct _all_positions, simply creates a dictionary for each symbol, sets the value to zero for each and then adds a datetime key, finally adding it to a list. It uses a dictionary comprehension, which is similar in spirit to a list comprehension: # portfolio. py
145 def construct _all_positions(self): """ Constructs the positions list using the start _date to determine when the time index will begin. """ d = dict( (k,v) for k, v in[(s, 0) for sinself. symbol _list] ) d['datetime'] = self. start _date return [d] Theconstruct _all_holdings method is similar to the above but adds extra keys for cash, commission and total, which respectively represent the spare cash in the account after any purchases, the cumulative commission accrued and the total account equity including cash and any open positions. Short positions are treated as negative. The starting cash and total account equity are both set to the initial capital. In this manner there are separate "accounts" for each symbol, the "cash on hand", the "commission" paid (Interactive Broker fees) and a "total" portfolio value. Clearly this does not take into account margin requirements or shorting constraints, but is sufficient to give you a flavour of how such an OMS is created: # portfolio. py def construct _all_holdings(self): """ Constructs the holdings list using the start _date to determine when the time index will begin. """ d = dict( (k,v) for k, v in[(s, 0. 0) for sinself. symbol _list] ) d['datetime'] = self. start _date d['cash'] = self. initial _capital d['commission'] = 0. 0 d['total'] = self. initial _capital return [d] The following method, construct _current _holdings is almost identical to the method above except that it doesn't wrap the dictionary in a list, because it is only creating a single entry: # portfolio. py def construct _current _holdings(self): """ This constructs the dictionary which will hold the instantaneous value of the portfolio across all symbols. """ d = dict( (k,v) for k, v in[(s, 0. 0) for sinself. symbol _list] ) d['cash'] = self. initial _capital d['commission'] = 0. 0 d['total'] = self. initial _capital return d On every heartbeat, that is every time new market data is requested from the Data Handler object, the portfolio must update the current market value of all the positions held. In a live trading scenario this information can be downloaded and parsed directly from the brokerage, but for a backtesting implementation it is necessary to calculate these values manually from the bars Data Handler. Unfortunately there is no such as thing as the "current market value" due to bid/ask spreads and liquidity issues. Thus it is necessary to estimate it by multiplying the quantity of the asset held by a particular approximate "price". The approach I have taken here is to use the closing
146 price of the last bar received. For an intraday strategy this is relatively realistic. For a daily strategy this is less realistic as the opening price can differ substantially from the closing price. The method update _timeindex handles the new holdings tracking. It firstly obtains the latest prices from the market data handler and creates a new dictionary of symbols to represent the current positions, by setting the "new" positions equal to the "current" positions. The current positions are only modified when a Fill Event is obtained, which is handled later on in the portfolio code. The method then appends this set of current positions to the all_positions list. The holdings are then updated in a similar manner, with the exception that the market value is recalculated by multiplying the current positions count with the closing price of the latest bar. Finally the new holdings are appended to all_holdings : # portfolio. py def update _timeindex(self, event): """ Adds a new record to the positions matrix for the current market data bar. This reflects the PREVIOUS bar, i. e. all current market data at this stage is known (OHLCV). Makes use of a Market Event from the events queue. """ latest _datetime = self. bars. get _latest _bar_datetime( self. symbol _list[0] ) # Update positions # ================ dp = dict( (k,v) for k, v in[(s, 0) for sinself. symbol _list] ) dp['datetime'] = latest _datetime for sinself. symbol _list: dp[s] = self. current _positions[s] # Append the current positions self. all _positions. append(dp) # Update holdings # =============== dh = dict( (k,v) for k, v in[(s, 0) for sinself. symbol _list] ) dh['datetime'] = latest _datetime dh['cash'] = self. current _holdings['cash'] dh['commission'] = self. current _holdings['commission'] dh['total'] = self. current _holdings['cash'] for sinself. symbol _list: # Approximation to the real value market _value = self. current _positions[s] *\ self. bars. get _latest _bar_value(s, "adj _close") dh[s] = market _value dh['total'] += market _value # Append the current holdings self. all _holdings. append(dh) The method update _positions _from _filldetermines whether a Fill Event is a Buy or a Sell and then updates the current _positions dictionary accordingly by adding/subtracting
147 the correct quantity of shares: # portfolio. py def update _positions _from _fill(self, fill): """ Takes a Fill object and updates the position matrix to reflect the new position. Parameters: fill-The Fill object to update the positions with. """ # Check whether the fill is a buy or sell fill _dir = 0 iffill. direction == 'BUY': fill _dir = 1 iffill. direction == 'SELL': fill _dir =-1 # Update positions list with new quantities self. current _positions[fill. symbol] += fill _dir*fill. quantity Thecorresponding update _holdings _from _fillissimilartotheabovemethodbutupdates theholdings values instead. In order to simulate the cost of a fill, the following method does not use the cost associated from the Fill Event. Why is this? Simply put, in a backtesting environment the fill cost is actually unknown (the market impact and the depth of book are unknown) and thus is must be estimated. Thus the fill cost is set to the the "current market price", which is the closing price of the last bar. The holdings for a particular symbol are then set to be equal to the fill cost multiplied by the transacted quantity. For most lower frequency trading strategies in liquid markets this is a reasonable approximation, but at high frequency these issues will need to be considered in a production backtest and live trading engine. Once the fill cost is known the current holdings, cash and total values can all be updated. The cumulative commission is also updated: # portfolio. py def update _holdings _from _fill(self, fill): """ Takes a Fill object and updates the holdings matrix to reflect the holdings value. Parameters: fill-The Fill object to update the holdings with. """ # Check whether the fill is a buy or sell fill _dir = 0 iffill. direction == 'BUY': fill _dir = 1 iffill. direction == 'SELL': fill _dir =-1 # Update holdings list with new quantities fill _cost = self. bars. get _latest _bar_value(fill. symbol, "adj _close") cost = fill _dir *fill _cost *fill. quantity self. current _holdings[fill. symbol] += cost self. current _holdings['commission'] += fill. commission self. current _holdings['cash']-= (cost + fill. commission)
148 self. current _holdings['total']-= (cost + fill. commission) Thepurevirtual update _fillmethodfromthe Portfolio classisimplementedhere. Itsim-plyexecutesthetwoprecedingmethods, update _positions _from _fillandupdate _holdings _from _fill, upon receipt of a fill event: # portfolio. py def update _fill(self, event): """ Updates the portfolio current positions and holdings from a Fill Event. """ ifevent. type == 'FILL': self. update _positions _from _fill(event) self. update _holdings _from _fill(event) While the Portfolio object must handle Fill Event s, it must also take care of generating Order Event s upon the receipt of one or more Signal Event s. The generate _naive _ordermethod simply takes a signal to go long or short an asset, sending an order to do so for 100 shares of such an asset. Clearly 100 is an arbitrary value, and will clearly depend upon the portfolio total equity in a production simulation. In a realistic implementation this value will be determined by a risk management or position sizing overlay. However, this is a simplistic Portfolio and so it "naively" sends all orders directly from the signals, without a risk system. The method handles longing, shorting and exiting of a position, based on the current quantity and particular symbol. Corresponding Order Event objects are then generated: # portfolio. py def generate _naive _order(self, signal): """ Simply files an Order object as a constant quantity sizing of the signal object, without risk management or position sizing considerations. Parameters: signal-The tuple containing Signal information. """ order = None symbol = signal. symbol direction = signal. signal _type strength = signal. strength mkt_quantity = 100 cur_quantity = self. current _positions[symbol] order _type = 'MKT' ifdirection == 'LONG' and cur_quantity == 0: order = Order Event(symbol, order _type, mkt _quantity, 'BUY') ifdirection == 'SHORT' and cur_quantity == 0: order = Order Event(symbol, order _type, mkt _quantity, 'SELL') ifdirection == 'EXIT' and cur_quantity > 0: order = Order Event(symbol, order _type, abs(cur _quantity), 'SELL') ifdirection == 'EXIT' and cur_quantity < 0: order = Order Event(symbol, order _type, abs(cur _quantity), 'BUY')
149 return order Theupdate _signalmethod simply calls the above method and adds the generated order to the events queue: # portfolio. py def update _signal(self, event): """ Acts on a Signal Event to generate new orders based on the portfolio logic. """ ifevent. type == 'SIGNAL': order _event = self. generate _naive _order(event) self. events. put(order _event) The penultimate method in the Portfolio is the generation of an equity curve. This simply creates a returns stream, useful for performance calculations, and then normalises the equity curve to be percentage based. Thus the account initial size is equal to 1. 0, as opposed to the absolute dollar amount: # portfolio. py def create _equity _curve _dataframe(self): """ Creates a pandas Data Frame from the all _holdings list of dictionaries. """ curve = pd. Data Frame(self. all _holdings) curve. set _index('datetime', inplace=True) curve['returns'] = curve['total']. pct _change() curve['equity _curve'] = (1. 0+curve['returns']). cumprod() self. equity _curve = curve The final method in the Portfolio is the output of the equity curve and various performance statistics related to the strategy. The final line outputs a file, equity. csv, to the same directory as the code, which can loaded into a Matplotlib Python script (or a spreadsheet such as MS Excel or Libre Office Calc) for subsequent analysis. Note that the Drawdown Duration is given in terms of the absolute number of "bars" that the drawdown carried on for, as opposed to a particular timeframe. def output _summary _stats(self): """ Creates a list of summary statistics for the portfolio. """ total _return = self. equity _curve['equity _curve'][-1] returns = self. equity _curve['returns'] pnl = self. equity _curve['equity _curve'] sharpe _ratio = create _sharpe _ratio(returns, periods=252 *60*6. 5) drawdown, max _dd, dd _duration = create _drawdowns(pnl) self. equity _curve['drawdown'] = drawdown stats = [("Total Return", "%0. 2f%%" % \ ((total _return-1. 0) *100. 0)), ("Sharpe Ratio", "%0. 2f" % sharpe _ratio), ("Max Drawdown", "%0. 2f%%" % (max _dd*100. 0)), ("Drawdown Duration", "%d" % dd _duration)]
150 self. equity _curve. to _csv('equity. csv') return stats The Portfolio object is the most complex aspect of the entire event-driven backtest system. The implementation here, while intricate, is relatively elementary in its handling of positions. 14. 2. 5 Execution Handler In this section we will study the execution of trade orders by creating a class hierarchy that will represent a simulated order handling mechanism and ultimately tie into a brokerage or other means of market connectivity. The Execution Handler described here is exceedingly simple, since it fills all orders at the current market price. This is highly unrealistic, but serves as a good baseline for improvement. As with the previous abstract base class hierarchies, we must import the necessary proper-ties and decorators from the abclibrary. In addition we need to import the Fill Event and Order Event : #!/usr/bin/python #-*-coding: utf-8-*-# execution. py from __future __import print _function from abc import ABCMeta, abstractmethod import datetime try: import Queue as queue except Import Error: import queue from event import Fill Event, Order Event The Execution Handler is similar to previous abstract base classes and simply has one pure virtual method, execute _order: # execution. py class Execution Handler(object): """ The Execution Handler abstract class handles the interaction between a set of order objects generated by a Portfolio and the ultimate set of Fill objects that actually occur in the market. The handlers can be used to subclass simulated brokerages or live brokerages, with identical interfaces. This allows strategies to be backtested in a very similar manner to the live trading engine. """ __metaclass __= ABCMeta @abstractmethod def execute _order(self, event): """ Takes an Order event and executes it, producing a Fill event that gets placed onto the Events queue.
151 Parameters: event-Contains an Event object with order information. """ raise Not Implemented Error("Should implement execute _order()") In order to backtest strategies we need to simulate how a trade will be transacted. The simplest possible implementation is to assume all orders are filled at the current market price for all quantities. This is clearly extremely unrealistic and a big part of improving backtest realism will come from designing more sophisticated models of slippage and market impact. Note that the Fill Event is given a value of Nonefor the fill _cost(see the penultimate line in execute _order) as we have already taken care of the cost of fill in the Portfolio object described above. In a more realistic implementation we would make use of the "current" market data value to obtain a realistic fill cost. I have simply utilised ARCA as the exchange although for backtesting purposes this is purely a string placeholder. In a live execution environment this venue dependence would be far more important: # execution. py class Simulated Execution Handler(Execution Handler): """ The simulated execution handler simply converts all order objects into their equivalent fill objects automatically without latency, slippage or fill-ratio issues. This allows a straightforward "first go" test of any strategy, before implementation with a more sophisticated execution handler. """ def __init __(self, events): """ Initialises the handler, setting the event queues up internally. Parameters: events-The Queue of Event objects. """ self. events = events def execute _order(self, event): """ Simply converts Order objects into Fill objects naively, i. e. without any latency, slippage or fill ratio problems. Parameters: event-Contains an Event object with order information. """ ifevent. type == 'ORDER': fill _event = Fill Event( datetime. datetime. utcnow(), event. symbol, 'ARCA', event. quantity, event. direction, None ) self. events. put(fill _event)
152 14. 2. 6 Backtest We are now in a position to create the Backtest class hierarchy. The Backtest object encapsulates theevent-handlinglogicandessentiallytiestogetheralloftheotherclassesthatwehavediscussed above. The Backtest object is designed to carry out a nested while-loop event-driven system in order to handle the events placed on the Event Queue object. The outer while-loop is known as the "heartbeat loop" and decides the temporal resolution of the backtesting system. In a live environment this value will be a positive number, such as 600 seconds (every ten minutes). Thus the market data and positions will only be updated on this timeframe. For the backtester described here the "heartbeat" can be set to zero, irrespective of the strategy frequency, since the data is already available by virtue of the fact it is historical! We can run the backtest at whatever speed we like, since the event-driven system is agnostic towhenthe data became available, so long as it has an associated timestamp. Hence I've only included it to demonstrate how a live trading engine would function. The outer loop thus ends once the Data Handler lets the Backtest object know, by using a boolean continue_backtest attribute. The inner while-loop actually processes the signals and sends them to the correct component depending upon the event type. Thus the Event Queue is continually being populated and depopulated with events. This is what it means for a system to be event-driven. The first task is to import the necessary libraries. We import pprint ("pretty-print"), because we want to display the stats in an output-friendly manner: #!/usr/bin/python #-*-coding: utf-8-*-# backtest. py from __future __import print _function import datetime import pprint try: import Queue as queue except Import Error: import queue import time The initialisation of the Backtest object requires the CSV directory, the full symbol list of traded symbols, the initial capital, the heartbeat time in milliseconds, the start datetime stamp of the backtest as well as the Data Handler, Execution Handler, Portfolio and Strategy objects. A Queue is used to hold the events. The signals, orders and fills are counted: # backtest. py class Backtest(object): """ Enscapsulates the settings and components for carrying out an event-driven backtest. """ def __init __( self, csv _dir, symbol _list, initial _capital, heartbeat, start _date, data _handler, execution _handler, portfolio, strategy ): """ Initialises the backtest.
153 Parameters: csv_dir-The hard root to the CSV data directory. symbol _list-The list of symbol strings. intial _capital-The starting capital for the portfolio. heartbeat-Backtest "heartbeat" in seconds start _date-The start datetime of the strategy. data _handler-(Class) Handles the market data feed. execution _handler-(Class) Handles the orders/fills for trades. portfolio-(Class) Keeps track of portfolio current and prior positions. strategy-(Class) Generates signals based on market data. """ self. csv _dir = csv _dir self. symbol _list = symbol _list self. initial _capital = initial _capital self. heartbeat = heartbeat self. start _date = start _date self. data _handler _cls = data _handler self. execution _handler _cls = execution _handler self. portfolio _cls = portfolio self. strategy _cls = strategy self. events = queue. Queue() self. signals = 0 self. orders = 0 self. fills = 0 self. num _strats = 1 self. _generate _trading _instances() The first method, _generate_trading_instances, attaches all of the trading objects (Data-Handler, Strategy, Portfolio and Execution Handler) to various internal members: # backtest. py def _generate _trading _instances(self): """ Generates the trading instance objects from their class types. """ print ( "Creating Data Handler, Strategy, Portfolio and Execution Handler" ) self. data _handler = self. data _handler _cls(self. events, self. csv _dir, self. symbol _list) self. strategy = self. strategy _cls(self. data _handler, self. events) self. portfolio = self. portfolio _cls(self. data _handler, self. events, self. start _date, self. initial _capital) self. execution _handler = self. execution _handler _cls(self. events) The _run_backtest method is where the signal handling of the Backtest engine is carried out. As described above there are two while loops, one nested within another. The outer keeps track of the heartbeat of the system, while the inner checks if there is an event in the Queue object, and acts on it by calling the appropriate method on the necessary object.
154 For a Market Event, the Strategy object is told to recalculate new signals, while the Portfolio object is told to reindex the time. If a Signal Event object is received the Portfolio is told to handle the new signal and convert it into a set of Order Events, if appropriate. If an Order Event is received the Execution Handler is sent the order to be transmitted to the broker (if in a real trading setting). Finally, if a Fill Event is received, the Portfolio will update itself to be aware of the new positions: # backtest. py def _run_backtest(self): """ Executes the backtest. """ i = 0 while True: i += 1 print i # Update the market bars ifself. data _handler. continue _backtest == True: self. data _handler. update _bars() else : break # Handle the events while True: try: event = self. events. get(False) except queue. Empty: break else : ifevent is not None: ifevent. type == 'MARKET': self. strategy. calculate _signals(event) self. portfolio. update _timeindex(event) elif event. type == 'SIGNAL': self. signals += 1 self. portfolio. update _signal(event) elif event. type == 'ORDER': self. orders += 1 self. execution _handler. execute _order(event) elif event. type == 'FILL': self. fills += 1 self. portfolio. update _fill(event) time. sleep(self. heartbeat) Once the backtest simulation is complete the performance of the strategy can be displayed to the terminal/console. The equity curve pandas Data Frame is created and the summary statistics are displayed, as well as the count of Signals, Orders and Fills: # backtest. py def _output _performance(self): """ Outputs the strategy performance from the backtest.
155 """ self. portfolio. create _equity _curve _dataframe() print ("Creating summary stats... ") stats = self. portfolio. output _summary _stats() print ("Creating equity curve... ") print (self. portfolio. equity _curve. tail(10)) pprint. pprint(stats) print ("Signals: %s" % self. signals) print ("Orders: %s" % self. orders) print ("Fills: %s" % self. fills) The last method to be implemented is simulate _trading. It simply calls the two previously described methods, in order: # backtest. py def simulate _trading(self): """ Simulates the backtest and outputs portfolio performance. """ self. _run_backtest() self. _output _performance() This concludes the event-driven backtester operational objects. 14. 3 Event-Driven Execution Abovewedescribedabasic Execution Handler classthatsimplycreatedacorresponding Fill Event instance for every Order Event. This is precisely what we need for a "first pass" backtest, but when we wish to actually hook up the system to a brokerage, we need more sophisticated han-dling. In this section we define the IBExecution Handler, a class that allows us to talk to the popular Interactive Brokers API and thus automate our execution. The essential idea of the IBExecution Handler class is to receive Order Event instances from the events queue and then to execute them directly against the Interactive Brokers order API using the open source Ib Py library. The class will also handle the "Server Response" messages sent back via the API. At this stage, the only action taken will be to create corresponding Fill Event instances that will then be sent back to the events queue. The class itself could feasibly become rather complex, with execution optimisation logic as well as sophisticated error handling. However, I have opted to keep it relatively simple here so that you can see the main ideas and extend it in the direction that suits your particular trading style. As always, the first task is to create the Python file and import the necessary libraries. The file is called ib_execution. py and lives in the same directory as the other event-driven files. We import the necessary date/time handling libraries, the Ib Py objects and the specific Event objects that are handled by IBExecution Handler : #!/usr/bin/python #-*-coding: utf-8-*-# ib _execution. py from __future __import print _function import datetime import time
156 from ib. ext. Contract import Contract from ib. ext. Order import Order from ib. opt import ib Connection, message from event import Fill Event, Order Event from execution import Execution Handler We now define the IBExecution Handler class. The __init __constructor firstly requires knowledge of the eventsqueue. It also requires specification of order _routing, which I've defaulted to "SMART". If you have specific exchange requirements, you can specify them here. The default currency has also been set to US Dollars. Within the method we create a fill _dictdictionary, needed later for usage in generating Fill Event instances. We also create a tws_connconnection object to store our connection information to the Interactive Brokers API. We also have to create an initial default order _id, which keeps track of all subsequent orders to avoid duplicates. Finally we register the message handlers (which we'll define in more detail below): # ib _execution. py class IBExecution Handler(Execution Handler): """ Handles order execution via the Interactive Brokers API, for use against accounts when trading live directly. """ def __init __( self, events, order _routing="SMART", currency="USD" ): """ Initialises the IBExecution Handler instance. """ self. events = events self. order _routing = order _routing self. currency = currency self. fill _dict = {} self. tws _conn = self. create _tws_connection() self. order _id = self. create _initial _order _id() self. register _handlers() The IB API utilises a message-based event system that allows our class to respond in partic-ular ways to certain messages, in a similar manner to the event-driven backtester itself. I've not included any real error handling (for the purposes of brevity), beyond output to the terminal, via the _error _handler method. The _reply _handler method, on the other hand, is used to determine if a Fill Event instance needs to be created. The method asks if an "open Order" message has been received and checks whether an entry in our fill _dictfor this particular order Id has already been set. If not then one is created. If it sees an "order Status" message and that particular message states than an order has been filled, then it calls create _fillto create a Fill Event. It also outputs the message to the terminal for logging/debug purposes: # ib _execution. py def _error _handler(self, msg): """
157 Handles the capturing of error messages """ # Currently no error handling. print ("Server Error: %s" % msg) def _reply _handler(self, msg): """ Handles of server replies """ # Handle open order order Id processing ifmsg. type Name == "open Order" and \ msg. order Id == self. order _idand \ not self. fill _dict. has _key(msg. order Id): self. create _fill _dict _entry(msg) # Handle Fills ifmsg. type Name == "order Status" and \ msg. status == "Filled" and \ self. fill _dict[msg. order Id]["filled"] == False: self. create _fill(msg) print ("Server Response: %s, %s\n" % (msg. type Name, msg)) The following method, create _tws_connection, creates a connection to the IB API using the Ib Py ib Connection object. It uses a default port of 7496 and a default client Id of 10. Once the object is created, the connect method is called to perform the connection: # ib _execution. py def create _tws_connection(self): """ Connect to the Trader Workstation (TWS) running on the usual port of 7496, with a client Id of 10. The client Id is chosen by us and we will need separate IDs for both the execution connection and market data connection, if the latter is used elsewhere. """ tws_conn = ib Connection() tws_conn. connect() return tws_conn To keep track of separate orders (for the purposes of tracking fills) the following method create _initial _order _idis used. I've defaulted it to "1", but a more sophisticated approach would be th query IB for the latest available ID and use that. You can always reset the current API order ID via the Trader Workstation > Global Configuration > API Settings panel: # ib _execution. py def create _initial _order _id(self): """ Creates the initial order ID used for Interactive Brokers to keep track of submitted orders. """ # There is scope for more logic here, but we # will use "1" as the default for now. return 1 The following method, register _handlers, simply registers the error and reply handler methods defined above with the TWS connection: # ib _execution. py
158 def register _handlers(self): """ Register the error and server reply message handling functions. """ # Assign the error handling function defined above # to the TWS connection self. tws _conn. register(self. _error _handler, 'Error') # Assign all of the server reply messages to the # reply _handler function defined above self. tws _conn. register All(self. _reply _handler) In order to actually transact a trade it is necessary to create an Ib Py Contract instance and then pair it with an Ib Py Orderinstance, which will be sent to the IB API. The following method, create _contract, generatesthefirstcomponentofthispair. Itexpectsatickersymbol, a security type (e. g. stock or future), an exchange/primary exchange and a currency. It returns the Contract instance: # ib _execution. py def create _contract(self, symbol, sec _type, exch, prim _exch, curr): """ Create a Contract object defining what will be purchased, at which exchange and in which currency. symbol-The ticker symbol for the contract sec_type-The security type for the contract ('STK' is 'stock') exch-The exchange to carry out the contract on prim _exch-The primary exchange to carry out the contract on curr-The currency in which to purchase the contract """ contract = Contract() contract. m _symbol = symbol contract. m _sec Type = sec _type contract. m _exchange = exch contract. m _primary Exch = prim _exch contract. m _currency = curr return contract The following method, create _order, generates the second component of the pair, namely the Orderinstance. It expects an order type (e. g. market or limit), a quantity of the asset to trade and an "action" (buy or sell). It returns the Orderinstance: # ib _execution. py def create _order(self, order _type, quantity, action): """ Create an Order object (Market/Limit) to go long/short. order _type-'MKT', 'LMT' for Market or Limit orders quantity-Integral number of assets to order action-'BUY' or 'SELL' """ order = Order() order. m _order Type = order _type order. m _total Quantity = quantity
159 order. m _action = action return order In order to avoid duplicating Fill Event instances for a particular order ID, we utilise a dictionary called the fill _dictto store keys that match particular order IDs. When a fill has beengeneratedthe"filled"keyofanentryforaparticularorder IDissetto True. Ifasubsequent "Server Response" message is received from IB stating that an order has been filled (and is a duplicatemessage)itwillnotleadtoanewfill. Thefollowingmethod create _fill _dict _entry carries this out: # ib _execution. py def create _fill _dict _entry(self, msg): """ Creates an entry in the Fill Dictionary that lists order Ids and provides security information. This is needed for the event-driven behaviour of the IB server message behaviour. """ self. fill _dict[msg. order Id] = { "symbol": msg. contract. m _symbol, "exchange": msg. contract. m _exchange, "direction": msg. order. m _action, "filled": False } The following method, create _fill, actually creates the Fill Event instance and places it onto the events queue: # ib _execution. py def create _fill(self, msg): """ Handles the creation of the Fill Event that will be placed onto the events queue subsequent to an order being filled. """ fd = self. fill _dict[msg. order Id] # Prepare the fill data symbol = fd["symbol"] exchange = fd["exchange"] filled = msg. filled direction = fd["direction"] fill _cost = msg. avg Fill Price # Create a fill event object fill = Fill Event( datetime. datetime. utcnow(), symbol, exchange, filled, direction, fill _cost ) # Make sure that multiple messages don't create # additional fills. self. fill _dict[msg. order Id]["filled"] = True # Place the fill event onto the event queue self. events. put(fill _event)
160 Now that all of the preceeding methods having been implemented it remains to override the execute _ordermethod from the Execution Handler abstract base class. This method actually carries out the order placement with the IB API. We first check that the event being received to this method is actually an Order Event and then prepare the Contract and Orderobjects with their respective parameters. Once both are created the Ib Py method place Order of the connection object is called with an associated order _id. It isextremely important to call the time. sleep(1) method to ensure the order actually goes through to IB. Removal of this line leads to inconsistent behaviour of the API, at least on my system! Finally, we increment the order ID to ensure we don't duplicate orders: # ib _execution. py def execute _order(self, event): """ Creates the necessary Interactive Brokers order object and submits it to IB via their API. The results are then queried in order to generate a corresponding Fill object, which is placed back on the event queue. Parameters: event-Contains an Event object with order information. """ ifevent. type == 'ORDER': # Prepare the parameters for the asset order asset = event. symbol asset _type = "STK" order _type = event. order _type quantity = event. quantity direction = event. direction # Create the Interactive Brokers contract via the # passed Order event ib_contract = self. create _contract( asset, asset _type, self. order _routing, self. order _routing, self. currency ) # Create the Interactive Brokers order via the # passed Order event ib_order = self. create _order( order _type, quantity, direction ) # Use the connection to the send the order to IB self. tws _conn. place Order( self. order _id, ib _contract, ib _order ) # NOTE: This following line is crucial. # It ensures the order goes through! time. sleep(1) # Increment the order ID for this session
161 self. order _id += 1 This class forms the basis of an Interactive Brokers execution handler and can be used in place of the simulated execution handler, which is only suitable for backtesting. Before the IB handler can be utilised, however, it is necessary to create a live market feed handler to replace the historical data feed handler of the backtester system. In this way we are reusing as much as possible from the backtest and live systems to ensure that code "swap out" is minimised and thus behaviour across both is similar, if not identical.
162
Chapter 15 Trading Strategy Implementation In this chapter we are going to consider the full implementation of trading strategies using the aforementioned event-driven backtesting system. In particular we will generate equity curves for all trading strategies using notional portfolio amounts, thus simulating the concepts of margin/leverage, which is a far more realistic approach compared to vectorised/returns based approaches. The first set of strategies are able to be carried out with freely available data, either from Yahoo Finance, Google Finance or Quandl. These strategies are suitable for long-term algorith-mic traders who may wish to only study the trade signal generation aspect of the strategy or even the full end-to-end system. Such strategies often possess smaller Sharpe ratios, but are far easier to implement and execute. The latter strategy is carried out using intraday equities data. This data is often not freely available and a commercial data vendor is usually necessary to provide sufficient quality and quantity of data. I myself use DTN IQFeed for intraday bars. Such strategies often possess much larger Sharpe ratios, but require more sophisticated implementation as the high frequency requires extensive automation. We will see that our first two attempts at creating a trading strategy on interday data are not altogether successful. It can be challenging to come up with a profitable trading strategy on interday data once transaction costs have been taken into account. The latter is something that many texts on algorithmic trading tend to leave out. However, it is my belief that as many factors as possible must be added to the backtest in order to minimises surprises going forward. In addition, this book is primarily about how to effectively create a realistic interday or intraday backtesting system (as well as a live execution platform) and less about particular individual strategies. It is far harder to create a realistic robust backtester than it is to find trading strategies on the internet! While the first two strategies presented are not particularly attractive, the latter strategy (on intraday data) performs well and gives us confidence in using higher frequency data. 15. 1 Moving Average Crossover Strategy I'm quite fond of the Moving Average Crossover technical system because it is the first non-trivial strategy that is extremely handy for testing a new backtesting implementation. On a daily timeframe, over a number of years, with long lookback periods, few signals are generated on a single stock and thus it is easy to manually verify that the system is behaving as would be expected. In order to actually generate such a simulation based on the prior backtesting code we need to subclassthe Strategy objectasdescribedinthepreviouschaptertocreatethe Moving Average Cross Strategy object, which will contain the logic of the simple moving averages and the generation of trading signals. In addition we need to create the __main __function that will load the Backtest object and actually encapsulate the execution of the program. The following file, mac. py, contains both of these objects. 163
164 The first task, as always, is to correctly import the necessary components. We are importing nearly all of the objects that have been described in the previous chapter: #!/usr/bin/python #-*-coding: utf-8-*-# mac. py from __future __import print _function import datetime import numpy as np import pandas as pd import statsmodels. api as sm from strategy import Strategy from event import Signal Event from backtest import Backtest from data import Historic CSVData Handler from execution import Simulated Execution Handler from portfolio import Portfolio Now we turn to the creation of the Moving Average Cross Strategy. The strategy requires both the bars Data Handler, the events Event Queue and the lookback periods for the simple moving averages that are going to be employed within the strategy. I've chosen 100 and 400 as the "short" and "long" lookback periods for this strategy. The final attribute, bought, is used to tell the Strategy when the backtest is actually "in the market". Entry signals are only generated if this is "OUT" and exit signals are only ever generated if this is "LONG" or "SHORT": # mac. py class Moving Average Cross Strategy(Strategy): """ Carries out a basic Moving Average Crossover strategy with a short/long simple weighted moving average. Default short/long windows are 100/400 periods respectively. """ def __init __( self, bars, events, short _window=100, long _window=400 ): """ Initialises the Moving Average Cross Strategy. Parameters: bars-The Data Handler object that provides bar information events-The Event Queue object. short _window-The short moving average lookback. long _window-The long moving average lookback. """ self. bars = bars self. symbol _list = self. bars. symbol _list self. events = events self. short _window = short _window self. long _window = long _window
165 # Set to True if a symbol is in the market self. bought = self. _calculate _initial _bought() Since the strategy begins out of the market we set the initial "bought" value to be "OUT", for each symbol: # mac. py def _calculate _initial _bought(self): """ Adds keys to the bought dictionary for all symbols and sets them to 'OUT'. """ bought = {} for sinself. symbol _list: bought[s] = 'OUT' return bought The core of the strategy is the calculate _signals method. It reacts to a Market Event object and for each symbol traded obtains the latest Nbar closing prices, where Nis equal to the largest lookback period. It then calculates both the short and long period simple moving averages. The rule of the strategy is to enter the market (go long a stock) when the short moving average value exceeds the long moving average value. Conversely, if the long moving average value exceeds the short moving average value the strategy is told to exit the market. This logic is handled by placing a Signal Event object on the events Event Queue in each of the respective situations and then updating the "bought" attribute (per symbol) to be "LONG" or "OUT", respectively. Since this is a long-only strategy, we won't be considering "SHORT" positions: # mac. py def calculate _signals(self, event): """ Generates a new set of signals based on the MAC SMA with the short window crossing the long window meaning a long entry and vice versa for a short entry. Parameters event-A Market Event object. """ ifevent. type == 'MARKET': for sinself. symbol _list: bars = self. bars. get _latest _bars _values( s, "adj _close", N=self. long _window ) bar_date = self. bars. get _latest _bar_datetime(s) ifbars is not None and bars != []: short _sma = np. mean(bars[-self. short _window:]) long _sma = np. mean(bars[-self. long _window:]) symbol = s dt = datetime. datetime. utcnow() sig_dir = "" ifshort _sma > long _sma and self. bought[s] == "OUT": print ("LONG: %s" % bar _date) sig_dir = 'LONG'
166 signal = Signal Event(1, symbol, dt, sig _dir, 1. 0) self. events. put(signal) self. bought[s] = 'LONG' elif short _sma < long _sma and self. bought[s] == "LONG": print ("SHORT: %s" % bar _date) sig_dir = 'EXIT' signal = Signal Event(1, symbol, dt, sig _dir, 1. 0) self. events. put(signal) self. bought[s] = 'OUT' That concludes the Moving Average Cross Strategy object implementation. The final task of the entire backtesting system is populate a __main __method in mac. pyto actually execute the backtest. Firstly, make sure to change the value of csv_dirto the absolute path of your CSV file directory for the financial data. You will also need to download the CSV file of the AAPL stock (from Yahoo Finance), which is given by the following link (for Jan 1st 1990 to Jan 1st 2002), since this is the stock we will be testing the strategy on: http://ichart. finance. yahoo. com/table. csv?s=AAPL&a=00&b=1&c=1990&d=00&e=1 &f=2002&g=d&ignore=. csv Make sure to place this file in the path pointed to from the main function in csv_dir. The __main __function simply instantiates a new backtest object and then calls the simu-late_trading method on it to execute it: # mac. py if__name __== " __main __": csv_dir = '/path/to/your/csv/file' # CHANGE THIS! symbol _list = ['AAPL'] initial _capital = 100000. 0 heartbeat = 0. 0 start _date = datetime. datetime(1990, 1, 1, 0, 0, 0) backtest = Backtest( csv_dir, symbol _list, initial _capital, heartbeat, start _date, Historic CSVData Handler, Simulated Execution Handler, Portfolio, Moving Average Cross Strategy ) backtest. simulate _trading() To run the code, make sure you have already set up a Python environment (as described in the previous chapters) and then navigate the directory where your code is stored. You should simply be able to run: python mac. py You will see the following listing (truncated due to the bar count printout!):.... 3029 3030 Creating summary stats... Creating equity curve... AAPL cash commission total returns equity _curve drawdown datetime 2001-12-18 0 99211 13 99211 0 0. 99211 0. 025383 2001-12-19 0 99211 13 99211 0 0. 99211 0. 025383 2001-12-20 0 99211 13 99211 0 0. 99211 0. 025383 2001-12-21 0 99211 13 99211 0 0. 99211 0. 025383
167 2001-12-24 0 99211 13 99211 0 0. 99211 0. 025383 2001-12-26 0 99211 13 99211 0 0. 99211 0. 025383 2001-12-27 0 99211 13 99211 0 0. 99211 0. 025383 2001-12-28 0 99211 13 99211 0 0. 99211 0. 025383 2001-12-31 0 99211 13 99211 0 0. 99211 0. 025383 2001-12-31 0 99211 13 99211 0 0. 99211 0. 025383 [('Total Return', '-0. 79%'), ('Sharpe Ratio', '-0. 09'), ('Max Drawdown', '2. 56%'), ('Drawdown Duration', '2312')] Signals: 10 Orders: 10 Fills: 10 The performance of this strategy can be seen in Fig 15. 1: Figure 15. 1: Equity Curve, Daily Returns and Drawdowns for the Moving Average Crossover strategy Evidently the returns and Sharpe Ratio are not stellar for AAPL stock on this particular set of technical indicators! Clearly we have some work to do in the next set of strategies to find a system that can generate positive performance.
168 15. 2 S&P500 Forecasting Trade In this sectiuon we will consider a trading strategy built around the forecasting engine discussed in prior chapters. We will attempt to trade off the predictions made by a stock market forecaster. We are going to attempt to forecast SPY, which is the ETF that tracks the value of the S&P500. Ultimately we want to answer the question as to whether a basic forecasting algorithm using lagged price data, with slight predictive performance, provides us with any benefit over a buy-and-hold strategy. The rules for this strategy are as follows: 1. Fit a forecasting model to a subset of S&P500 data. This could be Logistic Regression, a Discriminant Analyser (Linear or Quadratic), a Support Vector Machine or a Random Forest. The procedure to do this was outlined in the Forecasting chapter. 2. Use two prior lags of adjusted closing returns data as a predictor for tomorrow's returns. If the returns are predicted as positive then go long. If the returns are predicted as negative then exit. We're not going to consider short selling for this particular strategy. Implementation For this strategy we are going to create the snp_forecast. py file and import the following necessary libraries: #!/usr/bin/python #-*-coding: utf-8-*-# snp _forecast. py from __future __import print _function import datetime import pandas as pd from sklearn. qda import QDA from strategy import Strategy from event import Signal Event from backtest import Backtest from data import Historic CSVData Handler from execution import Simulated Execution Handler from portfolio import Portfolio from create _lagged _series import create _lagged _series We have imported Pandas and Scikit-Learn in order to carry out the fitting procedure for the supervised classifier model. We have also imported the necessary classes from the event-driven backtester. Finally, we have imported the create _lagged _seriesfunction, which we used in the Forecasting chapter. The next step is to create the SPYDaily Forecast Strategy as a subclass of the Strategy abstract base class. Since we will "hardcode" the parameters of the strategy directly into the class, for simplicity, the only parameters necessary for the __init __constructor are the bars data handler and the eventsqueue. We set the self. model _***start/end/test dates as datetime objects and then tell the class that we are out of the market ( self. long _market = False ). Finally, we set self. model to be the trained model from the create _symbol _forecast _modelbelow: # snp _forecast. py class SPYDaily Forecast Strategy(Strategy): """
169 S&P500 forecast strategy. It uses a Quadratic Discriminant Analyser to predict the returns for a subsequent time period and then generated long/exit signals based on the prediction. """ def __init __(self, bars, events): self. bars = bars self. symbol _list = self. bars. symbol _list self. events = events self. datetime _now = datetime. datetime. utcnow() self. model _start _date = datetime. datetime(2001,1,10) self. model _end_date = datetime. datetime(2005,12,31) self. model _start _test _date = datetime. datetime(2005,1,1) self. long _market = False self. short _market = False self. bar _index = 0 self. model = self. create _symbol _forecast _model() Herewedefinethe create _symbol _forecast _model. Itessentiallycallsthe create _lagged _series function, which produces a Pandas Data Frame with five daily returns lags for each current pre-dictor. We then consider only the two most recent of these lags. This is because we are making the modelling decision that the predictive power of earlier lags is likely to be minimal. At this stage we create the training and test data, the latter of which can be used to test our model if we wish. I have opted to not output testing data, since we have already trained the model before in the Forecasting chapter. Finally we fit the training data to the Quadratic Discriminant Analyser and then return the model. Note that we could easily replace the model with a Random Forest, Support Vector Machine or Logistic Regression, for instance. All we need to do is import the correct library from Scikit-Learn and simply replace the model = QDA() line: # snp _forecast. py def create _symbol _forecast _model(self): # Create a lagged series of the S&P500 US stock market index snpret = create _lagged _series( self. symbol _list[0], self. model _start _date, self. model _end_date, lags=5 ) # Use the prior two days of returns as predictor # values, with direction as the response X = snpret[["Lag1","Lag2"]] y = snpret["Direction"] # Create training and test sets start _test = self. model _start _test _date X_train = X[X. index < start _test] X_test = X[X. index >= start _test] y_train = y[y. index < start _test] y_test = y[y. index >= start _test] model = QDA() model. fit(X _train, y _train) return model
170 At this stage we are ready to override the calculate _signals method of the Strategy base class. We firstly calculate some convenience parameters that enter our Signal Event object and then only generate a set of signals if we have received a Market Event object (a basic sanity check). We wait for five bars to have elapsed (i. e. five days in this strategy!) and then obtain the lagged returns values. We then wrap these values in a Pandas Series so that the predict method of the model will function correctly. We then calculate a prediction, which manifests itself as a +1 or-1. If the prediction is a +1 and we are not already long the market, we create a Signal Event to go long and let the class know we are now in the market. If the prediction is-1 and we are long the market, then we simply exit the market: # snp _forecast. py def calculate _signals(self, event): """ Calculate the Signal Events based on market data. """ sym = self. symbol _list[0] dt = self. datetime _now ifevent. type == 'MARKET': self. bar _index += 1 ifself. bar _index > 5: lags = self. bars. get _latest _bars _values( self. symbol _list[0], "returns", N=3 ) pred _series = pd. Series( { 'Lag1': lags[1] *100. 0, 'Lag2': lags[2] *100. 0 } ) pred = self. model. predict(pred _series) ifpred > 0 and not self. long _market: self. long _market = True signal = Signal Event(1, sym, dt, 'LONG', 1. 0) self. events. put(signal) ifpred < 0 and self. long _market: self. long _market = False signal = Signal Event(1, sym, dt, 'EXIT', 1. 0) self. events. put(signal) Inordertorunthestrategyyouwillneedtodownloada CSVfilefrom Yahoo Financefor SPY and place it in a suitable directory (note that you will need to change your path below!). We then wrapthebacktestupviathe Backtest classandcarryoutthetestbycalling simulate _trading : # snp _forecast. py if__name __== " __main __": csv_dir = '/path/to/your/csv/file' # CHANGE THIS! symbol _list = ['SPY'] initial _capital = 100000. 0 heartbeat = 0. 0 start _date = datetime. datetime(2006,1,3) backtest = Backtest(
171 csv_dir, symbol _list, initial _capital, heartbeat, start _date, Historic CSVData Handler, Simulated Execution Handler, Portfolio, SPYDaily Forecast Strategy ) backtest. simulate _trading() The output of the strategy is as follows and is net of transaction costs:.... 2209 2210 Creating summary stats... Creating equity curve... SPY cash commission total returns equity _curve \ datetime 2014-09-29 19754 90563. 3 349. 7 110317. 3-0. 000326 1. 103173 2014-09-30 19702 90563. 3 349. 7 110265. 3-0. 000471 1. 102653 2014-10-01 19435 90563. 3 349. 7 109998. 3-0. 002421 1. 099983 2014-10-02 19438 90563. 3 349. 7 110001. 3 0. 000027 1. 100013 2014-10-03 19652 90563. 3 349. 7 110215. 3 0. 001945 1. 102153 2014-10-06 19629 90563. 3 349. 7 110192. 3-0. 000209 1. 101923 2014-10-07 19326 90563. 3 349. 7 109889. 3-0. 002750 1. 098893 2014-10-08 19664 90563. 3 349. 7 110227. 3 0. 003076 1. 102273 2014-10-09 19274 90563. 3 349. 7 109837. 3-0. 003538 1. 098373 2014-10-09 0 109836. 0 351. 0 109836. 0-0. 000012 1. 098360 drawdown datetime 2014-09-29 0. 003340 2014-09-30 0. 003860 2014-10-01 0. 006530 2014-10-02 0. 006500 2014-10-03 0. 004360 2014-10-06 0. 004590 2014-10-07 0. 007620 2014-10-08 0. 004240 2014-10-09 0. 008140 2014-10-09 0. 008153 [('Total Return', '9. 84%'), ('Sharpe Ratio', '0. 54'), ('Max Drawdown', '5. 99%'), ('Drawdown Duration', '811')] Signals: 270 Orders: 270 Fills: 270 The following visualisation in Fig 15. 2 shows the Equity Curve, the Daily Returns and the Drawdown of the strategy as a function of time: Note immediately that the performance is not great! We have a Sharpe Ratio < 1 but a reasonable drawdown of just under 6%. It turns out that if we had simply bought and held SPY in this time period we would have performed similarly, if slightly worse. Hence we have not actually gained very much from our predictive strategy once transaction costs are included. I specifically wanted to include this example because it uses an "end to end" realistic implementation of such a strategy that takes into account conservative, realistic transaction costs. As can be seen it is not easy to make a predictive forecaster on daily data that produces good performance!
172 Figure 15. 2: Equity Curve, Daily Returns and Drawdowns for the SPY forecast strategy Our final strategy will make use of other time series and a higher frequency. We will see that performance can be improved dramatically after modifying certain aspects of the system. 15. 3 Mean-Reverting Equity Pairs Trade In order to seek higher Sharpe ratios for our trading, we need to consider higher-frequency intraday strategies. The first major issue is that obtaining data is significantly less straightforward because high qualityintradaydataisusuallynotfree. Asstatedabove Iuse DTNIQFeedforintradayminutely bars and thus you will need your own DTN account to obtain the data required for this strategy. The second issue is that backtesting simulations take substantially longer, especially with the event-driven model that we have constructed here. Once we begin considering a backtest of a diversified portfolio of minutely data spanning years, and then performing any parameter optimisation, we rapidly realise that simulations can take hours or even days to calculate on a modern desktop PC. This will need to be factored in to your research process. The third issue is that live execution will now need to be fully automated since we are edging into higher-frequency trading. This means that such execution environments and code must be highly reliable and bug-free, otherwise the potential for significant losses can occur. This strategy expands on the previous interday strategy above to make use of intraday data. In particular we are going to use minutely OHLCV bars, as opposed to daily OHLCV. The rules for the strategy are straightforward: 1. Identify a pair of equities that possess a residuals time series which has been statistically identified as mean-reverting. In this case, I have found two energy sector US equities with tickers AREX and WLL.
173 2. Create the residuals time series of the pair by performing a rolling linear regression, for a particular lookback window, via the ordinary least squares (OLS) algorithm. This lookback period is a parameter to be optimised. 3. Create a rolling z-score of the residuals time series of the same lookback period and use this to determine entry/exit thresholds for trading signals. 4. If the upper threshold is exceeded when not in the market then enter the market (long or short depending on direction of threshold excess). If the lower threshold is exceeded when in the market, exit the market. Once again, the upper and lower thresholds are parameters to be optimised. Indeedwecouldhaveusedthe Cointegrated Augmented Dickey-Fuller(CADF)testtoidentify an even more accurate hedging parameter. This would make an interesting extension of the strategy. Implementation The first step, as always, is to import the necessary libraries. We require pandas for the rolling _applymethod, which is used to apply the z-score calculation with a lookback win-dow on a rolling basis. We import statsmodels because it provides a means of calculating the ordinary least squares (OLS) algorithm for the linear regression, necessary to obtain the hedging ratio for the construction of the residuals. We also require a slightly modified Data Handler and Portfolio in order to carry out minutely bars trading on DTN IQFeed data. In order to create these files you can simply copy all of the code in portfolio. py anddata. py into the new files hft_portfolio. py and hft_data. py respectively and then modify the necessary sections, which I will outline below. Here is the import listing for intraday _mr. py: #!/usr/bin/python #-*-coding: utf-8-*-# intraday _mr. py from __future __import print _function import datetime import numpy as np import pandas as pd import statsmodels. api as sm from strategy import Strategy from event import Signal Event from backtest import Backtest from hft_data import Historic CSVData Handler HFT from hft_portfolio import Portfolio HFT from execution import Simulated Execution Handler In the following snippet we create the Intraday OLSMRStrategy class derived from the Strategy abstractbaseclass. Theconstructor __init __methodrequiresaccesstothe barshis-torical data provider, the eventsqueue, a zscore _lowthreshold and a zscore _highthreshold, used to determine when the residual series between the two pairs is mean-reverting. In addition, we specify the OLS lookback window (set to 100 here), which is a parameter that is subject to potential optimisation. At the start of the simulation we are neither long or short the market, so we set both self. long _marketandself. short _marketequal to False: # intraday _mr. py
174 class Intraday OLSMRStrategy(Strategy): """ Uses ordinary least squares (OLS) to perform a rolling linear regression to determine the hedge ratio between a pair of equities. The z-score of the residuals time series is then calculated in a rolling fashion and if it exceeds an interval of thresholds (defaulting to [0. 5, 3. 0]) then a long/short signal pair are generated (for the high threshold) or an exit signal pair are generated (for the low threshold). """ def __init __( self, bars, events, ols _window=100, zscore _low=0. 5, zscore _high=3. 0 ): """ Initialises the stat arb strategy. Parameters: bars-The Data Handler object that provides bar information events-The Event Queue object. """ self. bars = bars self. symbol _list = self. bars. symbol _list self. events = events self. ols _window = ols _window self. zscore _low = zscore _low self. zscore _high = zscore _high self. pair = ('AREX', 'WLL') self. datetime = datetime. datetime. utcnow() self. long _market = False self. short _market = False The following method, calculate _xy_signals, takes the current zscore (from the rolling calculation performed below) and determines whether new trading signals need to be generated. These signals are then returned. There are four potential states that we may be interested in. They are: 1. Long the market and below the negative zscore higher threshold 2. Long the market and between the absolute value of the zscore lower threshold 3. Short the market and above the positive zscore higher threshold 4. Short the market and between the absolute value of the zscore lower threshold In either case it is necessary to generate two signals, one for the first component of the pair (AREX) and one for the second component of the pair (WLL). If none of these conditions are reached, then a pair of Nonevalues are returned: # intraday _mr. py def calculate _xy_signals(self, zscore _last): """ Calculates the actual x, y signal pairings to be sent to the signal generator.
175 Parameters zscore _last-The current zscore to test against """ y_signal = None x_signal = None p0 = self. pair[0] p1 = self. pair[1] dt = self. datetime hr = abs(self. hedge _ratio) # If we're long the market and below the # negative of the high zscore threshold ifzscore _last <=-self. zscore _high and not self. long _market: self. long _market = True y_signal = Signal Event(1, p0, dt, 'LONG', 1. 0) x_signal = Signal Event(1, p1, dt, 'SHORT', hr) # If we're long the market and between the # absolute value of the low zscore threshold ifabs(zscore _last) <= self. zscore _low and self. long _market: self. long _market = False y_signal = Signal Event(1, p0, dt, 'EXIT', 1. 0) x_signal = Signal Event(1, p1, dt, 'EXIT', 1. 0) # If we're short the market and above # the high zscore threshold ifzscore _last >= self. zscore _high and not self. short _market: self. short _market = True y_signal = Signal Event(1, p0, dt, 'SHORT', 1. 0) x_signal = Signal Event(1, p1, dt, 'LONG', hr) # If we're short the market and between the # absolute value of the low zscore threshold ifabs(zscore _last) <= self. zscore _low and self. short _market: self. short _market = False y_signal = Signal Event(1, p0, dt, 'EXIT', 1. 0) x_signal = Signal Event(1, p1, dt, 'EXIT', 1. 0) return y_signal, x _signal The following method, calculate _signals _for_pairsobtains the latest set of bars for each component of the pair (in this case 100 bars) and uses them to construct an ordinary least squares based linear regression. This allows identification of the hedge ratio, necessary for the construction of the residuals time series. Once the hedge ratio is constructed, a spreadseries of residuals is constructed. The next step is to calculate the latest zscore from the residual series by subtracting its mean and dividing by its standard deviation over the lookback period. Finally, the y_signalandx_signalare calculated on the basis of this zscore. If the signals are not both Nonethen the Signal Event instances are sent back to the eventsqueue: # intraday _mr. py def calculate _signals _for_pairs(self): """ Generates a new set of signals based on the mean reversion strategy.
176 Calculates the hedge ratio between the pair of tickers. We use OLS for this, althought we should ideall use CADF. """ # Obtain the latest window of values for each # component of the pair of tickers y = self. bars. get _latest _bars _values( self. pair[0], "close", N=self. ols _window ) x = self. bars. get _latest _bars _values( self. pair[1], "close", N=self. ols _window ) ifyis not None and xis not None: # Check that all window periods are available iflen(y) >= self. ols _window and len(x) >= self. ols _window: # Calculate the current hedge ratio using OLS self. hedge _ratio = sm. OLS(y, x). fit(). params[0] # Calculate the current z-score of the residuals spread = y-self. hedge _ratio *x zscore _last = ((spread-spread. mean())/spread. std())[-1] # Calculate signals and add to events queue y_signal, x _signal = self. calculate _xy_signals(zscore _last) ify_signal is not None and x_signal is not None: self. events. put(y _signal) self. events. put(x _signal) The final method, calculate _signals is overidden from the base class and is used to check whether a received event from the queue is actually a Market Event, in which case the calculation of the new signals is carried out: # intraday _mr. py def calculate _signals(self, event): """ Calculate the Signal Events based on market data. """ ifevent. type == 'MARKET': self. calculate _signals _for_pairs() The __main __section ties together the components to produce a backtest for the strategy. We tell the simulation where the ticker minutely data is stored. I'm using DTN IQFeed format. I truncated both files so that they began and ended on the same respective minute. For this particular pair of AREX and WLL, the common start date is 8th November 2007 at 10:41:00AM. Finally, we build the backtest object and begin simulating the trading: # intraday _mr. py if__name __== " __main __": csv_dir = '/path/to/your/csv/file' # CHANGE THIS! symbol _list = ['AREX', 'WLL'] initial _capital = 100000. 0 heartbeat = 0. 0 start _date = datetime. datetime(2007, 11, 8, 10, 41, 0) backtest = Backtest( csv_dir, symbol _list, initial _capital, heartbeat,
177 start _date, Historic CSVData Handler HFT, Simulated Execution Handler, Portfolio HFT, Intraday OLSMRStrategy ) backtest. simulate _trading() However, before we can execute this file we need to make some modifications to the data handler and portfolio objects. In particular, it is necessary to create new files hft_data. py andhft_portfolio. py which are copies of data. py andportfolio. py respectively. Inhft_data. py weneedtorename Historic CSVData Handler to Historic CSVData Handler HFT and replace the nameslist in the _open _convert _csv_filesmethod. The old line is: names=[ 'datetime', 'open', 'high', 'low', 'close', 'volume', 'adj _close' ] This must be replaced with: names=[ 'datetime', 'open', 'low', 'high', 'close', 'volume', 'oi' ] This is to ensure that the new format for DTN IQFeed works with the backtester. The other change is to rename Portfolio to Portfolio HFT inhft_portfolio. py. We must then modify a few lines in order to account for the minutely frequency of the DTN data. In particular, within the update _timeindex method, we must change the following code: for sinself. symbol _list: # Approximation to the real value market _value = self. current _positions[s] *\ self. bars. get _latest _bar_value(s, "adj _close") dh[s] = market _value dh['total'] += market _value To: for sinself. symbol _list: # Approximation to the real value market _value = self. current _positions[s] *\ self. bars. get _latest _bar_value(s, "close") dh[s] = market _value dh['total'] += market _value This ensures we obtain the closeprice, rather than the adj_closeprice. The latter is for Yahoo Finance, whereas the former is for DTN IQFeed. We must also make a similar adjustment in update _holdings _from _fill. We need to change the following code: # Update holdings list with new quantities fill _cost = self. bars. get _latest _bar_value( fill. symbol, "adj _close" ) To: # Update holdings list with new quantities fill _cost = self. bars. get _latest _bar_value( fill. symbol, "close" )
178 The final change is occurs in the output _summary _statsmethod at the bottom of the file. We need to modify how the Sharpe Ratio is calculated to take into account minutely trading. The following line: sharpe _ratio = create _sharpe _ratio(returns) Must be changed to: sharpe _ratio = create _sharpe _ratio(returns, periods=252 *6. 5*60) This completes the necessary changes. Upon execution of intraday _mr. pywe get the fol-lowing (truncated) output from the backtest simulation:.... 375072 375073 Creating summary stats... Creating equity curve... AREX WLL cash commission total returns \ datetime 2014-03-11 15:53:00 2098-6802 120604. 3 9721. 4 115900. 3-0. 000052 2014-03-11 15:54:00 2101-6799 120604. 3 9721. 4 115906. 3 0. 000052 2014-03-11 15:55:00 2100-6802 120604. 3 9721. 4 115902. 3-0. 000035 2014-03-11 15:56:00 2097-6810 120604. 3 9721. 4 115891. 3-0. 000095 2014-03-11 15:57:00 2098-6801 120604. 3 9721. 4 115901. 3 0. 000086 2014-03-11 15:58:00 2098-6800 120604. 3 9721. 4 115902. 3 0. 000009 2014-03-11 15:59:00 2099-6800 120604. 3 9721. 4 115903. 3 0. 000009 2014-03-11 16:00:00 2100-6801 120604. 3 9721. 4 115903. 3 0. 000000 2014-03-11 16:01:00 2100-6801 120604. 3 9721. 4 115903. 3 0. 000000 2014-03-11 16:01:00 2100-6801 120604. 3 9721. 4 115903. 3 0. 000000 equity _curve drawdown datetime 2014-03-11 15:53:00 1. 159003 0. 003933 2014-03-11 15:54:00 1. 159063 0. 003873 2014-03-11 15:55:00 1. 159023 0. 003913 2014-03-11 15:56:00 1. 158913 0. 004023 2014-03-11 15:57:00 1. 159013 0. 003923 2014-03-11 15:58:00 1. 159023 0. 003913 2014-03-11 15:59:00 1. 159033 0. 003903 2014-03-11 16:00:00 1. 159033 0. 003903 2014-03-11 16:01:00 1. 159033 0. 003903 2014-03-11 16:01:00 1. 159033 0. 003903 [('Total Return', '15. 90%'), ('Sharpe Ratio', '1. 89'), ('Max Drawdown', '3. 03%'), ('Drawdown Duration', '120718')] Signals: 7594 Orders: 7478 Fills: 7478 You can see that the strategy performs adequately well during this period. It has a total return of just under 16%. The Sharpe ratio is reasonable (when compared to a typical daily strategy), but given the high-frequency nature of the strategy we should be expecting more. The major attraction of this strategy is that the maximum drawdown is low (approximately 3%). This suggests we could apply more leverage to gain more return. The performance of this strategy can be seen in Fig 15. 3: Note that these figures are based on trading a total of 100 shares. You can adjust the leverage by simply adjusting the generate _naive _ordermethod of the Portfolio class. Look for the
179 Figure 15. 3: Equity Curve, Daily Returns and Drawdowns for intraday mean-reversion strategy attribute known as mkt_quantity. It will be set to 100. Changing this to 2000, for instance, provides these results:.... [('Total Return', '392. 85%'), ('Sharpe Ratio', '2. 29'), ('Max Drawdown', '45. 69%'), ('Drawdown Duration', '102150')].... Clearly the Sharpe Ratio and Total Return are much more attractive, but we have to endure a 45% maximum drawdown over this period as well! 15. 4 Plotting Performance The three Figures displayed above are all created using the plot _performance. py script. For completeness I've included the code so that you can use it as a base to create your own perfor-mance charts. It is necessary to run this in the same directory as the output file from the backtest, namely where equity. csv resides. The listing is as follows: #!/usr/bin/python #-*-coding: utf-8-*-# plot _performance. py import os. path
180 import numpy as np import matplotlib. pyplot as plt import pandas as pd if__name __== " __main __": data = pd. io. parsers. read _csv( "equity. csv", header=0, parse _dates=True, index _col=0 ). sort() # Plot three charts: Equity curve, # period returns, drawdowns fig = plt. figure() # Set the outer colour to white fig. patch. set _facecolor('white') # Plot the equity curve ax1 = fig. add _subplot(311, ylabel='Portfolio value, %') data['equity _curve']. plot(ax=ax1, color="blue", lw=2. ) plt. grid(True) # Plot the returns ax2 = fig. add _subplot(312, ylabel='Period returns, %') data['returns']. plot(ax=ax2, color="black", lw=2. ) plt. grid(True) # Plot the returns ax3 = fig. add _subplot(313, ylabel='Drawdowns, %') data['drawdown']. plot(ax=ax3, color="red", lw=2. ) plt. grid(True) # Plot the figure plt. show()
Chapter 16 Strategy Optimisation In prior chapters we have considered how to create both an underlying predictive model (such as with the Suppor Vector Machine and Random Forest Classifier) as well as a trading strategy based upon it. Along the way we have seen that there are many parameters to such models. In the case of an SVM we have the "tuning" parameters γand C. In a Moving Average Crossover trading strategy we have the parameters for the two lookback windows of the moving average filters. In this chapter we are going to describe optimisation methods to improve the performance of our trading strategies by tuning the parameters in a systematic fashion. For this we will use mechanisms from the statistical field of Model Selection, such as cross-validation and grid search. The literature on model selection and parameter optimisation is vast and most of the methods are somewhat beyond the scope of this book. I want to introduce the subject here so that you can explore more sophisticated techniques at your own pace. 16. 1 Parameter Optimisation At this stage nearly all of the trading strategies and underlying statistical models have required one or more parameters in order to be utilised. In momentum strategies using technical indica-tors, such as with moving averages (simple or exponential), there is a need to specify a lookback window. The same is true of many mean-reverting strategies, which require a (rolling) lookback window in order to calculate a regression between two time series. Particular statistical machine learning models such as a logistic regression, SVM or Random Forest also require parameters in order to be calculated. The biggest danger when considering parameter optimisation is that of overfitting a model or trading strategy. This problem occurs when a model is trained on an in sample retained slice of training data and is optimised to perform well (by the appropriate performance measure), but performance degrades substantially when applied to out of sample data. For instance, a trading strategy could perform extremely well in the backtest (the in sample data) but when deployed for live trading can be completely unprofitable. An additional concern of parameter optimisation is that it can become very computationally expensive. With modern computational systems this is less of an issue than it once was, due to parallelisation and fast CPUs. However, multiple parameter optimisation can increase compu-tational complexity by orders of magnitudes. One must be aware of this as part of the research and development process. 16. 1. 1 Which Parameters to Optimise? A statistical-based algorithmic trading model will often have many parameters and different measures of performance. An underlying statistical learning algorithm will have its own set of parameters. Inthecaseofamultiplelinearorlogisticregressionthesewouldbethe βicoefficients. In the case of a random forest one such parameter would be the number of underlying decision trees to use in the ensemble. Once applied to a trading model other parameters might be entry 181
182 and exit thresholds, such as a z-score of a particular time series. The z-score itself might have an implicit rolling lookback window. As can be seen the number of parameters can be quite extensive. In addition to parameters there are numerous means of evaluating the performance of a statistical model and the trading strategy based upon it. We have defined concepts such as the hit rate and the confusion matrix. In addition there are more statistical measures such as the Mean Squared Error (MSE). These are performance measures that would be optimised at the statistical model level, via parameters relevant to their domain. Theactualtradingstrategyisevaluatedondifferentcriteria, suchascompoundannualgrowth rate (CAGR) and maximum drawdown. We would need to vary entry and exit criteria, as well as other thresholds that are not directly related to the statistical model. Hence this motivates the question as to which set of parameters to optimise and when. In the following sections we are going to optimise both the statistical model parameters, at the early research and development stage, as well as the parameters associated with a trading strategy using an underlying optimised statistical model, on each of their respective performance measures. 16. 1. 2 Optimisation is Expensive With multiple real-valued parameters, optimisation can rapidly become extremely expensive, as each new parameter adds an additional spatial dimension. If we consider the example of a grid search(to be discussed in full below), and have a single parameter α, then we might wish to varyαwithin the set{0. 1,0. 2,0. 3,0. 4,0. 5}. This requires 5 simulations. Ifwenowconsideranadditionalparameter β,whichmayvaryintherange {0. 2,0. 4,0. 6,0. 8,1. 0}, then we will have to consider 52= 25simulations. Another parameter, γ, with 5 variations brings this to 53= 125simulations. If each paramater had 10 separate values to be tested, this would be equal to 103= 1000simulations. As can be seen the parameter search space can rapidly make such simulations extremely expensive. It is clear that a trade-off exists between conducting an exhaustive parameter search and maintaining a reasonable total simulation time. While parallelism, including many-core CPUs and graphics processing units (GPUs), have mitigated the issue somewhat, we still need to be careful when introducing parameters. This notion of reducing parameters is also an issue of model effectiveness, as we shall see below. 16. 1. 3 Overfitting Overfitting is the process of optimising a parameter, or set of parameters, against a particular data set such that an appropriate performance measure (or error measure) is found to be max-imised (or minimised), but when applied to an unseen data set, such a performance measure degrades substantially. The concept is closely related to the idea of the bias-variance dilemma. The bias-variance dilemma concerns the situation where a statistical model has a trade-off between being a low-bias model or a low-variance model, or a compromise between the two. Bias refers to the difference between the model's estimation of a parameter and the true "population" value of the parameter, or erroneous assumptions in the statistical model. Variance refers to the error from the sensitivity of the model to small fluctuations in the training set (in sample data). In all statistical models one is simultaneously trying to minimise both the bias error and the variance error in order to improve model accuracy. Such a situation can lead to overfitting in models, as the training error can be substantially reduced by introducing models with more flexibility (variation). However, such models can perform extremely poorly on new (out of sample) data since they were essentially "fit" to the in sample data. A common example of a high-bias, low-variance model is that of linear regression applied to a non-linear data set. Additions of new points do not affect the regression slope dramatically (assuming they are not too far from the remaining data), but since the problem is inherently non-linear, there is a systematic bias in the results by using a linear model. A common example of a low-bias, high-variance model is that of a polynomial spline fit applied to a non-linear data set. The parameter of the model (the degree of the polynomial)
183 could be adjusted to fit such a model very precisely (i. e. low-bias on the training data), but additions of new points would almost certainly lead to the model having to modify its degree of polynomial to fit the new data. This would make it a very high-variance model on the in sample data. Such a model would likely have very poor predictability or inferential capability on out of sample data. Overfitting can also manifest itself on the trading strategy and not just the statistical model. For instance, we could optimise the Sharpe ratio by varying entry and exit threshold parameters. While this may improve profitability in the backtest (or minimise risk substantially), it would likely not be behaviour that is replicated when the strategy was deployed live, as we might have been fitting such optimisations to noise in the historical data. We will discuss techniques below to minimise overfitting, as much as possible. However one has to be aware that it is an ever-present danger in both algorithmic trading and statistical analysis in general. 16. 2 Model Selection In this section we are going to consider how to optimise the statistical model that will underly a trading strategy. In the field of statistics and machine learning this is known as Model Selection. While I won't present an exhaustive discussion on the various model selection techniques, I will describe some of the basic mechanisms such as Cross Validation and Grid Search that work well for trading strategies. 16. 2. 1 Cross Validation Cross Validation is a technique used to assess how a statistical model will generalise to new data that it has not been exposed to before. Such a technique is usually used on predictive models, such as the aforementioned supervised classifiers used to predict the sign of the following daily returns of an asset price series. Fundamentally, the goal of cross validation is to minimise error on out of sample data without leading to an overfit model. In this section we will describe the training/test split andk-fold cross validation, as well as use techniques within Scikit-Learn to automatically carry out these procedures on statistical models we have already developed. Train/Test Split The simplest example of cross validation is known as a training/test split, or a2-fold cross validation. Once a prior historical data set is assembled (such as a daily time series of asset prices), it is split into two components. The ratio of the split is usually varied between 0. 5 and 0. 8. In the latter case this means 80% of the data is used for training and 20% is used for testing. All of the statistics of interest, such as the hit rate, confusion matrix or mean-squared error are calculated on the test set, which has not been used within the training process. Tocarryoutthisprocessin Pythonwith Scikit-Learnwecanusethe sklearn cross _validation train _test _splitmethod. We will continue with our model as discussed in the chapter on Forecasting. In particular, we are going to modify forecast. py and create a new file called train _test _split. py. We will need to add the new import to the list of imports: #!/usr/bin/python #-*-coding: utf-8-*-# train _test _split. py from __future __import print _function import datetime import sklearn
184 from sklearn. cross _validation import train _test _split from sklearn. ensemble import Random Forest Classifier from sklearn. linear _model import Logistic Regression from sklearn. lda import LDA from sklearn. metrics import confusion _matrix from sklearn. qda import QDA from sklearn. svm import Linear SVC, SVC from create _lagged _series import create _lagged _series Inforecast. py we originally split the data based on a particular date within the time series: # forecast. py.. # The test data is split into two parts: Before and after 1st Jan 2005. start _test = datetime. datetime(2005,1,1) # Create training and test sets X_train = X[X. index < start _test] X_test = X[X. index >= start _test] y_train = y[y. index < start _test] y_test = y[y. index >= start _test].. Thiscanbereplacedwiththemethod train _test _splitfrom Scikit-Learninthe train _test _split. py file. For completeness, the full __main __method is provided below: # train _test _split. py if__name __== " __main __": # Create a lagged series of the S&P500 US stock market index snpret = create _lagged _series( "^GSPC", datetime. datetime(2001,1,10), datetime. datetime(2005,12,31), lags=5 ) # Use the prior two days of returns as predictor # values, with direction as the response X = snpret[["Lag1","Lag2"]] y = snpret["Direction"] # Train/test split X_train, X _test, y _train, y _test = train _test _split( X, y, test _size=0. 8, random _state=42 ) # Create the (parametrised) models print ("Hit Rates/Confusion Matrices:\n") models = [("LR", Logistic Regression()), ("LDA", LDA()), ("QDA", QDA()), ("LSVC", Linear SVC()), ("RSVM", SVC( C=1000000. 0, cache _size=200, class _weight=None, coef0=0. 0, degree=3, gamma=0. 0001, kernel='rbf', max_iter=-1, probability=False, random _state=None,
185 shrinking=True, tol=0. 001, verbose=False) ), ("RF", Random Forest Classifier( n_estimators=1000, criterion='gini', max_depth=None, min _samples _split=2, min_samples _leaf=1, max _features='auto', bootstrap=True, oob _score=False, n _jobs=1, random _state=None, verbose=0) )] # Iterate through the models for min models : # Train each of the models on the training set m[1]. fit(X _train, y _train) # Make an array of predictions on the test set pred = m[1]. predict(X _test) # Output the hit-rate and the confusion matrix for each model print ("%s:\n%0. 3f" % (m[0], m[1]. score(X _test, y _test))) print ("%s\n" % confusion _matrix(pred, y _test)) Notice that we have picked the ratio of the training set to be 80% of the data, leaving the testing data with only 20%. In addition we have specified a random _stateto randomise the sampling within the selection of data. This means that the data is not sequentially divided chronologically, but rather is sampled randomly. The results of the cross-validation on the model are as follows (yous will likely appear slightly different due to the nature of the fitting procedure): Hit Rates/Confusion Matrices: LR: 0. 511 [[ 70 70] [419 441]] LDA: 0. 513 [[ 69 67] [420 444]] QDA: 0. 503 [[ 83 91] [406 420]] LSVC: 0. 513 [[ 69 67] [420 444]] RSVM: 0. 506 [[ 8 13] [481 498]]
186 RF: 0. 490 [[200 221] [289 290]] It can be seen that the hit rates are substantially lower than those found in the aforemen-tioned forecasting chapter. Consequently we can likely conclude that the particular choice of training/test split lead to an over-optimistic view of the predictive capability of the classifier. The next step is to increase the number of times a cross-validation is performed in order to minimise any potential overfitting. For this we will use k-fold cross validation. K-Fold Cross Validation Rather than partitioning the set into a single training and test set, we can use k-fold cross validation to randomly partition the the set into kequally sized subsamples. For each iteration (of which there are k), one of the ksubsamples is retained as a test set, while the remaining k-1subsamples together form a training set. A statistical model is then trained on each of the kfolds and its performance evaluated on its specific k-th test set. The purpose of this is to combine the results of each model into an emsemble by means of averaging the results of the prediction (or otherwise) to produce a single prediction. The main benefit of using k-fold cross validation is that the every predictor within the original data set is used both for training and testing only once. This motivates a question as to how to choose k, which is now another parameter! Generally, k= 10is used but one can also perform another analysis to choose an optimal value of k. We will now make use of the cross _validation module of Scikit-Learn to obtain the KFold k-fold cross validation object. We create a new file called k_fold _cross _val. py, which is a copy of train _test _split. py and modify the imports by adding the following line: #!/usr/bin/python #-*-coding: utf-8-*-# k_fold _cross _val. py from __future __import print _function import datetime import pandas as pd import sklearn from sklearn import cross _validation from sklearn. metrics import confusion _matrix from sklearn. svm import SVC from create _lagged _series import create _lagged _series We then need to make changes the __main __function by removing the train _test _split method and replacing it with an instance of KFold. It takes five parameters. The first isthe length of the dataset, which in this case 1250 days. The second value is K representing the number of folds, which in this case is 10. The third value is indices, which I have set to False. This means that the actual index values are used for the arrays returned by the iterator. The fourth and fifth are used to randomise the order of the samples. As before in forecast. py and train _test _split. py we obtain the lagged series of the S&P500. We then create a set of vectors of predictors ( X) and responses ( y). We then utilise the KFoldobject and iterate over it. During each iteration we create the training and testing sets for each of the Xandyvectors. These are then fed into a radial support vector machine with identical parameters to the aforementioned files and the model is fit. Finally the hit rate and confusion matrix for each instance of the SVM is output.
187 # k_fold _cross _val. py if__name __== " __main __": # Create a lagged series of the S&P500 US stock market index snpret = create _lagged _series( "^GSPC", datetime. datetime(2001,1,10), datetime. datetime(2005,12,31), lags=5 ) # Use the prior two days of returns as predictor # values, with direction as the response X = snpret[["Lag1","Lag2"]] y = snpret["Direction"] # Create a k-fold cross validation object kf = cross _validation. KFold( len(snpret), n _folds=10, indices=False, shuffle=True, random _state=42 ) # Use the kf object to create index arrays that # state which elements have been retained for training # and which elements have beenr retained for testing # for each k-element iteration for train _index, test _index inkf: X_train = X. ix[X. index[train _index]] X_test = X. ix[X. index[test _index]] y_train = y. ix[y. index[train _index]] y_test = y. ix[y. index[test _index]] # In this instance only use the # Radial Support Vector Machine (SVM) print ("Hit Rate/Confusion Matrix:") model = SVC( C=1000000. 0, cache _size=200, class _weight=None, coef0=0. 0, degree=3, gamma=0. 0001, kernel='rbf', max_iter=-1, probability=False, random _state=None, shrinking=True, tol=0. 001, verbose=False ) # Train the model on the retained training data model. fit(X _train, y _train) # Make an array of predictions on the test set pred = model. predict(X _test) # Output the hit-rate and the confusion matrix for each model print ("%0. 3f" % model. score(X _test, y _test)) print ("%s\n" % confusion _matrix(pred, y _test)) The output of the code is as follows: Hit Rate/Confusion Matrix: 0. 528 [[11 10] [49 55]]
188 Hit Rate/Confusion Matrix: 0. 400 [[ 2 5] [70 48]] Hit Rate/Confusion Matrix: 0. 528 [[ 8 8] [51 58]] Hit Rate/Confusion Matrix: 0. 536 [[ 6 3] [55 61]] Hit Rate/Confusion Matrix: 0. 512 [[ 7 5] [56 57]] Hit Rate/Confusion Matrix: 0. 480 [[11 11] [54 49]] Hit Rate/Confusion Matrix: 0. 608 [[12 13] [36 64]] Hit Rate/Confusion Matrix: 0. 440 [[ 8 17] [53 47]] Hit Rate/Confusion Matrix: 0. 560 [[10 9] [46 60]] Hit Rate/Confusion Matrix: 0. 528 [[ 9 11] [48 57]] It is the clear that the hit rate and confusion matrices vary dramatically across the various folds. This is indicative that the model is prone to overfitting, on this particular dataset. A remedy for this is to use significantly more data, either at a higher frequency or over a longer duration. In order to utilise this model in a trading strrategy it would be necessary to combine each of these individually trained classifiers (i. e. each of the Kobjects) into an ensemble average and then use that combined model for classification within the strategy. Note that technically it is not appropriate to use simple cross-validation techniques on tem-porally ordered data (i. e. time-series). There are more sophisticated mechanisms for coping with autocorrelation in this fashion, but I wanted to highlight the approach so we have used time series data for simplicity.
189 16. 2. 2 Grid Search We have so far seen that k-fold cross validation helps us to avoid overfitting in the data by performing validation on every element of the sample. We now turn our attention to optimising thehyper-parameters of a particular statistical model. Such parameters are those not directly learnt by the model estimation procedure. For instance, Candγfor a support vector machine. In essence they are the parameters that we need to specify when calling the initialisation of each statistical model. For this procedure we will use a process known as a grid search. The basic idea is to take a range of parameters and assess the performance of the statistical model on each parameter element within the range. To achieve this in Scikit-Learn we can create a Parameter Grid. Such an object will produce a list of Python dictionaries that each contain a parameter combination to be fed into a statistical model. An example code snippet that produces a parameter grid, for parameters related to a support vector machine, is given below: >>> from sklearn. grid _search import Parameter Grid >>> param _grid = {'C': [1, 10, 100, 1000], 'gamma': [0. 001, 0. 0001]} >>> list(Parameter Grid(param _grid)) [{'C': 1, 'gamma': 0. 001}, {'C': 1, 'gamma': 0. 0001}, {'C': 10, 'gamma': 0. 001}, {'C': 10, 'gamma': 0. 0001}, {'C': 100, 'gamma': 0. 001}, {'C': 100, 'gamma': 0. 0001}, {'C': 1000, 'gamma': 0. 001}, {'C': 1000, 'gamma': 0. 0001}] Now that we have a suitable means of generating a Parameter Grid we need to feed this into a statistical model iteratively to search for an optimal performance score. In this case we are going to seek to maximise the hit rate of the classifier. The Grid Search CV mechanism from Scikit-Learn allows us to perform the actual grid search. In fact, it allows us to perform not only a standard grid search but also a cross validation scheme at the same time. Wearenowgoingtocreateanewfile, grid _search. py,thatonceagainuses create _lagged _series. py and a support vector machine to perform a cross-validated hyperparameter grid search. To this end we must import the correct libraries: #!/usr/bin/python #-*-coding: utf-8-*-# grid _search. py from __future __import print _function import datetime import sklearn from sklearn import cross _validation from sklearn. cross _validation import train _test _split from sklearn. grid _search import Grid Search CV from sklearn. metrics import classification _report from sklearn. svm import SVC from create _lagged _series import create _lagged _series As before with k_fold _cross _val. pywe create a lagged series and then use the previous two days of returns as predictors. We initially create a training/test split such that 50% of the
190 data can be used for training and cross validation while the remaining data can be "held out" for evaluation. Subsequently we create the tuned _parameters list, which contains a single dictionary de-noting the parameters we wish to test over. This will create a cartesian product of all parameter lists, i. e. a list of pairs of every possible parameter combination. Once the parameter list is created we pass it to the Grid Search CV class, along with the type of classifier that we're interested in (namely a radial support vector machine), with a k-fold cross-validation k-value of 10. Finally, we train the model and output the best estimator and its associated hit rate scores. In this way we have not only optimised the model parameters via cross validation but we have also optimised the hyperparameters of the model via a parametrised grid search, all in one class! Such succinctness of the code allows significant experimentation without being bogged down by excessive "data wrangling". if__name __== " __main __": # Create a lagged series of the S&P500 US stock market index snpret = create _lagged _series( "^GSPC", datetime. datetime(2001,1,10), datetime. datetime(2005,12,31), lags=5 ) # Use the prior two days of returns as predictor # values, with direction as the response X = snpret[["Lag1","Lag2"]] y = snpret["Direction"] # Train/test split X_train, X _test, y _train, y _test = train _test _split( X, y, test _size=0. 5, random _state=42 ) # Set the parameters by cross-validation tuned _parameters = [ {'kernel': ['rbf'], 'gamma': [1e-3, 1e-4], 'C': [1, 10, 100, 1000]} ] # Perform the grid search on the tuned parameters model = Grid Search CV(SVC(C=1), tuned _parameters, cv=10) model. fit(X _train, y _train) print ("Optimised parameters found on training set:") print (model. best _estimator _, "\n") print ("Grid scores calculated on training set:") for params, mean _score, scores inmodel. grid _scores _: print ("%0. 3f for %r" % (mean _score, params)) The output of the grid search cross validation procedure is as follows: Optimised parameters found on training set: SVC(C=1, cache _size=200, class _weight=None, coef0=0. 0, degree=3, gamma=0. 001, kernel='rbf', max _iter=-1, probability=False, random _state=None, shrinking=True, tol=0. 001, verbose=False) Grid scores calculated on training set: 0. 541 for {'kernel': 'rbf', 'C': 1, 'gamma': 0. 001} 0. 541 for {'kernel': 'rbf', 'C': 1, 'gamma': 0. 0001} 0. 541 for {'kernel': 'rbf', 'C': 10, 'gamma': 0. 001}
191 0. 541 for {'kernel': 'rbf', 'C': 10, 'gamma': 0. 0001} 0. 541 for {'kernel': 'rbf', 'C': 100, 'gamma': 0. 001} 0. 541 for {'kernel': 'rbf', 'C': 100, 'gamma': 0. 0001} 0. 538 for {'kernel': 'rbf', 'C': 1000, 'gamma': 0. 001} 0. 541 for {'kernel': 'rbf', 'C': 1000, 'gamma': 0. 0001} As we can see γ= 0. 001and C= 1provides the best hit rate, on the validation set, for this particular radial kernel support vector machine. This model could now form the basis of a forecasting-based trading strategy, as we have previously demonstrated in the prior chapter. 16. 3 Optimising Strategies Up until this point we have concentrated on model selection and optimising the underlying statistical model that (might) form the basis of a trading strategy. However, a predictive model and a functioning, profitable algorithmic strategy are two different entities. We now turn our attention to optimising parameters that have a direct effect on profitability and risk metrics. To achieve this we are going to make use of the event-driven backtesting software that was described in a previous chapter. We will consider a particular strategy that has three parameters associated with it and search through the space formed by the cartesian product of parameters, using a grid search mechanism. We will then attempt to maximise particular metrics such as the Sharpe Ratio or minimise others such as the maximum drawdown. 16. 3. 1 Intraday Mean Reverting Pairs Thestrategyofinteresttousinthischapteristhe"Intraday Mean Reverting Equity Pairs Trade" using the energy equities AREX and WLL. It contains three parameters that we are capable of optimising: The linear regression lookback period, the residuals z-score entry threshold and the residuals z-score exit threshold. We will consider a range of values for each parameter and then calculate a backtest for the strategy across each of these ranges, outputting the total return, Sharpe ratio and drawdown characteristics of each simulation, to a CSV file for each parameter set. This will allow us to ascertain an optimised Sharpe or minimised max drawdown for our trading strategy. 16. 3. 2 Parameter Adjustment Since the event-driven backtesting software is quite CPU-intensive, we will restrict the parameter range to three values per parameter. This will give us a total of 33= 27separate simulations to carry out. The parameter ranges are listed below: OLS Lookback Window-wl∈{50,100,200} Z-Score Entry Threshold-zh∈{2. 0,3. 0,4. 0} Z-Score Exit Threshold-zl∈{0. 5,1. 0,1. 5} To carry out the set of simulations a cartesian product of all three ranges will be calculated and then the simulation will be carried out for each combination of parameters. The first task is to modify the intraday _mr. pyfile to include the product method from the itertools library: # intraday _mr. py.. from itertools import product.. We can then modify the __main __method to include the generation of a parameter list for all three of the parameters discussed above.