Introduction¶
Machine learning provides a collection of principled statistical methods for learning mappings from data, bypassing the need to specify a closed-form generative model for every phenomenon of interest. In algorithmic trading, the range of applications is broad: predicting short-term price displacements in Fair value estimation, fitting win-probability curves in Modelling RfQs in Dealer to Client Markets, constructing composite liquidity indicators in Liquidity Modelling, and generating investment signals in Quantitative Investment Fundamentals. This chapter develops the mathematical foundations that underpin all of these applications, emphasising core theory rather than software libraries or data pipelines.
The chapter is organised as follows. We open with the statistical learning framework (Statistical Learning Framework): the formalisation of learning as risk minimisation, the bias–variance decomposition, and the tools of regularisation and cross-validation. The bulk of the chapter is devoted to supervised learning (Supervised Learning): linear regression and its probabilistic interpretation, ridge and lasso regularisation as MAP inference, logistic regression for classification, kernel methods and support vector machines, tree ensembles (random forests and gradient boosting), and the fundamentals of neural networks. We then cover unsupervised learning (Unsupervised Learning): principal component analysis derived as a variance-maximising projection, and -means clustering as a special case of the EM algorithm. The chapter closes with reinforcement learning (Reinforcement Learning): the Markov decision process, Bellman equations, -learning, and policy gradient methods, providing the theoretical scaffold for sequential decision-making in trading.
Statistical Learning Framework¶
Risk minimisation¶
Let be an input–output pair drawn from an unknown joint distribution, with a feature vector and a target. A model is a function that predicts from . The quality of a prediction is measured by a loss function ; common choices are the squared error for regression and the 0–1 loss for classification. The expected risk (or generalisation error) of is
The ideal model minimises over all measurable functions. For squared-error loss, differentiating inside the expectation shows that the optimal predictor is the regression function Murphy, 2013. For the 0–1 loss, the optimal predictor is the Bayes classifier .
Since is unknown, cannot be computed. Given a training dataset of i.i.d. samples, we substitute the empirical risk
Empirical risk minimisation (ERM) finds within a restricted function class . If is too rich, memorises the training data (overfitting); if too restricted, it cannot approximate (underfitting). The generalisation gap depends on the complexity of , which is controlled through regularisation and cross-validation.
Bias–variance decomposition¶
For squared-error loss and a model learned from a training set of size , the expected test error at a point decomposes as Bishop, 2006
where is irreducible noise. The bias measures systematic error from model mis-specification; the variance measures sensitivity to the particular training set realised. More flexible models (higher-degree polynomials, deeper trees) reduce bias but increase variance, producing the characteristic U-shaped test error curve as a function of model complexity (Figure 1). Regularisation and ensemble methods are the primary tools for managing this tradeoff.

