Full text
Bachelor’s Thesis Bachelor Degree in Informatics Engineering Bachelor Degree in Mathematics High Frequency Trading via Convolutional Neural Networks Author Miguel Cidr´ as Senra Supervisor: Daniel P. Palomar Convocatory: May 2020
Abstract The objective of this project is to develop and train a CNN capable to trade in a HFT. The methodology followed consisted in design models to forecast particular features of the LOB. The start point was to test traditional methods in finance with the purpose of predicting futures prices. These methods were rejected through experimentation. Subsequently, a study on ANN architectures was conducted to build models capable of predicting the direction of the mid price. Furthermore, experiments were carried out on different models, testing different representations of the LOB. The results showed how, with proper input and architecture design, a CNN slightly outperforms a MLP in predicting price direction. Finally, new labels were introduced to detect when the trade has benefits. Thereupon, experiments were conducted to predict these labels. In that case, both models had positive results but CNN did not outperform MLP. Keywords: Deep Learning, Convolutional Neural Networks, Multilayer Perceptron, Artifical Neural Networks, Limit Order Book, High Frequency Trading MSC2020: 91B84
Contents 1 Introduction 7 2 Theoretical background 7 2.1 LimitOrderBookdefinition.................................. 7 2.2 Simplemodels ......................................... 9 2.3 NeuralNetworks ........................................ 10 3 Data processing 11 3.1 Datadescription ........................................ 11 3.2 Datacleaning.......................................... 11 3.3 Datanormalization....................................... 12 3.4 ImageRepresentation ..................................... 13 4 Technical Details 15 4.1 Implementation......................................... 15 4.2 Initialization .......................................... 15 4.3 Architecture........................................... 15 4.4 Activationfunctions ...................................... 16 4.5 Lossfunctions.......................................... 17 4.6 Learningalgorithm....................................... 18 4.7 Labels.............................................. 18 4.8 Performancemetrics ...................................... 19 5 Experimental results 21 5.1 Performance of non-neural network models . . . . . . . . . . . . . . . . . . . . . . . . . 21 5.2 Performance of MLP and different CNNs with a Mid price based label . . . . . . . . . . 22 5.3 Proposed labels performance of MLP and different CNN . . . . . . . . . . . . . . . . . . 29 6 Conclusion 33 7 Annex: Simple models 34 7.1 ARIMA ............................................. 34 7.2 Naive .............................................. 34 7.3 Exponentialsmoothing..................................... 34 8 Annex: Custom loss function 35
8.1 Confunsionmatrix ....................................... 35 8.2 Logarithm............................................ 36
List of Figures 3 Graphical example of a snapshot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9 4 Midpricethroughoutoneday................................. 12 5 Example of shortcut connection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16 6 RMSE comparison of simple models . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21 7 Min F1-score comparison of simple models . . . . . . . . . . . . . . . . . . . . . . . . . . 22 8 Min F1-score comparison between ANN models with direct encoding . . . . . . . . . . . 24 9 Accuracy comparison between ANN models with direct encoding . . . . . . . . . . . . . 24 10 Min F1-score comparison between MLP models with direct encoding . . . . . . . . . . . 25 11 Accuracy comparison between MLP models with direct encoding . . . . . . . . . . . . . 25 12 Accuracy comparison between models with GAF encoding . . . . . . . . . . . . . . . . . 27 13 Accuracy comparison between models with two-channels encoding . . . . . . . . . . . . 28 14 Accuracy comparison between MLP and CNNs with direct encoding . . . . . . . . . . . 29 15 Min F1-score comparison between MLP and CNNs with direct encoding . . . . . . . . . 29 16 Trading score comparison between two labels . . . . . . . . . . . . . . . . . . . . . . . . 30 17 Trading score comparison between the best label . . . . . . . . . . . . . . . . . . . . . . 31 18 Trading score comparison between focal loss and cross-entropy . . . . . . . . . . . . . . 31 19 Trading score comparison between focal loss and cross-entropy . . . . . . . . . . . . . . 32
Acronyms ANN Artificial Neural Network. 10 CNN Convolutional Neural Network. 10 FNN Feedforward Neural Network. 10 GAF Gramian Angular Field. 14 HFT High Frequency Trading. 7 LOB Limit Order Book. 7 MLP Multilayer Perceptron. 10 ReLU Rectified linear unit. 17 RNN Recursive Neural Networks. 7
1 Introduction High Frequency Trading (HFT) is a type of financial trading that has very short-term investment horizons, of the order of minutes or even less, as opposed to lower frequency trading like daily trading or monthly trading. Given the quick decision-making and the advancement in technology, it is executed in an automated way with algorithms, known as algorithmic trading. These decisions have to be made based on the past history of limit order book. Practitioners usually use handcraft features based on their experience and then use some simple linear regression for the forecast. Our purpose explore the potential of deep neural networks networks to bypass the need for handcrafting features. Since the data follows a time sequence, the Recursive Neural Networks (RNN) are generally considered the best neural network architectures. However recent studies show that convolutional networks can perform comparably or even better [BKK18], so we are going to explore this possibility. The project is divided in four main sections. The first section explains the core concepts of the project, the second section describes the transformations applied to the initial data, the third section describes how our neural networks are built, and the fourth section presents the results of the experiments. In the annexes, we extend the description of traditional models and discard a possible custom loss function. 2 Theoretical background This section explains the central theoretical concepts of the project. For this reason, the section defines the Limit Order Books and introduces the models used in the project. 2.1 Limit Order Book definition Limit Order Book (LOB) is a mechanism that facilitates trade, which today has become essential in the operation of many markets due to the fast pace and competitiveness of the financial world. In this section, we provide a LOB description that is common to most markets. The LOB essential element is an limit order, which is an order to buy or sell a given amount of asset at a specified limit price or better. An limit order xcan be expressed as x= (px, ωx, tx), which was submitted at time txwith price pxand size ωx. The sign of ωxindicates if it is a arrangement to sell or buy. In this way, we have two cases: •If ωx>0 is a commitment to sell up to |ωx|units of the traded asset at a price no less than px. •If ωx<0 is a commitment to buy up to |ωx|units of the traded asset at a price no greater than px. For a given LOB, the units of limit order price and size have some conditions, as there exists two resolution parameters: •The tick size π: the smallest difference between two prices. All orders must arrive with a price px∈ {kπ|k= 1,2, . . . }. •The lot size σ: the smallest amount that can be traded. All orders must arrive with a size ωx∈ {±kσ|k= 1,2, . . . } 7
The structure of a LOB can be described as a set of two of priority queues, one which consists of active sell limit orders and one which consists of active buy limit orders. The priority of these queues is usually a price-time, so they are ordered according to prices and if the prices are the same, the submission time is compared. The set of all active limit orders in a market at time tcan be named as L(t). This set can be partitioned into two sets, each one corresponds to one of the queues: •The set of active sell limit order. A(t) := {x|x∈L(t), ωx>0} •The set of active buy limit order. B(t) := {x|x∈L(t), ωx<0} When a limit order xis submitted, a matching process checks if it is possible to match xto some other submitted order of the opposite type (sell against buy and, respectively, buy against sell). If so, the matching happens automatically and the system will attempt to match the incoming order with the opposite order of highest priority. If the previous order is fully satisfied, it will be removed, and if the new order still has remaining volume, the system will try to match again until it is fully fulfilled or no further matches can be made. At this time, if there is still volume in the new order, it will be placed in the order book with the current volume. In general, the trades made immediately at the best price currently available in the market are called market orders. There are some important terms that are used in the context of LOB: •The best ask price at time t: the lowest price among active limit sell order at time t. It is the lowest price at it is possible to buy forthwith at time t. a(t) := min x∈A(t)px •The best bid price at time t: the highest price among active limit buy order at time t. Respectively, it is the highest price at it is possible to sell forthwith at time t. b(t) := max x∈B(t)px •The mid price at time t: the mean between the best ask price and the best bid price at time t pm(t) := a(t) + b(t) 2 In a LOB, it is useful to consider the group of several limit order by their price, to define pairs of price and volume for each price, where the volume is the sum of all size of the limit order with these particular price. After that, for each type of order, the pairs can be arrange from the lowest price to the highest and therefore, defining in this ways price levels and volume levels. These definitions are important as our forecast will rely on them, as our data does not include information about individual orders. The ask price levels definition is: p(i) a=(a(t), if i= 1 min{px|x∈ A(t), px> p(i−1) a}, otherwise 8
Then, the ask volume levels definition is: v(i) a=X ω∈V(i) a |ω|where V(i) a={ωx|x∈ A(t), px=p(i) a} Analogously, the bid price levels definition is: p(i) b=(b(t), if i= 1 max{px|x∈ A(t), px< p(i−1) b}, otherwise Then, the bid volume levels definition is: v(i) b=X ω∈V(i) b |ω|where V(i) b={ωx|x∈ B(t), px=p(i) b}} Focusing attention on a time t, we can draw a plot in which we easily observe the ten price levels and their respective volumes. Figure 3: Graphical example of a snapshot 2.2 Simple models We explored two traditional time series analysis methods as baselines for the project, because despite being simple models, they are still used in the finance field. 2.2.1 Exponential Smoothing Methods Exponential smoothing are a class of forecasting methods such that the forecast is a weighted combination of past observations and the weights decay exponentially as the observations get older. This family of methods proves itself as useful, in particular in the finance field. In finance, it is often helpful to split a time series into several components such as the trend component T(the long-term direction of the series), the seasonal component S(a pattern with a known periodicity) and the error or noisy component E(the unpredictable part of the series). These three components can be integrated in different ways, i.e.: 9
depends on this choice. On other hand, the output layer structure depends on the labels codification. For binary classification, the output layer consists of one node and its output value is either 0 or 1. For multiclass classification of Cclasses, the last layer consists of Cnodes with binary output. In our case, C= 3. Therefore, the main difference between our MLP and CNN models come from the hidden layers. MLP may have several consecutive full-connected hidden layers, our MLPs only have one hidden layer. To build the hidden layers of the CNN, we concatenate convolutional layers and we intercalate some pooling layers. After that, we full-connect the last one with one layer, which is also full-connected with the output layer. In our CNNs, the pooling layers cluster the subset of neurons into the maximum. Because of that, we call them max pooling layers. The application of a convolutional layer reduce the dimension of the input. For this reason, we may add some zeros to the original input with the purpose of conserving the spatial resolution after convolution layer. This technique is called padding. The CNNs of section 5.2.4 are inspired by the philosophy of VGG nets [SZ14a]. Thus, the rules that follow are: •The convolutional layers have filters 3 ×3 and use spatial padding. •Consecutive convolutional layers have the same number of filters, i.e. we should apply padding. •After a max pooling of 2 ×2, the number of filters is duplicated In [SZ14b], they add shortcut connections to the ANN. The motivation came from the observation that the error of a model sometimes is increased by adding more layers. However, after stacking more layers to a ANN, the performance should at least be maintained, as the ANN with more layers can learn exactly the same as the original. Therefore, shortcut connections are created to allow the ANN to learn deviations from the identity layer. Following the work in [SZ14b], we also add shortcut connections to skip convolutional layers. Figure 5: Example of shortcut connection 4.4 Activation functions The activation function determines the relationship between inputs and outputs of a node in a network. The main reason behind using them is to introduce non-linearity in the model. Nowadays, a wide range 16
of functions can be used. Nevertheless, we have only employ the following three: •Rectified linear unit (ReLU) as the activation function for the intermediate layers. σ(z) = max{0, x} •Sigmoid as the activation function for the output layer in binary classification. It produces similar results to step function in that the output is between 0 and 1, so the output can be viewed as the probability of belonging to a class. σ(z) = 1 1 + e−z •Softmax as the activation function for the output layer in multiclass classification. It guarantees that the output will be in a range of 0 and 1, and the sum of them is 1, thus the output can be interpreted as the probability for each class. σ(z)i=ezi Pk j=1 ezk 4.5 Loss functions Loss function is the function that the neural network is trying to minimize and it measures how good a prediction model does in terms of being able to predict the expected outcome. During the training, the loss is summed over all samples in each batch. The cross-entropy measures how different two distributions are. Its formulation depends on the number of classes in the classification problem and can be deduced from the minimization of the log likelihood [Bis07]. We denote the ground truth vector by y, while ˆyis the predicted label distribution. •Binary cross-entropy: when we consider the problem involving two classes in which we consider a network with a single output. E(y, ˆy) = −(ylog ˆy+ (1 −y) log(1 −ˆy)) •Categorical cross-entropy: when we consider the problem involving more than two mutually exclusive classes in which we consider a network with an output for each case and the target data has a one-hot encoding scheme. E(y, ˆy) = − C X j=1 yilog ˆyi We also explore the focal loss, introduced in [Lin+17]. E(y, ˆy;α, γ) = −(yα(1 −ˆy)γlog ˆy+ (1 −y)(1 −α)ˆyγlog(1 −ˆy)) where αis a weighted factor and γis a parameter such that α∈(0,1) and γ≥0. The idea behind this function is to add a factor to the cross-entropy criterion in order to reduce the loss of correct predictions, putting more emphasis on incorrect predictions. This factor is regulated by gamma. In fact, when γ= 0, we obtain a weighted binary cross-entropy: E(y, ˆy;α) = −(αy log ˆy+ (1 −α)(1 −y) log(1 −ˆy)) 17
4.6 Learning algorithm The weight of the models are updated by an algorithm based on mini-batch gradient descent. This means that splits the training dataset into small batches that are used to compute the updated weights. In particular, we use ADAM because it is a very popular algorithm and it has a good performance in neural networks with similar architecture [Bas+18]. The algorithm core ideas are to incorporate the previous updates in the current change and to adapt the learning rate depending of the evolution of the error. 4.7 Labels A set of discrete options must be constructed from our data to be used as a target for our classification models. Therefore, we define labels. The most common ones are based on the mid price change, as in [Nta+17]. Although the mid price is not a real value and cannot guarantee the immediate execution of any order if placed at this exact price, forecasting its upwards or downwards movement provides a good estimate of the price of future orders. Simply using the inequations pm(t+k)> pm(t) or pm(t+k)< pm(t) to determine the direction of the mid price would introduce a large amount of noise, since even the smallest change would be recorded as a movement. To avoid this issue, an average filter was applied in a future window h: ma(t) = 1 h h X i=1 pm(t+i) The thresholds α1, α−1are defined in order to determine how significant is the change of ma(t) value and if it must be label the movement as upward or downward. Cases which thresholds are not satisfy are considered as having no price movement. The labels for describing the movement are denoted by l(t)∈ {−1,0,1}, where tdenotes the time step and {−1,0,1}denote downwards movement, no movement and upwards movement. The resulting label is: lm(t) = 1,if ma(t) pm(t)>1 + α1 −1,if ma(t) pm(t)<1 + α−1 0,otherwise Some works, as in [ZZR19], also apply the average filter to the past mid prices: mb(t) = 1 h+ 1 h X i=0 pm(t−i) However, as in [Tra+20], we found that replacing pmvalue with mbis an oversimplification of the labels, making the problem significantly easier due to the slower adaptation to sudden price changes. We also introduced two new labels, this time focused on detecting only upward price movements. The available information does not allow us to infer the real price, however, if the future best bid price is higher than the current best ask price, the price has necessarily had to increase. Detecting this price change also allows a simple strategy to evaluate the forecast in which a buy order is made at time t and then a sell order is made between time t+ 1 and t+h. Following the previous notation, the new labels for describing the movement are denoted by {0,1}, which denote no movement and upwards movement. 18
The condition to take into account is given a time t, to detect if there is some k∈ {1, . . . , h}such that p(1) a(t)< p(1) b(t+k). The first label is based on counting, for a certain horizon h, how many kaccomplish the condition. We define a function that expresses the frequency with which the condition is fulfilled in a horizon h: u1(t) = 1 h#{k|k∈ {1. . . h}and p(1) b(t+k)> p(1) a(t)} Using this function, we can define the label: l1(t) = (1, u1(t)> τ1 0,otherwise Some threshold τ1is defined in order to differentiate more the two classes. The second label takes to account the maximum difference between the current best ask price and the future best bid prices: u2(t) = max 1≤k≤h{max{p(1) b(t+k)−p(1) a(t),0}} =|max 1≤k≤h{p(1) b(t+k)} − p(1) a(t)|+ Analogously, some threshold τ2is defined in order to differentiate more the two classes. The resulting label is: l2(t) = (1, u2(t)> τ2 0,otherwise The three labels are not only different, but also the thresholds are: •lmis very sensitive to small changes of α1or α−1. •In the l1case, two thresholds generate different labels only if their difference is at least 1 h. •In the l2case, the difference must be at least the tick size. 4.7.1 Codification The binary labels are encoded with a binary variable. This is not possible with multiclass labels, so we use One Hot Encoding and it is defined a new binary variable is added for each unique label value. In the case of first label, we need three binary varibles to encode it. 4.8 Performance metrics We define the functions used to evaluate the superiority of the different models. The function that evaluates the predictions of traditional models is: •Root Mean Square Error: which measures the quadratic means of the difference between two variables. RMSE =v u u t1 N N X j=1 (yj−ˆyj)2 where Nis the number of observations. 19
To evaluate the quality of the mid price label prediction, we have used at least one of the following functions: •Accuracy: which measures the average number of correct predictions. Accuracy =1 n C X k=1 X x|g(x)=k I(g(x) = ˆg(x)) where Iis the indicator function and Cis the number of classes. •Min F1-score: is minimum of all F1-score of all classes. F1-score is defined as the harmonic mean of the precision and the recall. F1i= 2 Pi·Ri Pi+Ri where Pi=TPi TPi+F Pi Ri=TPi TPi+F Ni where TPi,F Piand FNirespectively represent true positives, false positives, and false negatives of the i-th class. In addition, we defined another approach to evaluating labels from a financial point of view which is to evaluate the performance of labels with a trading strategy. Given a LOB of a day of Nsnapshots, ˆythe predictions for the day, a horizon hand extra price ρ(ρ must be a positive multiple of the tick size), we can define a simple algorithm that compute the profits of the approximation of a simple trading strategy. It is an approximation because we assume that the first order is executed instantly, we do not take into account the cost of trading and we are not always sure that the second order we place has priority. The description of the algorithm is: if the models predict that the price goes up, we execute immediately an ask limit order of size 1. We send an bid limit order of size 1 and a price increased by ρindex points. After a certain period of time, if the order is not executed, it will be canceled and a size 1 market order will be sent. Its translation to pseudocode is: cumsum ←0 for t := 1 to N-h-1 do if ˆy(t)=1then new.price ←p(1) b(t) + ρ fut.price ←max1≤k≤h{p(1) a(t+k)} if fut.price ≥new.price then cumsum ←cumsum +ρ else cumsum ←cumsum −new.price +p(1) a(t+h+ 1) end if end if end for return cumsum In consequence, given a set of predictions for different days, we define as trading score to the mean of the output of the algorithm these prediction. 20
5 Experimental results In this section, we present the results of the experiments we have done. We show every technique that we have applied, the motivations of them and the results. The results are summarized in figures, which show the performance of the models. The benchmark is represented by a red dotted line. In general, we present the results of two metrics: Accuracy and Min F1-score. Although we are usually guided by the accuracy, Min F1-score serves to verify that the accuracy is not misguiding. An extreme example is the case of having three balanced classes and an accuracy of 2 3. At first, it might seem like a better model than a random prediction, which has a accuracy of 1 3. However, this model may be a random prediction between two of the three classes. Since the minimum F1 score would be 0, it would clarify that it is a bad model. When the number of parameters of an ANN is shown, it has been calculated assuming that the input came from the raw time series. Since the difference is not significant, we decided not to include both numbers for the sake of clarity. 5.1 Performance of non-neural network models Our first approach was to try to short-term forecast the mid-price, using the traditional models and having as input the past mid price values. We split the data as follow: •The training set is the mid price of the first ten consecutive days. •The test set is mid price of the eleventh day. For the first evaluation, we made a prediction for the horizon 10 time steps into the future and rounded it to the closest multiple of half a tick size. The prediction is a possible mid price thanks to the rounding. Since some of the most simple forecasting methods can be comparatively effective to more complex ones, we chose as benchmark the naive forecast that always predicts the last observation. We measured the RMSE. The results of figure 6 show that the methods failed to predict the mid price value. Figure 6: RMSE comparison of simple models 21
For the second evaluation, we transformed the prediction into the lmlabels. We set α1, α−1for each day such that lmwas balanced. We measured the minimum F1-Score of each three labels and the benchmark is the random prediction. The results of figure 7 show that neither of these methods outperform the random prediction. Figure 7: Min F1-score comparison of simple models In conclusion, traditional time series analysis methods had failed to capture the complexity of the LOB market adequately. This experiment convinced us to address the classification problem directly and not try to predict the price, as we hoped to reduce the noise of the problem. 5.2 Performance of MLP and different CNNs with a Mid price based label We conducted experiments to observe the neural network performance in the prediction of the label lmbased on the direction of the mid price in an horizon h. We decided to set the horizon to h= 10 and we set the thresholds α1, α−1such that the classes are balanced for each day. However, if we had used all of the label values over the course of a day to define thresholds, we would be encoding future information on the label. Thus, the thresholds are defined to balance the labels of the previous five days. This approach for α1, α−1is common for the rest of the experiments. The loss function is the categorical cross-entropy. We used early stopping to avoid the overfitting. Thus, the data was always split in training set, validation test and test set and after one epoch, we evaluated the error on the validation set. If the error had not been reduced after two times, the training was stopped. 5.2.1 Experiment 1 The first experiment was conducted to find out which normalization had the best performance. Raw time series and stationary time series are represented by images using direct encoding. For this experiment, we set d= 50, so the image represented 50 consecutive days. This experiment also explored three forms of filters and because of that, we trained a neural network for each type of filter. The benchmark was the random guess. We set the maximum number of epochs to 20 and we split the data as follow: •The training set consisted of the first 40 consecutive days. 22
•The validation set consisted of the following 10 consecutive days. •The test set consisted of the following 10 consecutive days. We trained four ANN: •MLP with a hidden layer of 128 neurons. It had 128257 trainable parameters. •The first CNN was adapted from [Tra+20] and its filters were of the form 1 ×f. It had 181553 trainable parameters. The structure was: 1. Convolutional layer with 16 filters of size 1 ×10 2. Convolutional layer with 16 filters of size 1 ×10 3. Convolutional layer with 16 filters of size 1 ×8 4. Convolutional layer with 16 filters of size 1 ×6 5. Convolutional layer with 16 filters of size 1 ×4 6. Fully-connected layer with 32 neurons 7. Fully-connected layer with 3 neurons •The second CNN was adapted from [Zhe+15] and its filters were of the form f×1. It had 148977 trainable parameters. The structure was: 1. Convolutional layer with 16 filters of size 5 ×1 2. Max pooling of 2 ×1 3. Convolutional layer with 16 filters of size 5 ×1 4. Max pooling of 2 ×1 5. Fully-connected layer with 64 neurons 6. Fully-connected layer with 3 neurons •The third CNN used the most common form of filter: square filters. It had 102,049 trainable parameters. 1. Convolutional layer with 16 filters of size 3 ×3 2. Convolutional layer with 16 filters of size 3 ×3 3. Max pooling of 2 ×2 4. Convolutional layer with 16 filters of size 3 ×3 5. Convolutional layer with 16 filters of size 3 ×3 6. Max pooling of 2 ×2 7. Fully-connected layer with 128 neurons 8. Fully-connected layer with 3 neurons The results of figures 8 and 9 confirm that the transformation into stationary time series of the data significantly improve performance. Consequently, direct time series coding is constructed from stationary series. On other hand, no CNN had a significantly better performance than the random guess. In particular, the three CNNs and the random guess had a very similar Min F1-score. However, the third CNN seemed to have the best performance, as its accuracy outperforms the other CNNs. Since this CNN also was the one with the most traditional filters, the results convinced us to use square filters. In addition, since MLP outperformed the rest of the models and the benchmark, it became the new benchmark for the CNNs. 23
Figure 8: Min F1-score comparison between ANN models with direct encoding Figure 9: Accuracy comparison between ANN models with direct encoding 5.2.2 Experiment 2 This experimented was conducted to check the influence of the size of the training set and the number of dtime steps we take in account in the direct encoding representation. We trained an MLP with one hidden layer, since we also wanted to get a benchmark for future CNNs. We decided to use a hidden layer with 512 units because we were to avoid the possibility that a too simple MLP could not learn features of a big input. We set the maximum number of epochs to 25 and we split the data as follow: •The training set consisted of the first 10, 60 or 100 consecutive days. •The validation set consisted of the following 10 consecutive days. •The test set consisted of the following 10 consecutive days. The results of figures 10 and 11 show two main conclusions. The first conclusion is that MLP performance improves with more training data. However, after a certain point, the influence is very small. This conclusion was expected, unlike the other conclusion. We observe that increasing the size of the entrance worsens the performance model. This fact seems to indicate that the LOB dynamics mainly 24
depends on the most recent events, therefore, more historical data at the input can introduce noise into the model. The experiment consequence are the definition of the benchmark as the MLP with a hidden layer with 512 units, the number of dtime steps is set to 12, and the size of the training set is 100 days. Figure 10: Min F1-score comparison between MLP models with direct encoding Figure 11: Accuracy comparison between MLP models with direct encoding 5.2.3 Experiment 3 The reason behind this experiment was the exploration of other image representations. We tested the GAF representation and the two-channel representation. In both cases, we set the maximum number of epochs to 25 and we split the data as follow: •The training set consisted of the first 100 consecutive days. •The validation set consisted of the following 10 consecutive days. •The test set consisted of the following 10 consecutive days. The benchmark is the model obtained in the section 5.2.2. 25
labels l1and the thresholds τ1∈ { 4 20 ,6 20 }and both loss functions, i.e. binary cross-entropy and focal loss with (α, γ) = (0.5,0.5). Similarly to the previous experiment, for each trained model, we found the threshold πthat maximizes the trading score of the validation set. The results are summarised in the figure 19. Although the CNN model obtained a positive trading score, its performance is worse than the performance of MLP models. Due to the higher time cost of training compared to MLP, the number of experiments performed is significantly less. The last observation is that the focal loss continues to worsen the results for τ1∈ {4,6}. Figure 19: Trading score comparison between focal loss and cross-entropy In conclusion, it was possible to trade with positive gains directly from the predictions of an ANN. However, we have not been able to improve the results of the MLP with CNNs. 32
6 Conclusion We started with a traditional time series analysis that failed to accurately capture the nonlinearity nature of LOB, followed by an ANN study applied to a classification problem. At first, we designed CNN to try to predict the direction of the mid price, which is a common approach in the literature. Although the experiments showed that CNNs were able to capture LOB nonlinearities and improve the results achieved with MLP, they did not achieve high accuracies. Different methodologies have been applied to correct this problem, as testing different architectures and LOB representation, but they have not offered good solutions. At last, we have introduced new labels with the motivation to predict when the trade reports benefits. Although we have achieved the objective of developing CNN models that obtain positive results, these are inferior to those obtained with MLP. Further development in the project may include further experimentation with CNN in predicting the new labels. After that, a possible approach would be to try to eliminate the labeling process by using Reinforcement learning algorithms. Since in the context of HFT is easy to define a reward, for example, the obtained benefit, these algorithms seem a good option. 33
7 Annex: Simple models In this section, we expand the description of the simple models. They are going to be defined for time series y, where y1· · · yTis the historical data and ˆyT+h|Tis the estimate of yT+hbased on the historical data. 7.1 ARIMA The mathematical formulation of the ARIMA(p,d,q) model using lag polynomial is: 1−Pp i=1 φiLi(1 −L)dyt=1−Pp i=1 θiLi where p,d,qare nonnegative integers and refer to the order of the autoregressive, integrated and moving average parts of the model. The lag operator is define as Lyt=yt−1 In the case of d= 1, the model can be rewritten as: y0 t=c+φ1y0 t−1+· · · +φpy0 t−p+θ1εt−1+·+θqεt−q+εtwhere y0 tis the differenced series. If ytis differenced once, the result series is y0 t=yt−yt−1. We can difference a time series more than once. For instance, the twice-differenced series is y00 t=y0 t−y0 t−1=yt−yt−1−(yt−1−yt−2) = yt−2yt−1+yt−2 7.2 Naive A naive forecast is optimal when data follow a random walk. Since the random walk is a common model for the evolution of stock prices, it is a reasonable benchmark. The mathematical formulation is: ˆyT+h|T=yT This model is equivalent to an ARIMA(0,1,0). 7.3 Exponential smoothing One can choose whether to have trend and seasonal terms and also one can choose whether they are additive or multiplicative. This can be expressed compactly with the triplet (E,T,S) refers to the three components: error, trend and seasonality. This notation helps in specifying how the components are specified: N, A, M refer to none, additive and multiplicative respectively. For example, the simplest model is ETS(A,N,N) and is also called simple exponential smoothing. This forecast has the form of: ˆyT+1|T=αyT+ (1 −α)ˆyT|T−1 . All forecast take the same value ˆyT+h|T= ˆyT+1|T The linear exponential smoothing models are all special cases of ARIMA models (ETS(A,N,N) corresponds to ARIMA(0,1,1) and ETS(A,A,N) corresponds to ARIMA(0,2,2)). However, the non-linear exponential smoothing models have no equivalent ARIMA counterparts. On the other hand, there are also many ARIMA models that have no exponential smoothing counterparts. In particular, all ETS models are non-stationary, while some ARIMA models are stationary. 34
8 Annex: Custom loss function The categorical cross-entropy measures the difference between the distributions of the real and predicted labels. We explored the idea of using the confusion matrix to penalize errors more than others -for example, the penalty of predicting downward mid price direction instead of upward should be greater than the penalty of predicting no significant change and being wrong. The reason comes from the financial point of view, since it is evident that there are misprediction that could cause more losses than others. Therefore, we explored the idea of a custom loss function which tries to accomplish the task of scoring the confusion matrix. Since the loss functions must be differential, we approximate as: Q(y,ˆ y) = ytˆ y where y,ˆ y∈RN×Care bunch of Nrow vector and Cnumbers of classes. The vector yirepresents the target prediction and ˆ yithe model outcome for the same input. To score Q, we add the elements of the matrix resulting from the element-wise product of the matrix Qand the weight matrix θ. q(Q;θ) = IC·(θQ)·It C where ICis the unity row vector (1,...,1) of dimension 1 ×C. We observed that q(Q(y,ˆ y); θ) = N X i=1 q(Q(yi,ˆ yi); θ) We restricted ourselves to a model prediction and its target value to study and define the function. In this way, the function can be rewritten as: L(y, ˆy;θ) = − C X i=1 C X j=1 θij ·yi·ˆyj It has a minus sign so that minimizing the loss function is maximizing the matrix score. 8.1 Confunsion matrix It is a multiclass loss, so the activation function of the output layer is softmax. Let be zthe output of the model before applying the activation function and pthe output of the model after applying the activation function. Then, pi=ezi PC j=1 ezj Since the weights are updated by a stochastic gradient descent algorithm, the update depends on the gradient of the loss function respect to the weight. In general, this gradient is calculated by the chain rule, so it depends heavily on the gradient of the loss function respect to the output of the model. 35
∂L(y, p) ∂zk =− C X i=1 C X j=1 θij ·yi ∂pj ∂zk = =− C X i=1 C X j=1 θij ·yipj(δjk −pk) = =− C X i=1 − C X j=1 j6=k (θijyipjpk) + θik ·yipk(1 −pk) = =−pk C X i=1 yi θik − C X j=1 θijpj =−pk C X i=1 yi C X j=1 (θik −θij)pj When y=p, the derivative of loss function is zero. We want this since the red neuronal does not need any update. However, when y= (1,0,0), then p= (0, p2, p3) is also a point that cancel the derivative. Because of that, we discard this function, since it has bad properties. An example is: θ= 100 010 001 =⇒∂L(y, p) ∂zk =−pk C X j=1 j6=k ykpj=−pk(1 −pk)yk where the penalization for the penalty for a very incorrect prediction is the same as for a very correct one. 8.2 Logarithm We add a function fto the loss function to try to get another one with better properties. L(y, ˆy;θ, f) = − C X i=1 C X j=1 θij ·yi·f(ˆyj) Then, ∂L(y, p) ∂zk =− C X i=1 C X j=1 θij ·yif0(pj)∂pj ∂zk = =−pk C X i=1 yi θikf0(pk)− C X j=1 θijf0(pj)pj = =−pk C X i=1 θikyif0(pk) + pk C X i=1 C X j=1 θijyif0(pj)pj 36
To avoid unwanted zeros, necessarily if yk= 1, then limpk→0+∂L(y,p) ∂zk=c, where cis a non zero constant. The condition has to be satisfied for every pj, where j6=k. Since fis not the constant function: lim pk→0+pk C X i=1 C X j=1 θijyif0(pj)pj= 0 Therefore, lim pk→0+ ∂L(y, p) ∂zk = lim pk→0+−pk C X i=1 θikyif0(pk) = −θkk lim pk→0+pkf0(pk) = c=⇒lim x→0+xf0(x) = lim x→0+ f0(x) 1 x =c0 We can conclude that f0(x)∼1 xas x→0+. A natural option for f0(x) is 1 x. Because of that, we set f(x) = log(x): ∂L(y, p) ∂zk =− C X i=1 yi θik − C X j=1 θijpkpj = =−θtk +pk C X j=1 θtjpjwhere yi=δit Assuming that k6=tand pk= 0, then ∂L(y,p) ∂zk=−θtk In conclusion, the loss function should have the form: L(y, ˆy;θ,log) = − C X i=1 θii ·yi·log(ˆyi) We note that this function is a weighted categorical cross-entropy. 37
References [Alp10] Ethem Alpaydin. Introduction to Machine Learning, Second Edition (Adaptive Computation and Machine Learning). 2nd ed. Adaptive Computation and Machine Learning. The MIT Press, 2010. isbn: 026201243X,9780262012430. url:http://gen.lib.rus.ec/book/ index.php?md5=78e4afc293ef14dfe964fc156cd079c0. [BKK18] Shaojie Bai, J. Zico Kolter, and Vladlen Koltun. “An Empirical Evaluation of Generic Convolutional and Recurrent Networks for Sequence Modeling”. In: CoRR abs/1803.01271 (2018). arXiv: 1803.01271.url:http://arxiv.org/abs/1803.01271. [Bas+18] Amitabh Basu et al. “Convergence guarantees for RMSProp and ADAM in non-convex optimization and their comparison to Nesterov acceleration on autoencoders”. In: CoRR abs/1807.06766 (2018). arXiv: 1807.06766.url:http://arxiv.org/abs/1807.06766. [Bis07] Christopher M. Bishop. Natural networks for pattern recognition. Oxford Univ. Press, 2007. [Hau14] Nikolaus Hautsch. Econometrics of financial high-frequency data. Springer, 2014. [Hay16] Simon Haykin. Neural networks and learning machines. 3rd ed. Delhi Chennai: Pearson, 2016. [Hyn08] Rob Hyndman. Forecasting with exponential smoothing: the state space approach. Springer, 2008. [HA18] Rob J. Hyndman and George Athanasopoulos. Forecasting: principles and practice. 3rd ed. OTexts, 2018. [Lin+17] Tsung-Yi Lin et al. “Focal Loss for Dense Object Detection”. In: CoRR abs/1708.02002 (2017). arXiv: 1708.02002.url:http://arxiv.org/abs/1708.02002. [Lu+17] Zhou Lu et al. “The Expressive Power of Neural Networks: A View from the Width”. In: Advances in Neural Information Processing Systems 30. Ed. by I. Guyon et al. Curran Associates, Inc., 2017, pp. 6231–6239. url:http://papers.nips.cc/paper/7203-the- expressive-power-of-neural-networks-a-view-from-the-width.pdf. [Nou+18] Paraskevi Nousi et al. “Machine Learning for Forecasting Mid Price Movement using Limit Order Book Data”. In: CoRR abs/1809.07861 (2018). arXiv: 1809.07861.url:http: //arxiv.org/abs/1809.07861. [Nta+17] Adamantios Ntakaris et al. “Benchmark Dataset for Mid-Price Prediction of Limit Order Book data”. In: CoRR abs/1705.03233 (2017). arXiv: 1705.03233.url:http://arxiv. org/abs/1705.03233. [Sil+17] Ivan Nunes da Silva et al. Artificial Neural Networks. Springer International Publishing, 2017. doi:10.1007/978-3-319-43162-8.url:https://doi.org/10.1007/978-3-319- 43162-8. [SZ14a] Karen Simonyan and Andrew Zisserman. Very Deep Convolutional Networks for Large- Scale Image Recognition. 2014. arXiv: 1409.1556 [cs.CV]. [SZ14b] Karen Simonyan and Andrew Zisserman. Very Deep Convolutional Networks for Large- Scale Image Recognition. 2014. arXiv: 1409.1556 [cs.CV]. [Tra+20] Dat Thanh Tran et al. Data Normalization for Bilinear Structures in High-Frequency Financial Time-series. 2020. arXiv: 2003.00598 [cs.CE]. [Tsa16] Ruey S. Tsay. Analysis of financial time series. Wiley India, 2016. [WZ15] Zhaodong Wang and Weian Zheng. High-frequency trading and probability theory. World Scientific, 2015. 38
[WO15] Zhiguang Wang and Tim Oates. Imaging Time-Series to Improve Classification and Imputation. 2015. arXiv: 1506.00327 [cs.LG]. [YD19] Omolbanin Yazdanbakhsh and Scott Dick. “Multivariate Time Series Classification using Dilated Convolutional Neural Network”. In: CoRR abs/1905.01697 (2019). arXiv: 1905. 01697.url:http://arxiv.org/abs/1905.01697. [ZZR19] Zihao Zhang, Stefan Zohren, and Stephen Roberts. “DeepLOB: Deep Convolutional Neural Networks for Limit Order Books”. In: IEEE Transactions on Signal Processing 67.11 (June 2019), pp. 3001–3012. issn: 1941-0476. doi:10.1109/tsp.2019.2907260.url:http: //dx.doi.org/10.1109/TSP.2019.2907260. [Zhe+15] Yi Zheng et al. “Exploiting multi-channels deep convolutional neural networks for multivariate time series classification”. In: Frontiers of Computer Science 10.1 (Aug. 2015), pp. 96–112. doi:10.1007/s11704-015-4478-2. 39