QM 6 – Machine Learning
The volume of data available to investors keeps growing, the variety of that data keeps widening, and the economic value of the insights buried inside it keeps rising. Data science has grown up in response, borrowing from mathematics, computer science and business analytics, and adding something the older disciplines did not emphasise: learning. Learning here ranges from simple functions that map one variable onto another to elaborate networks that absorb information, order it and adapt to it.
For an investment professional the practical question is not whether to become a data scientist. It is whether you can source sensible inputs, read the outputs correctly, and turn those outputs into portfolio decisions. That requires an understanding of which investment problems machine learning can address, a working picture of how the main algorithms operate, and enough vocabulary to hold a serious conversation with a quantitative team.
Where the techniques are already being applied
The techniques now appear at every link of the value chain in asset and wealth management.
- Client-facing services. Chatbots field basic retirement savings questions and improve as they accumulate interactions with investors.
- Alpha generation. A signal for security selection can be produced in three ways: a non-linear forecast of one time series, a forecast assembled out of a set of factors defined in advance, or a design in which the algorithm itself picks which inputs to use, whether from existing sources or newly discovered ones. Work using textual analysis reports that when a company revises its annual and quarterly filings, the 10-K and the 10-Q, against the same document one year earlier, those revisions predict equity returns strongly. The predictive content concentrates in deterioration inside the sections dealing with management discussion and with risk.
- Portfolio construction. Target portfolio weights can be calculated subject to client restrictions and then reweighted dynamically to maximise a Sharpe ratio. A better estimate of the variance–covariance matrix can be obtained through principal components analysis, which shrinks how many variables are required before the variation present in the data is accounted for. Research points to machine learning solutions beating mean–variance optimisation at the construction stage.
- Trading and operations. Order flow management tools built on non-linear trading algorithms cut what it costs to put a portfolio decision into effect. The same forces have automated whole tools, processes and businesses, robo-advising being the obvious case.
The wider claim is more ambitious still. Large datasets and learning models may reshape what the profession believes about asset risk premiums, and may reconfigure the business processes of investment management itself.
How machine learning differs from statistics
Statistical modelling and machine learning both study observations in order to uncover the process that generated them. They part company on assumptions, vocabulary and method. A statistical approach starts from foundational assumptions and an explicit model of structure: the sample is assumed to be drawn from a specified probability distribution, and the analysis proceeds from there. Those restrictive assumptions, imposed before the data are examined, can simply be wrong.
Machine learning aims to pull knowledge out of very large quantities of data while imposing far fewer such restrictions. Its goal is to automate decision making by generalising from known examples until the underlying structure of the data emerges, with as little human help as possible. A compact way to remember the objective is that the algorithm finds a pattern and then applies that pattern.
Two practical consequences follow. First, machine learning copes better than a technique such as linear regression when there are very many variables, which is the problem of high dimensionality. Second, it copes better when the relationship is strongly non-linear. Algorithms of this kind are also unusually good at spotting change, because they can pick up the preconditions of a model breaking down or gauge the probability that a regime is about to switch.
The field divides into three broad classes of technique: supervised learning, unsupervised learning, and deep learning together with reinforcement learning. The rest of this lesson works through each of them, then through the individual algorithms, and finishes with a decision framework for choosing among them.
Supervised learning infers the pattern that links a set of inputs, the X variables, to a desired output, Y. Once inferred, that pattern maps any new input set into a predicted output. The defining requirement is a labeled dataset: one in which observed inputs are matched with the associated output. Running the algorithm over that dataset to extract the pattern is called training the algorithm. After training, the pattern can be applied to inputs that were never part of the training data.
Multiple regression is itself a case of supervised learning. Matched data on the X variables and Y are used to estimate parameters that characterise the relationship, and those parameters then predict Y for a fresh set of X values. The gap between predicted and actual Y measures how well the model performs out of sample, meaning on data it has not seen.
The vocabulary shift
The terminology differs from the regression terminology most candidates already know, and examiners exploit the difference.
| Symbol | Regression term | Machine learning term |
|---|---|---|
| Y | Dependent variable, output | Target |
| Xk | Independent variables, inputs | Features |
The labeled data used for training carry both the target outcomes and the paired feature inputs. The test data supply feature inputs only, and the predicted targets are then compared against the actual targets that were held back.
A concrete case makes the vocabulary stick. Suppose the task is to separate legitimate credit card transactions from fraudulent ones. The target is binary, set to 1 where the transaction is fraudulent and to 0 where it is not. The features are the characteristics of each transaction. The algorithm trains on those elements so that it predicts the likelihood of fraud more accurately on new transactions. Learning from experience means something measurable here: as the underlying database grows and supplies more input, the share of transactions classified correctly should climb. One workable choice of algorithm here is a logistic regression, which returns an estimated probability that a given transaction is fraudulent.
Regression problems and classification problems
Supervised learning splits into two problem types, and the split is decided by the nature of the target variable, not by the technique used.
- Regression applies when the target is continuous. Note the trap in the vocabulary: the task is called regression even when the technique employed is not a regression at all.
- Classification applies when the target is categorical or ordinal, an ordinal target being a ranked category.
Regression tasks predict continuous targets. Ordinary least squares is the familiar case, but non-linear supervised techniques also exist, and they earn their place on large datasets carrying many features, a good number of which may be correlated with one another. Predicting how a stock price will perform from a history of market returns is a regression task, and so is estimating the chance that a bond defaults from a history of corporate ratios.
Classification tasks sort observations into distinct categories. When the target is categorical, the model that relates the outcome to the features is called a classifier, and logistic regression is a classifier you have already met. Many classifiers are binary, as with the credit card fraud problem. Multi-category classification is common too: sorting firms into several credit rating categories is a standard example, and there the outcome variable is ordinal because the categories carry a distinct ranking from low to high creditworthiness. On a scale of measurement, an ordinal variable occupies the ground between a purely categorical one and a fully continuous one.
Unsupervised learning does not use labeled data. There are inputs, the X variables, and no target is supplied at all. Because no labeled training data are provided, the algorithm has to discover structure inside the data themselves. That makes it a natural first pass over an unfamiliar dataset: it can hand a human expert insight into data that are too large or too complicated to visualise directly.
Two problem types suit unsupervised learning particularly well.
- Dimension reduction cuts the number of features while retaining variation across observations, so that the information carried by that variation survives. It may be used to squeeze a wide dataset down to a representation that fits on a computer screen, and it is used heavily in quantitative investment and risk management wherever the task is to identify the most predictive factors behind asset price movements.
- Clustering sorts observations into groups such that members of the same group resemble each other more than they resemble members of other groups. The criteria that define the groups may or may not be specified in advance, the number of groups being one such criterion. Asset managers have used clustering to sort companies into data-driven groupings built from financial statement data or corporate characteristics, in place of conventional groupings by sector or country.
Deep learning and reinforcement learning
Within artificial intelligence more broadly, two further categories are distinguished. Deep learning applies sophisticated algorithms to hard problems: recognising what an image contains, recognising a face, recognising speech, and processing natural language. Deep learning rests on neural networks, also called artificial neural networks, which are highly flexible algorithms that have succeeded across a wide span of supervised and unsupervised tasks, the common thread being very large datasets, relationships that are not linear, and features that interact with one another. Reinforcement learning has a computer learn by interacting with itself, or with data that the same algorithm generated. Combining the two sets of principles has produced efficient algorithms for very hard problems in robotics, health care and finance.
A map of the algorithms
It helps to see the whole territory before walking through it. The table below organises the algorithms by whether they are supervised or unsupervised and by the type of variables involved. Linear and logistic regression are assumed known from earlier quantitative methods work; everything else in the table is covered in this lesson.
| Variables | Supervised (target variable present) | Unsupervised (no target variable) |
|---|---|---|
| Continuous | Regression: linear; penalized regression and LASSO; logistic; classification and regression tree (CART); random forest | Dimension reduction: principal components analysis (PCA). Clustering: k-means; hierarchical |
| Categorical | Classification: logistic; support vector machine (SVM); k-nearest neighbor (KNN); classification and regression tree (CART) | Dimension reduction: principal components analysis (PCA). Clustering: k-means; hierarchical |
| Continuous or categorical | Neural networks; deep learning; reinforcement learning | Neural networks; deep learning; reinforcement learning |
The four questions below test whether the definitions above have been absorbed rather than merely read.
Machine learning promises several advantages over a structured statistical approach when the task is to explore and analyse the structure of a very large dataset. The algorithms can uncover complex interactions between feature variables and the target, they process enormous quantities of data quickly, many of them capture non-linear relationships without effort, and some can recognise and predict structural change in the link between features and target. These advantages come mainly from the non-parametric and non-linear form of the models, which allows much more flexibility when a relationship is being inferred.
Flexibility is not free. The models produced can be so complex that the results resist interpretation, they may react to noise or to quirks of the particular dataset, and they may fit the training data too well. Where a model has been fitted to the training sample too closely, prediction on fresh material is typically poor. That failure carries the name overfitting: the fitted algorithm fails to generalize.
To generalize well is to keep explanatory power when predicting out of sample, on material never previously seen. What the overfitted model has done is take the noise, and the purely random fluctuation, present in its training sample and build it into the learned relationship. Neither survives into whatever data arrive next, so generalization suffers and predictive value drains away. Judging an algorithm therefore means looking at how badly it errs on fresh material, never at how neatly it fits the sample on which it was itself trained.
Underfitting, overfitting and robust fitting
Before going further, note how the dataset to which a model is applied is normally split. Three non-overlapping samples are carved out. The training sample fits the model. The validation sample validates and tunes it. The test sample establishes how well prediction holds up on material the model has not met. Of the three, the first two are labelled in-sample and the third out-of-sample.
A tailoring analogy makes the three fitting outcomes memorable. Overfitting is a custom suit cut so precisely that it fits exactly one person. Underfitting is a baggy suit that fits nobody. Robust fitting, the outcome wanted, is a suit that fits everyone of roughly similar dimensions.
- Underfitting means the model has not captured the relationships in the data at all. It shows up as errors on both sides of the boundary in a simple classification picture, and it is associated with high in-sample error.
- Overfitting means training has been pushed to a level of specificity at which quirks and spurious correlations in the sample begin to enter the model as though they were signal. Randomness is read as pattern. Memorisation has replaced learning, which gives the model flawless hindsight and no foresight whatever. Two things drive it: a lot of noise sitting in the data, and a model carrying more complexity than the problem needs.
- Good or robust fitting means the model fits the in-sample data well and also generalizes well out of sample, with both errors inside acceptable bounds.
Complexity has a specific meaning here. It counts the features, the terms and the branches a model carries, and it also asks whether the functional form is linear or not, the non-linear form being the more complex of the two. Overfitting risk climbs as complexity does.
Decomposing out-of-sample error
Calibrating fit means setting the two error rates side by side and watching how each responds to the data and to the algorithm. Write Ein for total error inside the sample: it is what the fitted relationship gets wrong when its predictions are set against the targets actually observed in the training set. Write Eout for total error outside it, measured on either the validation or the test material. Little or no error of the first kind sitting beside large error of the second kind is the signature of generalization failing.
The total out-of-sample error is decomposed into three sources.
- Bias error, meaning how closely the model manages to fit its training data. Where the assumptions behind an algorithm are mistaken the approximation is poor, and the result is high bias, underfitting, and error inside the sample.
- Variance error, meaning how far the results shift once new material arrives from the validation and test sets. An unstable model soaks up noise, which shows as high variance, overfitting, and error outside the sample.
- Base error, which is due to randomness in the data and cannot be removed by any model.
Learning curves and fitting curves
A learning curve plots the accuracy rate, equal to one minus the error rate, in the validation or test samples against the amount of data in the training sample. It is therefore a diagnostic for under- and overfitting expressed through bias and variance.
- Where the model is robust, accuracy outside the sample improves as the training set grows. The two error rates close on one another and settle at the error rate wanted, which is another way of saying they settle at the base error.
- Where bias error dominates and the model is underfitted, the rates do converge, but they converge underneath the accuracy that was wanted. Feeding in further training observations will not lift performance to the level required.
- Where variance error dominates and the model is overfitted, the two rates never come together at all.
Complexity moves the two errors in opposite directions. Add complexity and Ein falls on the training material, taking bias error down with it. Add the same complexity and Eout climbs on the test material, taking variance error up. As a rule a linear form is the one exposed to bias and underfitting, while a form that is not linear is the one exposed to variance and overfitting. Somewhere between the two lies an optimal level of complexity, the level at which the bias and variance curves cross and the pair of error rates is jointly at its lowest. Plotting Ein and Eout against complexity produces the fitting curve, which shows that trade-off at a glance.
Locating that point, the last moment before rising variance drags the total error rate upward again, is what managing overfitting risk actually consists of, and it decides whether generalization succeeds. Practitioners restate the whole problem as a trade-off between cost and complexity, cost here being the gap between the two error rates. Framed that way, the trade-off can be plotted, which makes both failure modes visible and gives a route to an optimised model.
Overfitting impairs generalization, and the potential for it is built into supervised learning because noise is always present. Two methods are commonly used to reduce it.
- Hold down complexity while the algorithm is being selected and trained, which means putting a number on an overfitting penalty and carrying it in the objective.
- Sample properly, through cross-validation, which measures error on validation material and so estimates error outside the sample directly rather than by inference.
Behind the first sits Occam razor, the principle that among competing explanations the simplest is usually right. Translated into supervised learning it means capping how many features enter, and imposing a cost on any algorithm that is more complex or more flexible than it needs to be, so that a parameter survives only where it lowers error outside the sample.
The second strategy descends from the principle of avoiding sampling bias, which can enter in many ways. The underlying difficulty is having a dataset large enough that both training and testing can be done on representative samples. A sample that is unrepresentative, or a training sample that has been shrunk too far, can hide the true patterns and so increase bias.
The three-way partition
The technique for reducing sampling bias is careful partitioning of the dataset into three groups.
- Training sample: labeled observations, with Y known, on which the model is fitted.
- Validation sample: the material against which structural choices are made, how much complexity to allow, which of several candidate solutions to prefer, and how to tune whichever one is chosen. Validation is what that tuning amounts to.
- Test sample: material set aside untouched, so that predictive or classifying power can be confirmed on something entirely unseen.
The point of all of it is a tested model that can be turned loose on fresh observations from the same domain. A common experimental design splits 70% for training, 15% for hyperparameter tuning and 15% for testing.
K-fold cross-validation
Holdout samples, meaning data samples not used to train the model, solve one problem and create another: they shrink the training set. Cross-validation techniques address that. Under k-fold cross-validation everything other than the test sample and any fresh material is shuffled at random and cut into k sub-samples of equal size. All but one of them train the model; the remaining one, the kth, validates it. Values of 5 or 10 for k are the usual choices.
Run that k times over. Each observation then appears in training k minus 1 times and in validation exactly once, which is what holds bias and variance down together. Averaging the k validation errors gives mean Eval, and that average serves as a reasonable estimate of Eout.
One limitation matters for finance in particular: k-fold cross-validation cannot be used with time-series data, because only the most recent data can reasonably serve for model validation. Shuffling a return series destroys the ordering that makes the prediction problem meaningful.
In short, a supervised model carries over to fresh material drawn from the same distribution only to the extent that error outside the sample has been kept in check, and the two levers available during construction are cutting complexity, otherwise known as regularization, and cross-validation.
Shreya Anand runs a high-dividend-yield fund for wealthy clients out of the Mumbai head office of an investment firm, and picked up some data science at university. Her aim is to sort the constituents of the NIFTY 200 Index, which covers large and mid-capitalisation names quoted on the National Stock Exchange of India, into two buckets: those raising the dividend and those not raising it. For that she gathers 1,000 observations, one per company, each carrying 25 features of a fundamental and technical kind alongside the label, and splits them for training, validation and testing.
After training, Anand finds that the model classifies the training sample well but performs poorly on new data. Colleagues offer conflicting accounts of what good generalization means:
| Statement | Claim |
|---|---|
| 1 | Explanatory power survives when the model predicts on fresh material, meaning outside the sample. |
| 2 | Explanatory power is weak once the model has been trained on material inside the sample. |
| 3 | Explanatory power disappears when the model predicts on fresh material. |
Supervised models are trained on labeled data, and the nature of the target decides the type: regression for a continuous target, classification for a categorical or ordinal one. This section and the three that follow work through the supervised algorithms in the order regression first, then classification, then the ensemble methods that combine them. Assume throughout a set of observations on some target Y together with n features taking real values, written X1 through Xn, and a task of tying the vector of those features to Y at each observation.
Penalized regression is a computationally efficient technique for prediction problems. Two things recommend it in practice: it shrinks a long feature list into something manageable, and it predicts well on big datasets, most usefully those whose features move together, which is exactly where classical linear regression falls apart.
The motivation is the overfitting problem. In a large dataset there may be very many features that could in principle help explain Y. Fit a model to training data and it may reflect the characteristics of that specific sample so closely that it fails on new data. Features can enter that carry nothing except noise, or randomness peculiar to that one training set, and neither will be there in future. Penalized regression is therefore best described as a technique for avoiding overfitting. Since prediction is judged outside the sample, a parsimonious specification, one in which no variable is along for the ride, tends to do well for the simple reason that it has less room to overfit.
From ordinary least squares to a penalty
Standardize the data first, so that every feature carries a mean of zero and unit variance. That step is what makes the size of one coefficient comparable with the size of another. In ordinary least squares the coefficients are chosen to minimise the sum of the squared residuals, that is, the sum of squared differences between the actual values and the predicted values.
A penalized regression bolts a constraint on to that. Coefficients now minimise the squared residuals together with a penalty that rises as more features are admitted. Admitting a feature therefore has a price, and the improvement in fit has to be worth more than the price. Only features that genuinely help explain Y clear that hurdle.
One popular form of the penalty defines LASSO, whose name expands to least absolute shrinkage and selection operator. It is written as follows, with lambda strictly positive.
Minimising then applies to two things at once: the squared residuals, and the absolute sizes of the estimated coefficients.
Retention follows one test: does the fall in squared residuals exceed the rise in the penalty? Every penalized regression rests on a trade-off of that shape. What is distinctive about LASSO is that it pushes the weakest coefficients all the way to zero, dropping those features out of the specification, so a form of feature selection happens on its own.
Lambda as a hyperparameter
Lambda is a hyperparameter. That word denotes any parameter the researcher fixes in advance, before learning starts, rather than one the algorithm learns. Its job is to balance fit against parsimony. Fixing it in practice means running the model repeatedly at different settings and watching performance on the validation set, and that is precisely why a separate test set cannot be dispensed with: without one, the hyperparameters end up overfitted to the validation material.
Two mechanical consequences follow. Set lambda to zero and the penalty disappears, leaving an ordinary least squares regression exactly. And the penalty operates only while the model is being built on training material. After that it has served its purpose and drops away, with the finished model assessed on the squared residuals it produces against the test dataset.
Regularization in practice
Regularization is the general name for methods that cut statistical variability out of estimation problems carrying many dimensions. Here it works by pulling coefficient estimates toward zero, which keeps models simple and keeps overfitting risk down with them. Now that fast computation is cheap, analysts reach for LASSO and its relatives routinely, to strip away the less pertinent features and leave a parsimonious specification behind.
A documented case is the prediction of default probability within industrial sectors. Scores of candidate features, a great many of them collinear, were cut down to a set of under 10 variables. The reduction matters enormously in that setting because defaults themselves are scarce, with only about 100 observations available.
The same methods carry over to models that are not linear. Asset management has struggled for decades to obtain stable covariance matrixes, and therefore stable weights, when optimising a large portfolio on a mean–variance basis. Returns are strongly multi-collinear, so the estimated matrix reacts sharply to noise and to outliers, and the weights that come out of the optimisation are unstable in consequence. Regularization has been applied to that problem, and once again the parsimony delivered by a penalized method leaves less room for overfitting.
Support vector machine, or SVM, ranks among the most widely used algorithms of all. It is supervised, it is powerful, and it serves three purposes: classification, regression and the detection of outliers. The name sounds forbidding; the idea underneath is simple and is best carried by a picture.
Start with a simple dataset containing two features, an x coordinate and a y coordinate, with every observation labeled as belonging to one of two groups. Suppose those groups fall into two visibly separate regions, which might represent stocks with positive and with negative returns in a given year. An infinite number of straight lines could separate the two regions. Such data are called linearly separable, and every one of those candidate lines qualifies as a linear classifier: a binary classifier whose verdict comes from a linear combination of the features attached to each point.
Two features give a classifier that is a straight line. Attach n features instead and each observation sits in a space of n dimensions, with separability meaning that some linear boundary through that space carves the observations into two regions. Whatever its dimension, that boundary is called an n-dimensional hyperplane. At n equal to 1 the word for it is a line and at n equal to 2 it is a plane.
The maximum margin idea
Among all the hyperplanes that would work, SVM picks the one that splits the observations optimally into two sets. The intuition is that a correct prediction is most likely when the dividing surface sits as far as possible from every observation. So the algorithm separates by the maximum margin, a margin being the strip dividing the two groups, and the line down the centre of that strip is the discriminant boundary, or the boundary for short.
What fixes the width of the strip is the handful of observations nearest the boundary on each side, and those observations are the support vectors. Pile in further training data well away from them and the boundary does not budge. Introduce points near the hyperplane and it may well move, because the set of support vectors can change.
When the data are not separable
Real datasets are usually not separable in this clean way. Points end up on the wrong side of the boundary and are misclassified. The adaptation that copes with this is soft margin classification, under which every misclassified training point attracts a penalty inside the objective function. The boundary chosen is then the one balancing a wider strip against a smaller total penalty.
A second route exists. Rather than softening the margin, allow the separating surface itself to bend, giving a non-linear SVM. Fewer training points end up misclassified, but the algorithm is more complex and, for that reason, readier to overfit.
Investment applications
The natural home for SVM is a dataset of modest size but awkward shape, complex and carrying many dimensions, of which corporate financial statements and bankruptcy databases are the standard cases. Predicting corporate failure matters to investors deciding what to avoid or what to sell short, and a long list of fundamental and technical variables can be reduced to a binary verdict, bankruptcy likely or bankruptcy unlikely. Its virtue on such material is that many features can be carried without the result becoming hostage to outliers or to features that move together. The same algorithm sorts documents, news articles, company announcements and annual reports, into categories that matter to investors, sentiment being the obvious one.
K-nearest neighbor, or KNN, is a supervised technique whose usual job is classification, though it occasionally handles regression. Its logic is to place a new observation by measuring how near it stands to the observations already held.
Return to the scatter of two labeled groups used for SVM and drop in one new point that has to be assigned. With k set to 1, the new point simply inherits the label of whichever single point lies closest. With k set to 5, the five closest points are consulted instead. Suppose those five split three to two. The rule is majority among the k consulted, so the new point takes the label held by the three. Notice that k equal to 1 and k equal to 5 can return the same verdict even though the neighbors consulted were entirely different.
A corporate bond illustration
Take a database of rated corporate bonds that also records detailed characteristics for each one. Some of those characteristics belong to the issuer, its asset size, its industry, its leverage and cash flow ratios. Others belong to the issue, its tenor, whether the coupon floats or is fixed, and any options embedded in it. Now an unrated bond comes to market. Since issuers and issues that look alike ought to attract much the same rating, KNN can infer the implied rating for the new one by measuring how close it stands to what is already in the database.
Strengths, and the problem of defining similarity
Simplicity is the appeal, and it is not a weakness. The method is non-parametric, imposing nothing whatever about how the data are distributed, and it extends to problems with more than two classes without any modification.
What is hard is pinning down the word near. Feature choice matters, but the deeper decision is which distance metric will stand in for similarity, since a metric that suits the problem badly yields a model that performs badly. The judgement becomes still more subjective once the data are ordinal or categorical. Someone comparing how various equities have performed in the market might, for example, treat the correlation between their return histories as the similarity measure.
Defining similarity therefore leans on knowledge of the data and on a clear view of what the analysis is for commercially. Irrelevant or correlated features distort the answer, so features may have to be selected by hand. Stripping out the low-value material leaves what is pertinent, and done well it produces a distance measure that represents the problem more faithfully. Broadly, the fewer features carried, the better this algorithm performs.
Choosing k
The number k is the hyperparameter here, and it has to be chosen knowing that different values can point to different conclusions. Should the unrated bond be compared against the 3 closest bonds, the 15 closest, or the 50 closest? An even value invites ties, which leave no clear verdict at all. Choose too small a value and the error rate rises while local outliers start to dominate. Choose too large a value and the idea of a nearest neighbor is diluted, since far too many outcomes are being averaged. A number of techniques exist for settling on an optimal value, and they take account of how many categories there are and how those categories carve up the feature space.
In investment work the algorithm turns up in predicting bankruptcy, predicting stock prices, assigning credit ratings to corporate bonds, and building customised equity and bond indexes. Knowing which bonds resemble one another and which do not is precisely the input a custom, diversified bond index requires.
Rachel Lee manages fixed income at Zeta Investment Management Company, which runs two bond portfolios: one of investment-grade paper for small, conservative institutions, and one of high-yield paper for wealthy individuals chasing yield. Either portfolio may take unrated bonds, provided the characteristics of the bond line up closely with the average holding in that portfolio.
An upcoming issue comes up in conversation with senior credit analyst Marc Watson: a straight bond, 10 years, fixed coupon, from Biotron Corporation, and unrated. Watson has looked at profitability, at cash flow, and at leverage and coverage, and puts the issue right on the line dividing the bottom of investment grade (Baa3/BBB−) from the top of the non-investment-grade range (Ba1/BB+). Lee turns to machine learning to pin the implied rating down. The two algorithms she runs both point clearly to the higher non-investment-grade category, and Watson says their agreement gives him confidence in the answer.
K-nearest neighbor. KNN suits the problem too, since it places a new point by measuring how close it stands to points already held. Trained on the same material, the rule for Biotron is whichever rating commands a majority among its k closest neighbors. Recall that k is a hyperparameter, so Lee has to fix it in advance.
Classification and regression tree, or CART, is supervised and handles both kinds of target. Aim it at a categorical target and it returns a classification tree; aim it at a continuous one and it returns a regression tree. Binary classification and regression are its usual employments.
Work through a simplified model that sorts companies according to how likely they are to raise the dividend. What is needed is a binary tree, built out of three ingredients: one initial root node, some decision nodes, and the terminal nodes at which paths end. Every node other than a terminal one names one feature, call it f, together with the cutoff value c at which that feature is split.
Let the feature at the root be investment opportunities growth, written IOG and designated X1, cut at 10%. Any new observation enters there. Below the root the observations are carved at each decision node into progressively smaller subgroups, and the process ends at terminal nodes, which are the only nodes carrying a predicted label. Here the two labels available are a dividend increase and no dividend increase.
Trace a single route. IOG above 10% answers Yes, sending the observation to a node splitting on free cash flow growth, written FCFG and designated X2, cut at 20%. FCFG at or under that cutoff answers No, and the prediction returned is no dividend increase, at a terminal node. FCFG above the cutoff answers Yes, and the prediction returned is a dividend increase, at a different terminal node.
One structural feature deserves emphasis: a single feature may show up more than once in the same tree, paired with different features, and certain features earn relevance only after other conditions are satisfied. Go back to the root and take the other branch. Where IOG sits at or below 10% while FCFG exceeds 10%, IOG returns as a decision node further down, this time cut at 5% rather than 10%.
How the algorithm picks features and cutoffs
Training comes first, on labeled material. In the hypothetical case that material is 20 companies, half of which raised the dividend and half of which did not. The feature space here is simply the plane traced out by X1 and X2, and every split, at the root and at each decision node alike, cuts that plane into two rectangles, one holding values above the relevant cutoff and one holding values at or below it.
How does the algorithm decide what to split on? At every node it searches for the feature, and the cutoff on that feature, that pull the labeled data furthest apart, the objective being minimum classification error under some criterion, mean-squared error being one. Each split leaves smaller partitions, and within each of those the error is lower than it was before. Splitting stops at whatever level a further bifurcation would barely reduce classification error. The node is then terminal, and it takes the label of whichever category is in the majority inside it.
So a classification tree predicts, at each terminal node, whichever category holds most of the observations sitting in that partition. Suppose the rectangle at the top right, where IOG exceeds 10% and FCFG exceeds 20%, holds five members of the dividend increase group, more observations than any other partition. A company with those characteristics would be predicted to raise the dividend. Change the second condition so FCFG falls at or below 20% and the company lands in the rectangle at the lower right, which holds three members of the no increase group against two of the increase group, so the prediction flips. Where the objective is regression rather than classification, the terminal node returns the mean of the labeled values instead of a category.
Regularization and pruning
Nothing whatever is assumed about the shape of the training data, which means an unconstrained tree can go on splitting until it reproduces that data exactly. That is overfitting at its purest. Constraints are therefore imposed as regularization parameters, and three are common: a ceiling on how deep the tree may go, a floor on how many observations a node must contain, and a ceiling on how many decision nodes may exist. Growth halts as soon as whichever criterion applies is hit. Take the rectangle at the upper left, reached by IOG at or below 10%, then FCFG above 10%, then IOG at or below 5%, and holding three members of the increase group. A minimum population set at 3 would make that a terminal node.
The other route is to regularize after the fact by pruning: growing the tree first and then cutting back whichever sections contribute little to classifying anything.
Why the iterative structure matters
Because the structure is built one split at a time, dependencies between features emerge that other specifications simply cannot express. Take a stylized tree separating an attractive equity holding from a value trap, the trap being a holding that looks cheap and is nonetheless likely to lose money. Profitability turns out to be the decisive feature, but it only becomes decisive once the stock is already cheap. The hypothetical route is a price to earnings ratio under 15, then leverage that is high with debt above 50% of total capital, then sales expanding at more than 15%. Reverse that statement and the point is sharper: where the stock is not cheap, or leverage is not high, or sales are not expanding, profitability tells you nothing at all in this context. A multiple linear regression is at its weakest on relationships shaped like that one.
Part of the appeal of the method is that the tree explains itself: the prediction is a path a human can read. Set that against the algorithms treated as black boxes, whose reasoning cannot easily be followed and therefore cannot easily be trusted. Trees make a strong foundation for expert systems used in decision making, and they extract dependable rules even where the data are noisy and the interactions among many features are involved. Investment uses include sharpening the search for fraud in financial statements, imposing a consistent process on equity and fixed-income selection, and making an investment strategy easier to explain to a client.
Every algorithm so far has rested a prediction on one model. There is an alternative: poll a whole group of them. Each individual model errs at some rate and predicts noisily. Average enough predictions drawn from enough models and the noise ought to wash out, leaving an average that sits closer to the truth. That pooling of output across a collection of models is ensemble learning, and the practice of combining several learning algorithms goes by the name ensemble method. Accuracy and stability both improve relative to the best individual model, which is why these methods so often win the well-known competitions in the field.
Ensemble learning splits into two categories:
- Aggregation of heterogeneous learners, meaning different types of algorithm combined through a voting classifier.
- Aggregation of homogeneous learners, meaning the same algorithm applied to different training data, generated for example by bootstrap aggregating.
Voting classifiers
Picture a machine learning project that has run for a while, in which several algorithms have been trained and their results compared, say a support vector machine, a k-nearest neighbor routine and a tree. A majority-vote classifier hands each new observation whichever predicted label collected the most votes. If two of the three call a stock an outperformer and the third calls it an underperformer, outperformer is the answer returned.
Aggregate accuracy improves as more models join the panel, though not without limit. Past some optimal count, adding models is expected to make matters worse through overfitting. What makes the panel work is diversity: different algorithms, different modelling techniques, different hypotheses. The assumption underneath, in its extreme form, is that individual predictions are independent of one another, in which case the law of large numbers does the rest.
Bootstrap aggregating
Bootstrap aggregating, shortened to bagging, holds the algorithm fixed and varies the data instead. Out of the one training set it manufactures n further training sets, called bags, each drawn at random with replacement from the original. Training the same algorithm on those n independent sets yields n models. Each new observation is then run through all of them, and the n answers are pooled, by majority vote where the task is classification and by averaging where it is regression. What bagging buys is steadier predictions and less exposure to overfitting.
Random forest
A random forest classifier is nothing more than a great many decision trees trained through bagging. Run a tree algorithm across each of the n bags and the result is the crowd of differing trees that constitutes the forest.
Diversity can be pushed further still by withholding features at random during training. Where an observation carries n features, a subset of m of them, with m below n, is drawn at random and only those are available to the tree when it looks for a split at a given decision node. That subset size, the count of trees, the floor on how many observations a node or leaf may hold, and the ceiling on depth are all hyperparameters, and all can be tuned to lift accuracy. Once trained, every tree in the forest votes on each new observation and the majority carries it, which is the algorithmic counterpart of the wisdom of crowds.
Building a model this way lowers variance and shields the result from overfitting the training material. Signal also improves relative to noise, since the errors made by any one tree tend to be cancelled by the others. The cost is interpretability. A single tree can be read; a forest of them cannot, which places the method firmly among the black boxes.
A published illustration plots defaults among small and medium-sized businesses against two characteristics, profitability and leverage, and sets the observed pattern beside what two models predict. The linear specification cannot reproduce the shape of the relationship at all, because that shape is not linear. The forest, fed identical data, tracks the observed distribution closely.
A fraud detection application
The forest is the clearest illustration of what ensembles achieve: pooling output across many models yields classifications whose signal stands out from the noise better than any single classifier manages. Take a fraud detection exercise built on an openly available card transaction dataset, whose features were anonymized but might still explain which transactions were fraudulent. The awkwardness is rarity. Out of 284,807 transactions only 492 were fraudulent, which is 0.17%, so this is a needle in a haystack.
Pairing a forest with oversampling, which deliberately inflates how large a share of the training set the fraudulent cases occupy, copes with that imbalance remarkably well. Precision reaches 89%: of all transactions flagged as fraud, that share genuinely was fraud. Recall reaches 82%: of all the fraud actually present, that share was caught.
For all its relative simplicity the method is powerful and turns up widely. Factor-based strategies use it in asset allocation and in choosing individual investments. It has also been used to predict whether an initial public offering will go well, judged by how far the book was oversubscribed or by where the first trading day closed relative to the offer price, given what is known about the offering and about the issuer.
Laurie Kim runs money at Hilux LLC, a firm investing in high-yield bonds. Several months of recession have driven credit spreads wide and prices down hard. Kim reads that as an opportunity rather than a warning, expecting to make money as spreads come back in and prices recover ahead of the economy. Her work identifies the B/B2 to CCC/Caa2 band as the most attractive, but a weak economy has lifted default risk, so which bonds she buys and which she leaves alone matters greatly.
She hands the analytics team a history covering several thousand high-yield issuers and issues, each labeled according to whether it defaulted, and each described by 19 fundamental factors and 5 technical ones. The request is for a model, using every factor supplied, that sorts accurately into the two outcomes. Preliminary exploration of the data suggests the feature set behaves in a decidedly non-linear way.
An analyst at a fund of funds has to draw up a list of attractive exchange-traded funds and mutual funds. She turns to machine learning for two things: separating the strongest performers from the weakest, and working out which characteristics do the separating. If a model can be trained to sort past winners from past losers reliably, it can then be pointed at the future. Not knowing in advance which classifier will serve best, she runs four of them, a tree, a support vector machine, a nearest-neighbor routine and a forest, and compares the results side by side.
The data
What the algorithms learn from is a mixture: what type of fund it is and how big, how its assets are split by class, its valuation multiples, and how its holdings are spread across sectors. Because the classifier is cross-sectional, the sector split and the size figure as at 15 February 2019 are taken to stand for the most recent month of reported fund return.
| Item | Detail |
|---|---|
| Datasets | Two, held apart: one covering mutual funds, one covering exchange-traded funds |
| Number of observations | 6,085 mutual funds and 1,594 exchange-traded funds |
| Features | Up to 21 |
| General features (six) | Fund type (blend, growth or value; exchange-traded fund dataset only); net assets in US dollars; investment category size (small, medium or large capitalisation); ratio of cash to total assets (mutual fund dataset only); ratio of stocks to total assets; ratio of bonds to total assets |
| Fundamentals (four) | Share price measured against earnings per share, against book value per share, against sales per share, and against cash flow per share |
| Sector weights (eleven, in percentages) | Technology; industrials; energy; utilities; healthcare; real estate; basic materials; financial services; communication services; consumer cyclical; consumer defensive |
| Data sources | Kaggle and Yahoo Finance, as at 15 February 2019 |
Labelling is relative, and the reference distribution is one-month returns across every fund of the same type. Where a fund returns at least one standard deviation above that mean, it is labeled 1 and counted a winner. Where it returns at least one standard deviation below, it is labeled −1 and counted a loser. Everything in between takes a 0. The arithmetic guarantees that most funds end up with a 0, meaning average.
Once records with missing values are dropped, 1,594 funds remain on the exchange-traded side and 6,085 on the mutual fund side. Stacking the two gives a matrix of 7,679 rows by 22 columns, one row per fund, and one column for each of the 21 features plus one more for the label. The exercise looks for the distinguishing characteristics as well as the winners and losers themselves, subject to an important caveat: nothing here establishes that any characteristic causes anything.
Method
Each dataset gets its own three-class classifier, and each classifier is built four times over, once with a tree, once with a support vector machine, once with nearest neighbors and once with a forest. Only the last of those is an ensemble, and it rests on bagging. A conventional design would set aside 70% for training, 15% for hyperparameter tuning and 15% for testing. Here the hyperparameters are left at their defaults and no fine tuning is attempted, so the middle slice is unnecessary and nothing is withheld for validation. What remains is a random 70% for training with the other 30% reserved for testing. Fairness demands that the split be shared: every algorithm sees the same training rows and is judged on the same testing rows.
| Algorithm | Hyperparameter | Value used |
|---|---|---|
| Random forest | Trees in the forest | 100 |
| Random forest | Depth limit per tree | 20 levels |
| CART | Depth limit | 5 levels |
| KNN | Neighbors consulted | 4 |
| SVM | Cost parameter | 1.0 |
Theory, academic research, practice and experimentation all support these settings as delivering a satisfactory trade-off between bias and variance. The cost parameter attaches a penalty to the margin around the decision boundary, so a high value squeezes the margin thin and a low value lets it widen. None of these values is claimed to be optimal on every dataset.
Evaluation metrics
Results are evaluated on the test portion of each dataset using metrics built on Type I and Type II classification errors, a Type I error being a false positive and a Type II error a false negative. Correct classifications are true positives and true negatives.
- Accuracy counts how many classes were predicted correctly as a percentage of all predictions, so a high figure means few errors of either type.
- F1 score weights precision against recall. Precision asks what share of the cases flagged as positive really were positive; recall asks what share of the genuinely positive cases were flagged.
Where the classes are unevenly distributed, a condition known as class imbalance, the second metric is the more appropriate of the two. That is the situation here, since the great majority of funds carry the neutral label.
Results
| Classifier | Accuracy | F1 score |
|---|---|---|
| Random forest | 0.812 | 0.770 |
| CART | 0.770 | 0.769 |
| SVM | 0.774 | 0.693 |
| KNN | 0.724 | 0.683 |
On raw accuracy the forest leads at 0.812. Allow for class imbalance by switching to the F1 measure and its 0.770 is barely distinguishable from the 0.769 returned by the single tree. That an ensemble should at least match the single model it is built from is the general expectation, since pooled forecasts carry over to fresh data better. Note what these comparisons do and do not establish. They rank the four methods against each other; they say nothing about whether any of them is good in absolute terms. For that, a score close to 1 marks an excellent model while a score near one third marks a worthless one, one third being what three evenly distributed labels would produce by chance. Since the classes are rarely evenly distributed, that reference figure usually needs adjusting.
| Classifier | Accuracy | F1 score |
|---|---|---|
| Random forest | 0.969 | 0.969 |
| CART | 0.959 | 0.959 |
| SVM | 0.859 | 0.847 |
| KNN | 0.856 | 0.855 |
On the mutual fund side the forest wins on both measures against every rival. Taking the two datasets together, the support vector machine and the nearest-neighbor routine score similarly to each other and both are beaten by the tree and the forest, most clearly on the larger of the two datasets. That the two datasets should produce different results is unsurprising, since one holds roughly four times as many funds as the other and more observations generally mean a better fitted model. Exactly why the tree-based methods win here is a longer story than this case can accommodate, but resilience to noise is a well-documented property of forests relative to most alternatives.
Which features mattered
Ranking the features inside the forest is done through information gain, a measure of how much a given feature tells you about the response. It can be read as a non-linear analogue of correlation between the target and a feature.
- The two valuation ratios based on sales and on earnings carry the most information among the fundamentals in both datasets, scoring roughly 0.08 to 0.09 and 0.06 to 0.07.
- How much of a fund sits in stocks, as a share of total assets, is another leading feature, at 0.06.
- Among sector weights the leaders differ by dataset: industrials, health care and communication services on the exchange-traded side, against real estate, consumer defensive and energy on the mutual fund side.
- The size category of the fund dominates everything else on the mutual fund side at approximately 0.20, yet counts for little on the exchange-traded side at approximately 0.04.
- Net assets inverts that pattern: reasonably informative on the exchange-traded side at 0.065, and dead last on the mutual fund side at 0.01.
Four conclusions follow. She trusts the mutual fund work more than the exchange-traded fund work, purely because the sample behind it is so much larger. She is satisfied that the uneven class distribution has not misled her, since she judged on the F1 measure throughout. The ensemble is the best performer on both datasets. And although valuation ratios, asset class shares and sector composition all carry weight in both models, it is size, whether measured as net assets or as size category, that does much of the discriminating.
The same analyst now builds a tree to predict, and to explain, which of the three outcomes a new exchange-traded fund will produce: winner at +1, average at 0, or loser at −1. The fund in question trades on a price to sales ratio of 2.29, a price to earnings ratio of 7.20, a price to book ratio of 1.41 and a price to cash flow ratio of 2.65. Behind the tree are 1,067 funds, and only valuation ratios are used as features because those were judged the most informative for this classification. Every node reports three things: the criterion on which it splits, how many funds reach it, and a vector counting winners, average performers and losers there. Taking the left branch means the criterion held true, and taking the right branch means it did not.
| Level | Split criterion | Fund value | Result |
|---|---|---|---|
| Initial node | Price to sales at or below 7.93 | 2.29 | True |
| Second level | Price to earnings at or below 12.08 | 7.20 | True |
| Third level | Price to sales at or below 1.32 | 2.29 | False |
| Fourth level | Price to book at or below 1.275 | 1.41 | False |
| Fifth level | Terminal node reached: samples 21, value [13, 4, 4] | Winner |
Probability of winner: 13 ÷ 21 = 0.619, or 62%.
Probability of average performer: 4 ÷ 21 = 0.190, or 19%.
Probability of loser: 4 ÷ 21 = 0.190, or 19%.
The two non-predicted outcomes carry equal probability because the counts are equal.
Depth. The tree was truncated at a maximum depth of five levels. That makes it easy to visualise, but a realistic decision path is likely to be more nuanced and would need greater depth.
Features. Only some of the important variables were used, again for ease of visualisation. A tree using fund asset class ratios, sector composition and, above all, net assets would be expected to produce a more accurate model measured by F1 score.
Sample size at the node. Only 21 of the 1,067 funds reach the winner terminal node, and only 13 of those are clear winners, which is too few to support a statistically significant conclusion. Beyond deepening the tree and widening the feature set, she could switch to a forest, since an ensemble carries over to fresh data more reliably than one tree acting alone.
An adjacent application: machine learning and ESG data
The same toolkit is now being aimed at environmental, social and governance material, which behaves much like alternative data: loosely defined, complicated, unstructured, and demanding a great deal of diligence before anyone should act on it. The governance component is the most tractable, because what a board does can be watched, counted and set against what other boards do in other markets. The environmental and social components are softer, less dependable and harder to compare.
Sustainability reporting by companies is frequently patchy, gathered inconsistently and full of gaps, and something is often lost when a vendor rolls raw inputs up into a single score. Neither the scoring nor the underlying data line up well from one company or one vendor to the next, so leaning on a summary number is risky. The response is to clean and reshape the raw material first, using ordinary data-science steps such as cleansing and wrangling, until a structured dataset exists. Only then do techniques such as natural language processing go to work, and they can be pointed at text-based material, at video or at audio. Underneath that processing sit the same supervised algorithms met earlier: logistic regression, support vector machines, trees, forests and neural networks.
A concrete use is scanning earnings calls for particular vocabulary. If mentions of human capital rise, or of employee health and safety, or of flexible working, the shift may indicate that the social pillar has moved up the agenda, which could lift the score assigned to that company. None of this operates on its own. Scoring frameworks are typically run by cross-functional teams, in which data scientists sit alongside economists, fundamental analysts and portfolio managers. An analyst covering an industry contributes without knowing how any algorithm works internally, in three ways: pointing to which raw data are worth having, helping the technical staff get that data into a suitable model, and reading what the model produces for what it implies about an investment. There is also a filtering role, since only some factors matter for any given company. Environmental factors bear heavily on a miner or a utility and lightly on a maker of clothes, while social factors bear heavily on global clothing manufacture and lightly on mining and utilities.
The unsupervised branch works without labels and therefore without any target, which leaves the algorithm to find whatever pattern lives inside the inputs. Two families of technique matter for the examination: shrinking the number of dimensions, done through principal components analysis, and grouping observations, done through k-means or through hierarchical methods. This section covers the first family and the next section covers the second.
Why shrink anything? Because a wide dataset is hard to picture and hard to model. Plots become impossible to read and fitted models start reflecting random influences peculiar to the one sample in hand, which is what the word noisy means in this context. Shrinking the dimensions means describing the same dataset with fewer features, where the features discarded were largely duplicating what the survivors already say.
Eigenvectors, eigenvalues and composite variables
Principal components analysis, or PCA, has been in the statistical toolkit for a very long time. It takes features that move closely together and condenses them into a handful of composite variables that do not move together at all. A composite variable is simply one built out of two or more variables whose statistical relationship with each other is strong. Loosely described, the procedure transforms the covariance matrix of the features, and it turns on two objects.
- An eigenvector defines one of the new composite variables. Each is a linear combination of the original features, each is uncorrelated with the others, and being a vector, each also points in a direction.
- An eigenvalue comes attached to every eigenvector, and it reports what share of the total variance present at the outset that eigenvector accounts for.
Ranking the eigenvectors by their eigenvalues, from largest downward, ranks them by how much of the original variance each one explains. Whichever eigenvector explains the most becomes the first principal component. Whatever variance the first one leaves behind is then attacked by the second, which explains the largest share of the remainder, and so on down through the third, the fourth and the rest. Since each one blends the whole feature set, a short list of them usually suffices to account for most of the variance sitting in the original covariance matrix.
Projection error and spread
Picture three features, so the data can be drawn in three dimensions with each observation carrying a reading on each axis. Standardize first, so every series has mean zero and standard deviation one. Now suppose the procedure has been run and the leading two components are known.
Drop a perpendicular from any observation onto the first component. The length of that perpendicular is the projection error attaching to that observation. Measure instead along the direction of the component itself, and the distances between observations give the spread of the data in that direction. The line selected as the first component is the one that makes the total of all the projection errors as small as it can be while making the spread as large as it can be. Those two criteria together are what guarantee that no other single direction captures more of the variance. The remainder is then best handled by the second component, which is set at right angles to the first and is therefore uncorrelated with it. Two numbers per observation now stand in for three, and that substitution is the dimension reduction.
Deciding how many components to keep
Keeping few components makes a complicated dataset manageable; keeping few also throws information away. Something has to arbitrate. That job falls to the scree plot, which charts what share of variance each component accounts for. The practical rule is to retain the smallest number of components that between them reach whatever share of the original variance the analyst has decided is enough, and in practice that target is commonly set somewhere between 85% and 95%.
An illustration uses two hypothetical equity indexes across the last 10-year period. One, a Diversified Large Cap 500, stands for a broad index of large companies spanning every economic sector. The other, a Very Large Cap 30, stands for a narrow index holding only the 30 biggest quoted companies. The raw material is index prices plus more than 2,000 features of a fundamental and technical kind. With that many candidates, overlap between features and combinations of features is inevitable, and multi-collinearity is the standard consequence. The procedure is applied to gather the information and the variance up into a much smaller set.
| Index | PC1 | PC2 | PC3 | First three combined |
|---|---|---|---|---|
| Diversified Large Cap 500 | 43% | 26% | 21% | About 90% |
| Very Large Cap 30 | 55% | 20% | 11% | About 86% |
Twenty components were produced in all, and the researchers settle on three as sufficient for each index. Their charts flatten out after roughly the fifth component, meaning what remains adds very little to the account of how the variance is structured, so those later components can be dropped at negligible cost.
The contrast between the two rows repays attention. Concentrate an index into 30 very large names and a single dominant factor explains 55% of the variance on its own. Broaden it and that leading factor accounts for only 43%, so more components are needed before a comparable share is reached. That difference is diversification expressed in statistical language.
Clustering arranges observations into groups whose members resemble one another. Every cluster is a subset of the dataset within which the members count as similar. What makes a clustering good is two properties working together. Members of one cluster should sit close to each other, a property named cohesion, and members of different clusters should sit as far apart as possible, a property named separation.
Any investment question in which resemblance is the point is a candidate. Turn these algorithms on companies and they may expose likenesses and differences that the conventional industry and sector labels never captured. Turn them on a portfolio and they have been used to improve how risk is spread.
Defining distance
Human judgement enters at the start, because someone must decide what resemblance means. Treat each company as an observation carrying many features: line items from the financial statements such as total revenue or profit attributable to shareholders, any number of ratios, or whatever else the model is to be given. From those features comes a measure of distance between any two companies. Short distance means the pair resembles each other closely; long distance means it does not.
The default measure is Euclidian distance, meaning the length of the straight line joining two points. A relative of it, useful when the object is diversification, is correlation, which amounts to averaging the Euclidian distance across a standardized set of points. Something like a dozen distance measures see regular use. Which one fits depends on what kind of data are involved, numerical or otherwise, and on the commercial question being asked. Fix the measure and the grouping can begin.
K-means clustering
K-means divides observations, over and over, into k groups that do not overlap. That number k is a hyperparameter of the model. Every group has a centroid at its centre, and every observation belongs to whichever centroid lies nearest to it. Nothing connects one finished cluster to another; they simply exist side by side.
The procedure iterates. Set k at 3 and describe each observation by two features, which might be two numerical readings on the quality of company management, the aim being to sort firms into three groups.
- Positions for three initial centroids are fixed at random.
- Each observation is examined and, under the chosen distance measure, attached to whichever centroid is nearest. Those attachments constitute the first three clusters.
- Fresh centroids are computed from the members of each cluster, each new centroid being the average of the observations assigned to it.
- Observations are attached again, this time to the fresh centroids, so the membership of each cluster changes.
- Centroids are recomputed once more from the revised memberships.
- Observations are attached again to those revised centroids, completing a second full iteration.
Iteration stops when a full pass moves nobody, at which point recomputing the centroids would change nothing either. The algorithm has converged and the final three clusters, with their members, stand revealed. Convergence means that distance within clusters is as small as it can be made, so cohesion is maximised, and distance between clusters is as large as it can be made, so separation is maximised, both under the constraint that exactly three groups were permitted.
What k-means does well and badly
Speed is the strength. Datasets running to hundreds of millions of observations present no difficulty. The weakness is that where the initial centroids landed can influence where the observations finally end up. The usual remedy is to run the whole procedure repeatedly from different random starts and keep whichever grouping is most useful commercially.
A second weakness is that k has to be settled before anything can run, which presumes some feeling for how many groups the problem and the data can support. An alternative is to sweep across a range of values and look for the one that pushes within-cluster distance lowest, maximising similarity inside groups, while pushing between-cluster distance highest. Even then the answer retains an element of judgement and depends on the context and on the particular training set. What usually decides it in practice is face validity: the groups look sensible and can be described. Summary statistics on the centroids, the range of values inside each group, and a few named members of each go a long way toward that judgement.
Take an index tracking the 3,000 largest listed companies in the United States by market capitalisation. Those companies can be split into 10 groups, into 50, or into many more, using financial characteristics such as total assets, total revenue, profitability and leverage alongside operating characteristics such as headcount and research intensity. Firms sharing a standard industry code can look entirely different on those measures, so groups derived this way tell you something real about who a genuine peer is. The number chosen depends on how fine a segmentation is wanted. The same treatment can be applied to collective investment vehicles or to hedge funds, again as a substitute for the standard labels, and it also helps in visualising data and in spotting trends or outliers. This is one of the most heavily used algorithms in the industry, above all when patterns are being hunted in wide datasets during exploration of the data, and as a way of generating alternatives to industry classifications that never change.
Hierarchical clustering
Hierarchical clustering proceeds iteratively too, but it constructs a hierarchy rather than a flat partition. Under k-means the data end up in a set number of groups bearing no relation to one another. Under hierarchical methods, intermediate rounds of grouping are produced along the way, growing larger under the agglomerative version and smaller under the divisive one, until a final arrangement is reached. Those intermediate rounds relate to one another, which is what the word hierarchy signals. The computation costs more than k-means. What it buys is the ability to inspect several different granularities of segmentation before committing to one.
Agglomerative clustering, working bottom up, opens with every observation as a cluster of one. The two nearest clusters, under whatever distance measure applies, are fused into a larger one, and that step repeats until a single cluster contains everything. Follow a hypothetical set of 11 observations, lettered A through K. Eleven singleton clusters exist at the start. The first round of fusing produces six clusters: five pairs plus observation G, which has not yet found a partner. The next round produces two, one holding six observations and one holding five. The last round produces the single cluster of 11. Look inside it and the structure is visible: two principal sub-clusters, and inside each of those, three smaller ones.
Divisive clustering, working top down, opens with one cluster containing everything. It splits that into two on a distance measure, then keeps splitting the intermediate clusters into smaller ones until every cluster holds a single observation. Run on the same 11 observations, it goes from one large cluster to two, of six and five members, then to six, five pairs plus G on its own, and finally to 11 singletons.
In this illustration the two directions of travel arrived at identical structures, two principal sub-clusters each containing three smaller ones, leaving the analyst free to work with either the six-cluster or the two-cluster picture. Identical answers are not the norm, since the two directions generally run on different algorithms. Bottom-up is the usual choice on a large dataset because it computes quickly. It also decides locally, without any initial view of the overall shape of the data, which makes it good at picking out small groups. Top-down begins from a view of the whole, so global structure is built into its decisions, and it is correspondingly better at picking out large ones.
Either direction needs a rule for the distance between two clusters, as opposed to between two points. Common rules take all the pairs of observations spanning the two clusters and use the shortest of those straight-line distances, or the longest, or the average.
Reading a dendrogram
A dendrogram is the tree diagram used to display a hierarchical clustering, and it makes the nesting explicit. Clusters run along the horizontal axis and a distance measure runs up the vertical one. Every cluster appears as a horizontal segment, called the arch, joining two vertical segments, called dendrites. How high an arch sits records how far apart the two clusters it joins actually are, so a short dendrite marks a close, and therefore similar, pair. A dashed horizontal line drawn across the diagram records how many clusters survive at that stage.
Read upward for the bottom-up version. At the base sit 11 clusters of one, A through K. Fusing produces six larger ones, numbered 1 through 6, with A and B combining into cluster 1 while G, still unpartnered, becomes cluster 4 in its own right. Higher up, two clusters remain, the first of them gathering clusters 1 through 3. At the summit is a single cluster, and its composition is plain to see: two principal sub-clusters, each built from three smaller ones. Read the identical diagram downward instead and it displays the top-down version, ending at the base with all 11 singletons.
Investment uses are numerous. Diversifying a portfolio can be posed as a clustering problem, the object being to hold assets drawn from several different clusters. Since separation between clusters is what the algorithm maximises, spreading holdings across them is a way of ensuring the portfolio spans a wide range of characteristics and that its risks are genuinely spread. Read the same output the other way and concentration within one cluster is a warning that risk is concentrated too. One caution: output from these algorithms is often awkward to evaluate, because a cluster is never defined explicitly by anything except its own membership. That does not stop them being valuable, since what they expose, the underlying resemblances among observations, would otherwise stay buried in a complicated dataset.
István Perényi manages the Europe Diversified Equity Fund inside the Diversified Investment Management Company family of funds. Its benchmark covers 600 European stocks across 17 countries, 19 industry sectors and three capitalisation bands. Recent performance has left him worried that the holdings, although lined up reasonably well with the country weights of the benchmark, carry biases and concentrations nobody has noticed. He asks the chief risk officer, Elsa Lund, to look into it, and her analysts come back with three proposals.
| Proposal | What it involves |
|---|---|
| 1 | Work out the country, industry and capitalisation exposure of every holding, add them up, set the totals beside the benchmark exposures, and study the mismatches for biases or concentrations nobody expected. |
| 2 | Look for natural groupings among the holdings using eight numerical measures of their operating and financial characteristics, then study those groupings for biases or concentrations nobody expected. |
| 3 | Run a regression of Fund returns on country equity indexes and sector indexes taken from the benchmark, then study the coefficients for biases or concentrations nobody expected. |
Lund then asks analyst Greg Kane what has to be specified before any clustering algorithm can run, whichever one is picked. Kane answers that the list is short: a distance measure, plus the hyperparameter k if k-means is used. She also asks whether k-means would have an advantage over the hierarchical alternative, and Kane says he considers the hierarchical route the better fit.
The investment committee of an endowment fund wants three names to buy for its large-cap equity portfolio. Eight constituents of a broad United States equity index are handed to an analyst, whose brief is to establish how closely the returns on those eight move together, which is to say how strongly they correlate. Since the object is diversification, the committee wants the three chosen names to correlate as little as possible. So the analyst groups the eight by resemblance and then takes one name out of each group.
| Item | Detail |
|---|---|
| Content | Closing prices, adjusted, on a daily basis for eight index member stocks |
| Period covered | Trading days from 30 May 2017 through 24 May 2019 |
| Observations | 501 |
| Tickers | GS, JPM and UBS; AAPL and GOOG; F and GM; FB |
The steps in the analysis
- Assemble the panel of adjusted closing prices for the eight names.
- Convert prices into daily log returns, so that each name is represented by a vector of 500 numbers.
- Run the bottom-up algorithm. It begins by computing a Euclidean distance for every pair of return vectors, and those pairwise figures populate a distance matrix, otherwise called a dissimilarity matrix, whose diagonal is zero throughout. Every stock starts alone. The two nearest clusters are located and fused into one. Distances from that newly created cluster out to everything still unmerged are then recomputed, here through average linkage, which measures from the centre of the new cluster to the centre of each remaining one. Other linkage rules exist, and whichever is chosen the sequence is identical: fuse the closest pair, treat the result as one cluster, recompute the distances.
- Keep repeating the recomputation until nothing is left unmerged.
- Draw the dendrogram, then find the highest horizontal line that cuts exactly three dendrites, three being the number of recommendations wanted, and read off the grouping at that level.
Note that the returns, not the prices, are what get clustered. Every calculation below comes straight out of the matrix.
| GS | JPM | UBS | AAPL | GOOG | F | GM | FB | |
|---|---|---|---|---|---|---|---|---|
| GS | 0.000 | 0.215 | 0.281 | 0.375 | 0.345 | 0.393 | 0.383 | 0.471 |
| JPM | 0.215 | 0.000 | 0.243 | 0.364 | 0.332 | 0.348 | 0.358 | 0.456 |
| UBS | 0.281 | 0.243 | 0.000 | 0.380 | 0.338 | 0.385 | 0.384 | 0.460 |
| AAPL | 0.375 | 0.364 | 0.380 | 0.000 | 0.307 | 0.456 | 0.445 | 0.437 |
| GOOG | 0.345 | 0.332 | 0.338 | 0.307 | 0.000 | 0.422 | 0.405 | 0.357 |
| F | 0.393 | 0.348 | 0.385 | 0.456 | 0.422 | 0.000 | 0.334 | 0.480 |
| GM | 0.383 | 0.358 | 0.384 | 0.445 | 0.405 | 0.334 | 0.000 | 0.491 |
| FB | 0.471 | 0.456 | 0.460 | 0.437 | 0.357 | 0.480 | 0.491 | 0.000 |
Work through the fusions in the order the algorithm carries them out. In the dendrogram, the vertical gap spanned by each connection is the Euclidean distance between the two things being joined, so every fusion fixes the height of one arch.
(0.243 + 0.281) ÷ 2 = 0.262.
Nothing else still unmerged sits closer than that, so UBS is absorbed and the arch is drawn at 0.262. Three banking names now share one cluster, and that cluster is carried forward as the average of the three return vectors.
(0.364 + 0.380 + 0.375 + 0.332 + 0.338 + 0.345) ÷ 6 = 2.134 ÷ 6 = 0.356.
At that level three groups survive: the cluster of five, the pair of auto names, and FB standing alone.
What the clustering reveals
Broadly the groups line up with sectors, but two anomalies surface. FB does not behave like the other two technology names at all once returns are compared for co-movement. And those other two behave more like the banks than like the pair of car makers, which end up isolated together.
The top-down algorithm begins from the opposite end, with all eight in one cluster, and splits recursively until each name stands alone. Working out the very first split means evaluating every way the eight could be divided, which is far too numerically intensive to set out in detail. The table below places the three-group outcome of all three algorithms side by side. Cluster numbers are arbitrary from one column to the next; what matters is which names sit together.
| Stock | Agglomerative | K-means | Divisive |
|---|---|---|---|
| GS | 3 | 3 | 1 |
| JPM | 3 | 3 | 1 |
| UBS | 3 | 3 | 1 |
| AAPL | 3 | 2 | 2 |
| GOOG | 3 | 2 | 2 |
| F | 2 | 1 | 1 |
| GM | 2 | 1 | 1 |
| FB | 1 | 2 | 3 |
Reading the columns as groupings: bottom-up gives a five-name cluster of banks and two technology stocks, an auto pair, and FB alone. K-means gives a bank trio, a technology trio including FB, and the auto pair. Top-down gives a five-name cluster of the three banks with the two auto names, a technology pair, and FB alone.
One point commands unanimity: the three banking names belong together under every method. Two of the three also isolate the car makers as a group of their own. Where they part company is FB. K-means sorts strictly along sector lines and files it with the other technology names; both hierarchical methods treat it as an outlier and leave it by itself. As a rule the two hierarchical routes agree with each other more often than either agrees with k-means, though even a shared linkage rule does not guarantee identical output. K-means opens with three groups already in existence and shuffles points between them, a mechanism unlike anything the hierarchical methods do, so its answers are not expected to coincide with theirs.
Given the instruction that the three purchases should correlate as little as possible, the recommendation is to buy FB, to buy whichever of the two car makers looks better value, and to buy whichever of the three banks looks better value.
Removing the auto stocks
Now suppose the same exercise is repeated with the two car makers withdrawn, leaving six names. The panel of prices and daily log returns covers those six only, and the matrix is the old one with two rows, two columns and every distance involving them deleted.
Rerun on six names, the algorithm produces three groups: the bank trio, the pair of AAPL and GOOG, and FB alone. GS and JPM still fuse first and UBS still joins them, exactly as before, and the technology pair still forms. What no longer happens is the merger of that pair into the bank cluster, because three distinct groups already exist and FB stays out on its own, its return co-movement being so unlike either of the others. The revised recommendation is to buy FB, to buy whichever of the technology pair is cheaper, and to buy whichever of the three banks looks most attractive.
A large share of the progress made in artificial intelligence traces back to three related developments: better neural networks, better deep learning algorithms, and reinforcement learning. Between them they handle the hardest problems in the field, sorting images into categories, recognising a face, recognising speech, and working with human language. What those problems share is that the relationships involved are not linear and that a great many feature inputs interact.
Neural networks, sometimes written as artificial neural networks, are flexible to an unusual degree and have performed well wherever interactions among features are complicated and the underlying relationship bends. Supervised work uses them for classification and for regression. They also matter in reinforcement learning, which needs no training data labeled by a human at all.
From regression to a network
The shortest way in is through a comparison with multiple regression. Suppose a regression takes four features, x1 through x4, and returns one predicted target y. It weights each feature, adds the weighted terms up, and allows for an error.
A basic network is drawn as circles joined by arrows. The circles are nodes and the arrows are links. Nodes are organised into three kinds of layer.
- The input layer, carrying one node per feature, so four nodes here.
- The hidden layers, which is where learning happens while the network trains, and where inputs are processed once it has been trained.
- The output layer, a single node in this case, which is how anything gets out of the network.
Structure aside, the decisive difference from a regression is what the hidden nodes do to the inputs. They transform them, and the transformation bends, so the values combined into the target are no longer the raw features. A widely used transformation is the rectified linear unit, written f(x) = max(0, x). Feed it anything negative and it returns zero; feed it anything positive and it returns that same number back. Apply it to three different combinations of the four features and the target becomes a weighted sum of three transformed quantities.
One preparatory step is required. Features have to be put on a common scale before they enter, since the units they arrive in differ. Where every input happens to be positive, dividing each by its own largest observed value places them all between zero and one.
What follows is an arithmetic illustration of the transformation just described. The scaled feature values are chosen to make the mechanism visible and are not drawn from any dataset. Let x1 = 0.40, x2 = −0.30, x3 = 0.50 and x4 = 0.20, and let the three output weights be 2.0, 1.5 and 0.5.
z1 = max(0, 0.40 − 0.30 + 0.50) = max(0, 0.60) = 0.60.
z2 = max(0, −0.30 + 0.20) = max(0, −0.10) = 0.00.
z3 = max(0, −0.30 + 0.50 + 0.20) = max(0, 0.40) = 0.40.
The middle node stays silent. Its inputs summed to a negative number, which the transformation maps to zero, so it contributes nothing onward.
y = (2.0 × 0.60) + (1.5 × 0.00) + (0.5 × 0.40) = 1.20 + 0.00 + 0.20 = 1.40.
Look at what the bend achieved. Under a linear specification every feature pushes on the answer in proportion to its own coefficient, always, whatever the level of the inputs. Here the pairing of x2 with x4 pushed on nothing at all, because together they failed to clear the threshold at which that node fires, while the very same x2 still worked through the other two nodes. A contribution that switches on and off according to the state of the other inputs is precisely what no linear model can express.
Inside a node
Now enlarge the picture: four input nodes, one hidden layer holding five nodes, and one output node. Those three counts, four, five and one, are hyperparameters, since they fix the shape of the network before any learning starts.
Consider any circle standing to the right of the inputs. Such circles are occasionally called neurons, on the grounds that they process what reaches them. Take the one at the top of the hidden layer. Four arrows run into it from the inputs, so four values arrive. Attached to each arrow is a weight standing for how much that path matters, and at the outset those weights may be nothing more than random numbers. Two operations then take place inside the circle.
- A summation operator multiplies each arriving value by the weight on its own link and adds the results, producing the total net input.
- An activation function receives that total and converts it into whatever the node passes on.
A useful image for the second operation is a dimmer switch on a lamp: it turns the strength of what arrived up or down. Which function is used is the choice of the modeller, so it counts as another hyperparameter, and characteristically it bends rather than running straight. Common choices are a sigmoidal curve shaped like an S, whose output runs between 0 and 1, or the rectified linear unit met earlier. Bending is the whole point: it means a given change in input alters the output by different amounts depending on where the input started.
The behaviour is easy to picture with the S-shaped function. A total net input that is negative comes out near 0, and a node returning almost nothing has effectively not fired, so there is nothing worth passing along. A total net input that is positive comes out near 1, and the node has fired. Whatever emerges travels on to the next set of circles where a second hidden layer exists, or, in a network with only one hidden layer, straight to the output node as the prediction. Moving values through the network in this direction is called forward propagation.
How a network learns
Training begins from weights initialised at random. In supervised work the loop is simple in outline: predict, compare the predictions with the actual labels using some agreed performance measure such as mean squared error, then nudge the weights so that total error falls. Where the nudging works its way back through the layers in reverse, the procedure is called backward propagation. Learning is nothing more than the accumulation of those nudges, and the updating rule can be written informally as follows.
How large each nudge is depends on the learning rate, itself a hyperparameter. Once training finishes, every weight holds a settled value, and collectively those values are the parameters of the fitted network. Because the features are all wired together through functions that bend, the arrangement can approximate relationships of considerable complexity. Add nodes and add hidden layers and that capacity grows, but so does the danger of overfitting.
Pricing assets is a noisy, stochastic business in which relationships refuse to stay put, which makes it awkward to model and interesting to researchers asking whether these methods can teach us anything about how markets function. Comparisons run so far between statistical and machine learning approaches to equity prices suggest that even modest networks model returns better than traditional statistical methods do, at the level of the individual stock and at the level of the portfolio, and the reason offered is that they track variables that move and interact. If so, they may simply be better suited to relationships in security prices that do not run in straight lines. Against that sit two costs: the fitted network cannot be interpreted, and training one demands both a great deal of data and a great deal of computation. Those costs are why many investment applications are better served by something else.
Deep neural networks
Everything above concerned shallow networks, meaning those with a single hidden layer. Stack many hidden layers instead, at least 2 and possibly upward of 20, and the result is a deep neural network. Networks of that kind underpin deep learning and have succeeded across a wide span of artificial intelligence applications, driving progress in recognising images, patterns and speech.
Put briefly, such a network accepts a set of inputs drawn from the feature set at its first layer and hands them to a layer of mathematical functions that bend, the neurons, each carrying a weight for every input it receives and each usually emitting a scaled number lying between 0 and 1, or between −1 and 1. Those emissions feed the next layer, and the next, until the last layer emits a probability for every category the target can take, one node per category. Whichever category carries the highest probability is the one assigned. Training on large volumes of data is what fixes the weights, and the criterion is the minimisation of a stated loss function.
How many nodes sit in the first and last layers is usually settled by the features available and by the output wanted. Plenty of hyperparameters remain: how many hidden layers, how many nodes in each, how they connect, and which activation architecture to adopt. They should be chosen for the best performance outside the sample, and no simple recipe exists for doing so. Start from a defensible guess informed by experience and by published work, observe the outcome, then adjust step by step until performance reaches the target. Since training takes substantial time, working through the hyperparameters systematically may be impractical, so on a problem with a modest dataset it is sensible to open with two or three hidden layers carrying a few hundred nodes between them, and to tune outward from that starting point.
Applications are numerous: recognising characters and images and other pattern problems, detecting fraud on payment cards, solving vision and control problems in self-driving cars, and processing human language, machine translation included. Three developments arriving together explain the success. Machine-readable data became available in enormous quantity. Analytical methods for fitting these models improved. And computers became fast, above all through the graphics processing unit chips whose design happens to suit the arithmetic these networks require.
Financial firms are experimenting with them for trading and for automating what happens inside the firm. One published study trained a deep network to price options, imitating the Black–Scholes–Merton model. The features fed into the input layer were the six parameters the model itself uses: the spot price, the strike, the time remaining to maturity, the dividend yield, the risk-free rate and volatility. Four hidden layers of 100 neurons apiece sat behind them, with one output layer. Prices predicted outside the sample tracked the real ones remarkably closely, and regressing predicted prices on actual prices produced an R-squared of 99.8%.
Reinforcement learning
Reinforcement learning entered the headlines in 2017, when a program defeated the reigning world champion at Go. Its framework has four elements: an agent that takes actions chosen to maximise its rewards over time, subject to whatever its environment permits. Mapped onto the game, the agent is a virtual player, the actions are the commands issued at the console, the environment is what appears on the screen, and the reward is the score.
Two things distinguish it from supervised learning. No observation arrives with a label attached, and no feedback arrives immediately. The algorithm has to watch its surroundings, try actions out even where they look unpromising in the moment, and draw on what earlier attempts taught it. Learning then accumulates across millions of trials and the errors they generate. The same structure is being applied to investment strategies, with the agent recast as a virtual trader operating under stated trading rules, the market as the environment and profit as the reward. Whether it can cope with what financial markets actually do remains unsettled.
Glen Mitsui is chief investment officer of a public employees pension fund belonging to a large Australian state, with A$20 billion under management. A quarter of that, A$5 billion, is run in-house and sits mostly in domestic government and corporate bonds and domestic equities. The other A$15 billion is farmed out to close to 100 external managers, most of them active, across foreign bonds and equities, hedge funds at home and abroad, property trusts, commodities and derivatives.
Four investment professionals pick and monitor those managers, whose fees exceed A$400 million a year. Returns against the relevant benchmarks have disappointed for several years running. Mitsui suspects drift away from stated style, and he is unwilling to pay for it. Professor Frank Monroe proposes a deep network that would take the trading of the external managers as it happens, compare it against recognised styles such as high dividend, minimum volatility, momentum, growth and value, and flag drift.
Case study: a deep learning fundamental factor model
A manager wants to choose stocks on forecast performance, working from a factor model built on company fundamentals, and to capture whatever excess return the strongest names deliver. Rather than a linear factor model she chooses a deep network to forecast returns. The design substitutes a feed-forward network regression, forward propagation being what feed-forward means, for the ordinary least squares regression that would normally occupy that slot. Networks overfit readily, so a LASSO penalty, the same penalty-based device applied earlier to regression, is brought in to hold that tendency down.
Managers rely heavily on cross-sectional fundamental factor models to pick up how company-specific characteristics affect individual securities. Such a model fixes a universe of N assets and a list of K fundamental factors. How sensitive an asset is to a factor, its exposure or loading, is written as beta, and the factors themselves are expressed through their factor returns. Two conventional estimation routes exist. Where the factors are known, a time-series regression recovers the loadings. Where the loadings are known, a cross-sectional regression recovers the factor returns. This case takes the second route, using the exposures to predict a return by estimating factor returns through a multivariate linear regression.
That equation is too plain to represent a bending relationship between returns and fundamental factors, so a deep network takes its place, learning how the betas map onto returns at each date without assuming the map is straight. What the network hunts for is the set of weights minimising mean squared error outside the sample, measured between predicted and observed returns. Simply piling on neurons raises in-sample performance and damages out-of-sample performance, which is the bias against variance trade-off in its familiar form. Adding a LASSO term to the loss function shrinks the count of non-zero weights automatically, and prediction outside the sample improves as a result.
A weight belongs to a link joining a node in one layer to a node in the next, so cutting weights generally cuts connections rather than circles. There is one exception. Should every weight leaving the neurons of the preceding layer be driven to zero, the current layer loses nodes as well. Where the preceding layer happens to be the input layer, that amounts to losing features.
| Item | Detail |
|---|---|
| Span | Monthly, June 2010 through November 2018 |
| Periods | 101 |
| Stocks (N) | 218 |
| Features (K) | 6 |
| The six features | Enterprise value; enterprise value against trailing 12-month EBITDA; the share price measured against sales, against earnings and against book value; the logarithm of market capitalisation |
| Target | The return on each stock over the month ahead |
The universe was defined as the 250 largest names in a broad United States equity index by market capitalisation as at June 2010, and 218 survive once names with missing loadings are dropped. Enterprise value here is equity plus preferred stock plus debt, less cash and short-term investments. Market capitalisation is share price multiplied by shares outstanding, and the logarithm of it is what enters the model. Prices and loadings were sourced from a commercial data terminal.
| Ticker | Enterprise value ($ mil.) | EV to 12M EBITDA | Price to sales | Price to earnings | Price to book | Log cap ($ mil.) | Return (%) |
|---|---|---|---|---|---|---|---|
| SWK | 10,775.676 | 30.328 | 1.138 | 16.985 | 1.346 | 9.082970 | −0.132996 |
| STZ | 7,433.553 | 15.653 | 1.052 | 10.324 | 1.480 | 8.142253 | −0.133333 |
| SRE | 19,587.124 | 10.497 | 1.286 | 10.597 | 1.223 | 9.314892 | −0.109589 |
Training proceeds by walking forward through time, a method also described as time-series cross-validation. A fresh model is fitted at every date. Each factor enters the network as one feature, and the loadings belonging to one stock form one feature vector, so each period supplies 218 paired observations of a feature vector and a monthly return. Fit at date t, then test on date t plus 1, which supplies another 218 pairs. On the following pass, what was the test material becomes the training material and the revised model is tested one month further on. The walk continues to the last pass, fitting on period 100 and testing on period 101.
The architecture is feed-forward with six input nodes, two hidden layers and a single output neuron. Each hidden layer holds 50 neurons, which deliberately over-specifies the parameter count so that bias sits well below and variance well above what would be optimal, leaving the LASSO term to shrink the set back. There is also a constraint worth noting: no hidden layer should hold more nodes than the training set holds observations, and 50 against 218 respects that comfortably. Each period the fitting exercise looks for the best available balance between bias and variance, and the in-sample error, the out-of-sample error and the optimal regularization parameter are all recorded. The whole cycle then repeats across the remaining 100 periods, with the hyperparameters tuned by cross-validation at every step.
Comparing the two errors month by month across the full 101 periods, the out-of-sample figure is generally far larger than the in-sample figure. What changes as the walk proceeds is the gap between them, which narrows dramatically as the model is trained and tested over and over.
Regularization pushes the two errors in opposite directions. Turning it up eliminates weights, which injects bias and therefore lifts the in-sample error, while cutting the variance of the model and therefore lowering the out-of-sample error. On the opening pass, cross-validation with 50 neurons per hidden layer indicates that a substantial amount of regularization is called for, namely 0.10, against a hyperparameter that typically falls somewhere between 0.001 and 1.0. Convergence has still not arrived at that setting. A gap of roughly 0.0051 persists, being 0.01025 less 0.0052, and the slopes of both curves imply the optimal setting is considerably above 0.10. Bear in mind that this hyperparameter cannot be interpreted directly and bears no fixed relation to how many weights were removed. All that can be said is that a larger value penalises the loss more heavily.
One caution matters more than any of the numbers. Error outside the sample describes how well the network predicts, but predicting well is not the same as producing a profitable strategy. The network forecasts the mean return for the coming month and says nothing about the rest of the distribution. So a rule that simply buys whatever the network ranks highest need not generate positive information ratios, an information ratio being alpha divided by nonsystematic risk, which measures abnormal return per unit of risk in a well-diversified portfolio.
| Basis | Reported information ratios | Range |
|---|---|---|
| In-sample forecasts | 0.6974, 0.6748, 0.6532, 0.6229 | 0.697 down to 0.623 |
| Out-of-sample forecasts | 0.2600, 0.3108, 0.3078, 0.3149 | 0.260 up to 0.315 |
Each back-test buys the highest ranked names on the forecast for month t plus 1, formed from features observed in month t, and is run for portfolios holding 10, 15, 20 and 25 stocks. No allowance is made for transaction costs, interest rates or other fees. For orientation, a ratio between 0.40 and 0.60 is generally regarded as quite good.
The second row sits far below the first, and it is the second row that indicates what this approach would plausibly deliver in future. Treat it as a baseline rather than a verdict. Bringing in further fundamental factors, and macroeconomic ones as well, is the obvious next refinement, and the expectation is that the out-of-sample ratios would then improve substantially.
Jane Hinton, a research analyst, is taking the model further. She brings in four more fundamental factors drawn from firm characteristics, debt leverage and research intensity among them, and adds dummy variables covering 11 industrial sectors. She also draws on a supplementary data source to widen the universe from 218 stocks to 420.
Everything covered so far collapses into a short series of questions. Work through them in sequence and the algorithm selects itself. One branch holds the supervised methods and the other holds the unsupervised ones, with each question acting as a junction.
- Are the data complicated, carrying many features that move closely together? Where they are, principal components analysis should be run first to shrink the dimensions.
- Is the problem one of classification or of numerical prediction?
- If numerical prediction, do the data have non-linear characteristics? Penalized regression and LASSO suit linear data; CART, random forest or neural networks suit non-linear data.
- If classification, are the data labeled? Labeled data lead to the classification algorithms; unlabeled data lead to the clustering algorithms.
- If the data are labeled, do they have non-linear characteristics? K-nearest neighbor and support vector machine suit linear data; CART, random forest or neural networks, including deep neural networks, suit non-linear data.
- If the data are unlabeled, do they have non-linear characteristics? Neural networks, including deep neural networks, suit non-linear data. For linear data, k-means applies when the number of categories is known and hierarchical clustering when it is not.
| Situation | Linear data | Complex non-linear data |
|---|---|---|
| Complexity reduction needed | Principal components analysis | |
| Numerical prediction (regression) | Penalized regression, LASSO | CART, random forests, neural networks |
| Classification with labeled data | K-nearest neighbor, support vector machine | CART, random forests, neural networks |
| Clustering with unlabeled data, number of categories known | K-means | Neural networks |
| Clustering with unlabeled data, number of categories unknown | Hierarchical clustering | Neural networks |
Note that the first question stands apart from the others. Dimension reduction is not an alternative to prediction or classification; it is a preparatory step that often precedes them.
Where this fits in a wider data project
Choosing an algorithm is one decision inside a longer sequence. Before any algorithm runs, the steps of preparing and wrangling the raw data have to be completed, because real data arrive incomplete, inconsistent and in formats no model can read. Data exploration follows, both to understand the distributions involved and to guide the work of engineering and selecting the features that will actually be fed to the model. Where the raw material is textual, exploring text-based sources such as filings, transcripts and news requires its own methods for extracting and constructing features before any financial forecasting can begin. The algorithms in this lesson are the engine; the surrounding project work determines whether the engine has anything worth running on.
Two habits of mind survive the whole subject. The first is that evaluation only counts when it happens outside the sample, since the point of any model is to say something about material it has never met. The second is that opacity has a price, and the price is commercial rather than aesthetic. A tree an investment committee can follow may be worth more than a forest that predicts a shade better, and choosing between them is a judgement about the business, not about statistics.
Six short questions covering the major types of machine learning.