Figure 1:Test error (solid) and training error (dashed) as a function of polynomial degree on a sinusoidal regression problem with noisy observations, averaged over 50 datasets. The irreducible noise floor is shown as a dotted line. Low degree yields high bias; high degree yields high variance. The optimal degree minimises test error.
Regularisation¶
Regularisation incorporates a penalty on model complexity into the objective:
where measures complexity and is a hyperparameter. Increasing shifts the bias–variance tradeoff towards higher bias and lower variance. From a Bayesian perspective (Bayesian Modelling), regularisation is MAP estimation under the prior : the penalty encodes prior beliefs about the smoothness or sparsity of .
Cross-validation and model selection¶
The hyperparameter — along with structural choices such as tree depth or network architecture — must be selected using data not in the training set. -fold cross-validation divides into equal folds, training on folds and evaluating on the remaining fold, then averaging over all splits:
where is the model trained on all folds except and is the empirical risk on fold . Common choices are or ; the limit is leave-one-out cross-validation. A completely withheld test set is reserved for final evaluation and must never inform any modelling decision.
Supervised Learning¶
Supervised learning covers problems where each training example pairs an input with a target . When the task is regression; when the task is classification. We treat the core model families in increasing order of flexibility.
Linear Regression¶
The simplest regression model is linear in a feature vector :
The feature map may include raw inputs, polynomial terms, or any fixed nonlinear transformation; the model remains linear in the parameters . Collecting all training points into the design matrix with rows and the target vector , ERM under squared-error loss gives the ordinary least squares (OLS) criterion
Setting the gradient to zero yields the normal equations , with closed-form solution
where is the Moore–Penrose pseudoinverse. Geometrically, is the orthogonal projection of onto the column space of .
Probabilistic interpretation. Assuming with , the log-likelihood is
Maximising over recovers the OLS estimator: least squares is maximum likelihood under Gaussian noise. Placing a Gaussian prior on and computing the posterior leads to Bayesian linear regression and the predictive distribution, developed in Bayesian Modelling.
Gauss–Markov theorem. Among all linear unbiased estimators, OLS achieves minimum variance — it is the Best Linear Unbiased Estimator (BLUE). This optimality can break down under high multicollinearity (when is near-singular) or when some bias is acceptable in exchange for lower variance, motivating the regularised estimators of the next section.
Regularisation¶
Ridge regression adds an penalty on the coefficients:
The unique closed-form solution is
Adding conditions the Gram matrix and removes the singularity problem. Probabilistically, ridge regression is MAP estimation under a spherical Gaussian prior . Using the SVD , the prediction at a new input can be written as a sum over principal directions with shrinkage factors : directions of small singular value (low signal-to-noise) are suppressed.
Lasso regression substitutes an penalty:
The penalty has a kink at the origin that forces many coefficients to be exactly zero for sufficiently large , performing variable selection simultaneously with shrinkage. Probabilistically, lasso is MAP under independent Laplace priors . There is no closed-form solution; efficient algorithms use coordinate descent or the LARS algorithm Hastie et al., 2009. (Figure 2).

Figure 2:Regularisation paths for ridge (left) and lasso (right) on a dataset with ten predictors, five informative (coloured lines). Each curve is one coefficient plotted against the log-penalty , moving from right (no penalty) to left (maximum penalty). Ridge shrinks all coefficients smoothly; lasso sets coefficients to zero sequentially, yielding a sparse model.
Elastic net combines both penalties: . It inherits lasso’s sparsity while retaining the grouping property of ridge (correlated predictors are selected jointly), which is desirable when financial features are highly collinear. These regularised regression models are used in Liquidity Modelling to combine liquidity metrics and identify their relative predictive contributions.
Classification and Logistic Regression¶
For a binary target , the logistic regression model places the posterior probability of the positive class as
The sigmoid maps the linear score to . The log-odds ratio is linear in , so the decision boundary is a hyperplane in feature space. The negative log-likelihood under Bernoulli observations gives the cross-entropy loss
where . This is convex in but has no closed-form minimiser; iterative methods such as gradient descent or Newton–Raphson (IRLS) are used. The gradient has the clean form : it is the residual of predicted probabilities against targets, projected by the design matrix.
For classes, logistic regression extends to the softmax model:
with a corresponding multinomial cross-entropy loss. Logistic regression is used in Modelling RfQs in Dealer to Client Markets to estimate the probability that a client’s reservation price exceeds the dealer’s quoted spread, and to identify whether a client is engaging in price discovery.

Figure 3:Decision boundaries on a two-dimensional binary classification dataset for logistic regression (linear boundary), SVM with RBF kernel (smooth nonlinear boundary), and a two-hidden-layer MLP (complex nonlinear boundary). All three achieve similar training accuracy; the nonlinear models adapt to the data geometry at the cost of higher variance.
Kernel Methods and Support Vector Machines¶
Many problems require nonlinear decision boundaries. Rather than engineering nonlinear features explicitly, the kernel trick exploits the fact that many learning algorithms depend on the data only through inner products . If one defines a kernel function , these inner products can be evaluated directly in input space without ever computing . By Mercer’s theorem, any symmetric positive semi-definite function is a valid kernel Bishop, 2006. The Gaussian (RBF) kernel corresponds to an infinite-dimensional feature space.
Kernel ridge regression. By the representer theorem, the optimal weight vector of any regularised learning algorithm lies in the span of the training feature vectors: . Substituting into the ridge objective and writing for the Gram matrix yields the dual formulation
where . This is equivalent to Gaussian process regression (Bayesian Modelling) with kernel as the covariance function.
Support vector machines. The SVM Vapnik, 1995 seeks the maximum-margin linear separator in feature space. For linearly separable data, the primal problem is
The margin between the two supporting hyperplanes is , so minimising maximises the margin. The Lagrangian dual depends only on the inner products , which are replaced by to give the kernel SVM. Only training points that lie on the margin boundary have non-zero dual variables and are called support vectors; the decision boundary depends only on these. For non-separable data, slack variables relax the constraints at cost , with acting as inverse regularisation strength.
Tree Ensembles¶
A decision tree partitions the input space into rectangular regions by recursively splitting on one feature at a time. At each node, the best split on feature at threshold maximises the gain in purity
where is within-region variance for regression or Gini impurity for classification. A single deep tree is a high-variance, low-bias estimator: small changes in the training data can alter the entire partition. Ensemble methods reduce variance by aggregating many trees.
Random forests Breiman, 2001 build trees in parallel, each trained on a bootstrap sample . At each split, only features are considered (typically for classification, for regression), de-correlating the trees. The prediction is the average (regression) or majority vote (classification):
By the bias-variance decomposition, the ensemble variance is , where is the average pairwise correlation between tree predictions. Feature randomisation reduces below what bagging alone achieves, and as the variance converges to , without further decrease; adding trees only reduces sampling noise.
Gradient boosted trees Friedman, 2001 build trees sequentially. Each new tree fits the negative gradient of the loss with respect to the current ensemble prediction :
For squared-error loss the negative gradient is the residual , so each tree fits the current residuals. For a general differentiable loss , the pseudo-residuals
define the gradient direction in function space. This functional gradient descent perspective makes gradient boosting highly flexible: the loss can be cross-entropy for classification, quantile loss for prediction intervals, or any domain-specific objective. Modern implementations (XGBoost, LightGBM) add second-order Newton steps and column/row subsampling for regularisation. Gradient-boosted trees achieve state-of-the-art performance on tabular financial data and are widely used in Modelling RfQs in Dealer to Client Markets for win-probability estimation (Figure 4).

Figure 4:Left: test RMSE as a function of the number of trees for a random forest and gradient-boosted ensemble, against the single-tree baseline (dashed). The random forest converges quickly; gradient boosting improves monotonically. Right: feature importances (mean decrease in impurity) from the random forest, with the five truly informative features highlighted.
Neural Networks¶
A multilayer perceptron (MLP) is a function formed by composing affine transformations and pointwise nonlinearities. With hidden layers of widths , the forward pass is
where is an activation function applied element-wise. Popular choices include the ReLU (avoids vanishing gradients, induces sparsity in activations), the hyperbolic tangent , and for the output layer the sigmoid or softmax for classification.
Universal approximation. The MLP is a universal function approximator: for any continuous and , there exists an MLP with a single hidden layer and sufficiently many units such that Cybenko, 1989. Depth provides efficiency: deeper networks can represent the same functions with exponentially fewer parameters, motivating the deep architectures used in practice Goodfellow et al., 2016.
Backpropagation. Training minimises the empirical risk over all parameters using gradient descent. The gradient is computed by backpropagation Rumelhart et al., 1986, which applies the chain rule backward through the network. Defining the error signal at layer as (where is the pre-activation), the backward recurrence is
The gradient with respect to the weight matrix is . The total computational cost is , the same order as a single forward pass. In practice, mini-batch SGD replaces the full-data gradient with a noisy estimate over a small batch :
Adaptive optimisers — Adam, RMSProp — maintain per-parameter step sizes and converge faster in practice. Regularisation of neural networks uses weight decay ( penalty on ), dropout (randomly zeroing activations during training, equivalent to an ensemble of thinned networks), and early stopping based on validation loss (Figure 5).

Figure 5:Training and validation MSE for an MLP on a simulated regression task, without regularisation (left) and with weight decay (right). Without regularisation the model overfits: training loss falls while validation loss rises after an early minimum. Weight decay maintains a small gap between the two curves.
Deep neural networks — including recurrent networks for sequential data and the Transformer architecture — build on these foundations and are covered in Generative Artificial Intelligence in the context of language modelling and generative AI.
Unsupervised Learning¶
Unsupervised learning addresses settings where no target label is available and the objective is to discover structure in the marginal distribution . The two main themes are dimensionality reduction — finding a low-dimensional representation that preserves information — and clustering — identifying groups or modes in .
Principal Component Analysis¶
Let be a centred data matrix (columns mean-zero). Principal component analysis (PCA) finds the orthogonal directions that maximise the projected variance. The first principal component solves
where is the sample covariance matrix. By Lagrange multipliers, : the first PC is the eigenvector of with the largest eigenvalue , which equals the projected variance. Successive PCs are the remaining eigenvectors in decreasing eigenvalue order, subject to orthogonality.
Equivalently, PCA minimises reconstruction error: with the score matrix (columns ), the reconstruction minimises over all rank- approximations. By the Eckart–Young theorem, the minimum is achieved by the truncated SVD , and the minimum reconstruction error equals . The fraction of variance explained by components is (Figure 6).
PCA has many financial applications: extracting common risk factors from a returns covariance matrix, constructing composite indicators from correlated liquidity metrics (Liquidity Modelling), and identifying the idiosyncratic residuals of stock returns relative to market factors in statistical arbitrage (Optimal Investment Theory).

Figure 6:Left: a two-dimensional correlated dataset with the two principal component directions overlaid; arrow length is proportional to the square root of the corresponding eigenvalue. Right: cumulative explained variance ratio as a function of the number of components for a ten-dimensional dataset; the elbow marks the intrinsic dimensionality of the data.
Autoencoders¶
PCA finds a linear subspace that best reconstructs the data. An autoencoder generalises this to nonlinear embeddings by parameterising both the projection and its inverse as neural networks. The architecture consists of two components: an encoder that maps a high-dimensional input to a low-dimensional latent code , and a decoder that reconstructs the input from the latent code . Training minimises the reconstruction loss:
by gradient descent through both encoder and decoder simultaneously. When encoder and decoder are restricted to affine maps and the bottleneck dimension is , the optimal solution recovers the -dimensional PCA subspace — autoencoders are therefore a strict generalisation of PCA.
With nonlinear activations, the latent code can capture curved manifolds and interactions between variables that a linear projection misses. For a yield curve with maturities, for example, a nonlinear autoencoder with latent dimensions can reconstruct shapes that lie far from any three-dimensional linear subspace, provided the yield curve moves tend to concentrate on a smooth manifold in .
Variational autoencoders. A standard autoencoder learns a deterministic mapping and provides no guarantee that the latent space is continuous or well-structured. The variational autoencoder (VAE) Kingma & Welling, 2013 places a probabilistic prior on the latent code, , and trains the encoder to output a distribution rather than a point. The training objective is the evidence lower bound (ELBO):
The first term is the reconstruction likelihood; the second regularises the posterior toward the prior, encouraging a smooth and interpretable latent space. The ELBO is maximised using the reparameterisation trick: sample and set , making the gradient with respect to tractable.
Financial applications. Autoencoders are used in finance wherever PCA’s linearity is a binding constraint. Three recurring applications are: (i) yield curve compression — learning a 3–5 dimensional nonlinear representation of a 30-point yield curve for risk management; (ii) covariance matrix estimation — using the latent structure to denoise the sample covariance, reducing estimation error for large portfolios; and (iii) factor hedging — computing instrument sensitivities with respect to the latent factors by automatic differentiation through the decoder, giving nonlinear hedging coefficients that generalise the linear PCA hedge (Optimal Hedging).

Figure 7:Left: reconstruction of a held-out yield curve by a two-hidden-layer autoencoder with latent dimensions (red) against the true curve (blue); the residual is plotted below. Right: the three latent codes over time for a sequence of yield curves; the first code tracks the level of the curve and the second its slope, analogous to the first two PCA factors but in a nonlinear embedding.
Monotone Neural Networks¶
Standard neural networks are universal approximators with no built-in constraint on the relationship between outputs and inputs. Many pricing and hedging functions, however, must satisfy monotonicity properties that follow from no-arbitrage: a call option price must be non-increasing in strike and non-decreasing in spot and volatility ; a bond price must be non-increasing in yield; a portfolio value must be non-decreasing in the amounts of assets held (when they are non-negative contributors). Approximating such functions with an unconstrained neural network risks producing arbitrage-violating outputs in regions of the input space where the training data are sparse.
A monotone neural network is an architecture that guarantees (or ) for every input and every realisation of the weights, not just on average. The simplest construction enforces non-negativity of all weight matrices applied to the constrained inputs, combined with a non-decreasing activation function:
where are unconstrained parameters and is applied element-wise. Since is strictly positive and or is non-decreasing, the chain rule gives for any composition depth. The cost is a reduction in expressiveness: the function class is restricted to isotone maps in the constrained arguments.
A richer construction is the input convex neural network (ICNN) Amos et al., 2017, in which the output is a convex function of the inputs. Convex functions are monotone in their gradient, so ICCNs can represent monotone relationships while retaining more flexibility in the unconstrained arguments. The ICNN architecture passes skip connections from the input directly to each hidden layer with non-negative weights, guaranteeing convexity in those arguments:
where (element-wise non-negative). The output is then convex in , so is a monotone map from to .
Application to Greeks computation. Once a monotone network is trained to approximate an option price , the hedge ratios follow by automatic differentiation: , , . This is fast (one backward pass through the network) and exact with respect to the surrogate. The monotonicity constraint ensures that the computed delta lies in for calls and for puts, even for inputs outside the training distribution. This application is discussed further in Accelerating Hedge Computations with Machine Learning.
![Left: BSM call price surface (ground truth) against the approximation by a standard MLP and a monotone MLP, for varying moneyness S/K and time-to-maturity T. Right: the call delta \partial C/\partial S computed by automatic differentiation through each network; the monotone network lies within [0,1] everywhere whereas the standard MLP produces negative deltas in sparse regions.](/build/ddm_monotone_nn-61d51406b2be96afdc988e759a4b54be.png)
Figure 8:Left: BSM call price surface (ground truth) against the approximation by a standard MLP and a monotone MLP, for varying moneyness and time-to-maturity . Right: the call delta computed by automatic differentiation through each network; the monotone network lies within everywhere whereas the standard MLP produces negative deltas in sparse regions.
Clustering and the EM Algorithm¶
-means partitions points into clusters by minimising the total within-cluster variance
The standard algorithm alternates between two steps:
Assignment: — assign each point to the nearest centroid.
Update: — recompute centroids as cluster means.
Each step decreases , guaranteeing convergence to a local minimum. -means is a special case of the EM algorithm applied to a Gaussian mixture model (GMM) with equal, isotropic covariances and equal mixing weights: the E-step is a hard assignment of each point to the nearest component, and the M-step re-estimates the means. The soft-assignment GMM (Bayesian Modelling) replaces hard assignments with responsibilities and also learns the covariance structure of each component, yielding a proper density model.
Selecting the number of clusters requires a model selection criterion. The Bayesian Information Criterion penalises the log-likelihood by the number of free parameters and the log-sample-size, providing a principled tradeoff between fit and complexity Murphy, 2013.
Reinforcement Learning¶
Reinforcement learning (RL) addresses sequential decision-making problems in which an agent interacts with an environment over discrete time steps, taking actions and receiving scalar rewards Sutton & Barto, 2018. Unlike supervised learning, there is no labelled dataset: the agent must discover which actions are beneficial by exploration. The formal framework is the Markov decision process (MDP).
Markov Decision Processes¶
An MDP is specified by the tuple :
: state space (observations available to the agent),
: action space,
: transition kernel (environment dynamics),
: expected immediate reward for taking action in state ,
: discount factor that down-weights future rewards.
The agent follows a policy , a conditional distribution over actions given the state. The goal is to find the policy that maximises the expected discounted return .
Value Functions and Bellman Equations¶
The state-value function of policy is the expected return from state :
The action-value function captures the expected return of taking action in state and thereafter following . Both satisfy Bellman equations expressing the value of a state recursively in terms of successor states:
The optimal value function satisfies the Bellman optimality equations, a system of nonlinear fixed-point equations whose solution defines the optimal policy .
-Learning and Policy Gradient¶
When the transition kernel is unknown, model-free methods learn directly from experience. -learning applies the update
The bracketed term is the temporal-difference (TD) error between the current estimate and the one-step bootstrapped target. When is represented by a neural network — the deep Q-network (DQN) — this approach scales to high-dimensional state spaces such as order book snapshots.
Policy gradient methods directly parameterise the policy and maximise by gradient ascent. The policy gradient theorem provides an unbiased gradient estimator:
which can be estimated from sampled trajectories without knowledge of . Actor-critic methods combine a parameterised policy (the actor) with a learned value function (the critic) to reduce the variance of the policy gradient estimator, using the advantage instead of as the learning signal. RL provides the theoretical basis for applications in market making and optimal execution, where a trading agent must take sequential decisions under uncertainty about the order flow and market impact.
Exercises¶
Bias–variance decomposition. Consider estimating from noisy observations using polynomial regression of degree with OLS. (a) Sketch qualitatively how squared bias and variance change with and explain why. (b) Show that as , training error approaches zero. What happens to test error and why?
Ridge shrinkage via SVD. Using the SVD , show that the ridge predictor at a test point can be written as and compare the shrinkage factors to OLS. What happens to directions of very small singular value?
Lasso sparsity via subgradients. Using the KKT conditions for the lasso, show that the -th coefficient satisfies if and only if , where is the -th column of and denotes all other coefficients. Interpret the condition in terms of the correlation between feature and the residuals.
Kernel computation. Verify that the polynomial kernel for corresponds to the explicit feature map . What is the dimension of the feature space for a degree- polynomial kernel in ?
Gradient boosting. Implement gradient boosting for a regression problem from scratch using depth-1 trees (stumps) and squared-error loss. Plot ensemble predictions after 1, 10, 50, and 100 rounds and plot training and test error vs. boosting iteration. How does the learning rate affect convergence and overfitting behaviour?
PCA as optimal compression. Show that the rank- linear reconstruction minimises over all choices of orthonormal columns in . Express the minimum error in terms of the discarded eigenvalues of the sample covariance matrix.
Bellman iteration. For a two-state, two-action MDP with known and , write the Bellman optimality equations explicitly and solve for . Verify that the greedy policy recovers the optimal policy found by exhaustive enumeration.
- Murphy, K. P. (2013). Machine learning : a probabilistic perspective. MIT Press.
- Bishop, C. M. (2006). Pattern Recognition and Machine Learning. Springer.
- Hastie, T., Tibshirani, R., & Friedman, J. (2009). The Elements of Statistical Learning: Data Mining, Inference, and Prediction (2nd ed.). Springer.
- Vapnik, V. N. (1995). The Nature of Statistical Learning Theory. Springer.
- Breiman, L. (2001). Random Forests. Machine Learning, 45(1), 5–32.
- Friedman, J. H. (2001). Greedy Function Approximation: A Gradient Boosting Machine. Annals of Statistics, 29(5), 1189–1232.
- Cybenko, G. (1989). Approximation by Superpositions of a Sigmoidal Function. Mathematics of Control, Signals and Systems, 2(4), 303–314.
- Goodfellow, I., Bengio, Y., & Courville, A. (2016). Deep Learning. MIT Press.
- Rumelhart, D. E., Hinton, G. E., & Williams, R. J. (1986). Learning Representations by Back-propagating Errors. Nature, 323, 533–536.
- Kingma, D. P., & Welling, M. (2013). Auto-Encoding Variational Bayes. arXiv Preprint arXiv:1312.6114.
- Amos, B., Xu, L., & Kolter, J. Z. (2017). Input Convex Neural Networks. Proceedings of the 34th International Conference on Machine Learning, 146–155.
- Sutton, R. S., & Barto, A. G. (2018). Reinforcement Learning: An Introduction (2nd ed.). MIT Press.