avatarMicroprediction

Summary

The website content discusses the application of financial portfolio theory to the construction of a diversified portfolio of machine learning models using the precise Python package in conjunction with LazyPredict and PyPortfolioOpt, aiming to improve out-of-sample model performance.

Abstract

The provided content outlines an innovative approach to machine learning model selection and combination, drawing parallels between financial portfolio construction and model ensemble techniques. The author, through a detailed Colab notebook, demonstrates the use of the precise Python package, LazyPredict, and PyPortfolioOpt to create a portfolio of scikit-learn models. The process involves training models on a standard dataset, selecting the best model based on out-of-sample performance, estimating portfolio weights using model residuals, and comparing the performance of the best single model to a weighted combination of models. The author emphasizes the importance of diversification in model portfolios to avoid over-reliance on a single model, much like diversification in financial investments to mitigate risk. The article also touches on the ethical considerations of using certain datasets and hints at future work to further integrate financial portfolio theory into machine learning model selection.

Opinions

  • The author believes that over-concentration in model selection can be detrimental to out-of-sample performance, similar to over-concentration in financial portfolios.
  • There is a cautious optimism about the potential for advanced portfolio construction techniques to enhance model ensembles, despite empirical warnings and the complexity of the task.
  • The author suggests that the literature's warnings against overly complex portfolio construction methods should not deter further research and development in the field.
  • The precise package is presented as a tool that can help push back against the notion that complexity in model ensembles does more harm than good.
  • The author expresses that the "blending" stage of automated machine learning could benefit from adopting methods from finance, particularly in the context of model combination.
  • The article implies that the precise package's approach to model portfolio construction is novel and has the potential to outperform traditional model selection methods.
  • The author is critical of the use of certain datasets, like the Boston dataset, for purposes other than educational, highlighting the importance of ethical considerations in data science.
  • The author invites collaboration and contribution to the precise GitHub repository, indicating a belief in the value of crowdsourcing and community engagement in advancing the field.

Optimizing a Portfolio of Models

In this colab notebook I provide an example of the use of the precise Python package (and PyPortfolioOpt) to create a diversified portfolio of scikit-learn models fitted using LazyPredict.

Background

For now, I’m content to draw the reader’s attention to the close parallels between financial portfolio construction and model ensembles. A linear combination of models is certainly akin to a portfolio of assets, insofar as the assessment is mathematically similar and sometimes, identical.

In the case of models assumed to be unbiased, we take an interest in the squared error of the combined model (or some similar metric). Likewise, in finance, we are sometimes interested in minimizing the variance of the value of a linear combination of securities (or, again, some proximate objective).

Interestingly both the forecasting literature and also the financial literature include the same stern empirical warning in different terminology. Over-concentration can hurt the long-term returns of a portfolio, just as over-reliance on a single model can hurt out-of-sample performance.

We also find empirical warnings in the literature about getting too fancy in the portfolio construction (analogously, the combining of expert opinions, or forecast models, or model outputs). The surprising difficulty in improving on what would seem to be a low bar (equal weights) is a refrain you’ll hear quite often.

It is a reasonable concern, and as an example, the dangers of point estimates of covariance are well appreciated — a topic you can spend hours reading about (here’s a list of papers) should you wish.

Yet theory and practice advances so the notion that cleverness does more harm than good is probably somewhat overwrought, in my opinion, and certainly should not dissuade people working in data-rich domains. It is my intent, with the creation of the precise package and some interoperability with AutoML, to gently push back against that perception.

In particular, I suspect that the “blending” stage of automated machine learning will start to borrow more from finance.

The Plan

My modest goal here is to take a standard sklearn dataset off the shelf and see if we can easily construct a “pretty good” autonomously created combination of models that serves you better than choosing the best one. A more careful comparison against various varieties of cross-validation will have to wait, but I’m providing you with the ingredients to charge ahead with that, should you choose to do so.

To this end, we’ll break the data into three partitions called “train”, “test” and “validate”. Here “test” is something of a misnomer as we’ll be doing the following:

  1. Train on X_train, y_train
  2. Select the best model based on X_test, y_test out of sample performance
  3. Also estimate model portfolio weights using model residuals for X_test, y_test, and standard portfolio construction technique.
  4. Retrain models on X_train+X_test
  5. Compare the performance of the best model against a weighted combination, with weights from step 3.

(As a semantic aside one notes that choosing “best” model as determined above is, of course, a special case of a portfolio — one where all the mass is on one model. I should probably add it to the precise package!)

Preliminaries

Getting to nuts and bolts, we’ll need LazyPredict and precise packages. If you are using colab or an environment with a pre-provided pandas, save yourself possible annoyance. For instance on colab:

then restart the environment. We’ll be using:

and the very same sklearn example as you’ll find in the LazyPredict README, the Boston dataset.

A careful reading of the sklearn documentation reminds us that this dataset has ethical problems and should not be used unless the purpose is to educate people about data ethics. Of course, of course, that is my intent. You should all buy and read my fabulous upcoming book “Microprediction: Building an Open AI Network” to be published by MIT Press in the fall. There you will find a long discussion about model fairness and why it can only be solved by a prediction web.

Anyway, back to our half-day effort to defeat enterprise AutoML...

The LazyPredict Package

It’s called LazyPredict for a reason, I guess. This nifty little package saves you quite a few lines of code marshaling scikit-learn models and their predictions en masse. For instance, the use of LazyRegressor below creates a performance table for models trained on X_train and tested on X_test:

(You could do the same with pycaret or autoviml or similar packages and I started down that path. However, the interactivity assumption of pycaret slowed me down just enough to switch over, for the purpose of this particular experiment. I’ll write some adaptors for the popular choices soon enough).

The predictions1 output gives us the data we need, and now we’ll turn to the precise package to infer a combination of models.

The Precise Package

The precise package comprises a collection of “managers”, among other things. A manager is someone who receives a vector (which might be a collection of contemporaneous returns for several stocks, but here comprises model residuals) and updates portfolio weights.

Using a “manager” to update weights

The package contains some novel approaches to this task, and also calls down to the excellent PyPortfolioOpt and Riskfolio-Lib packages. There is a full listing of managers in the file LISTING_OF_MANAGERS, would you believe.

In the Boston dataset, the rows are, I assume, non-temporal. The precise package is aimed mostly at real-time temporal problems, but that doesn’t really matter here.

For some managers we let Riskfolio-Lib do all the work, starting with an accumulated buffer of historical data. For others, a portfolio manager might be a combination of two choices:

  1. A method of estimating covariance in online fashion, combined with
  2. A way of determining a portfolio from a covariance forecast (sometimes using PyPortfolioOpt).

The explosion of possibilities leads to rather long names for fully autonomous managers, I’m afraid. If you squint at the import below and then refer to the precise README you might infer I’m using PyPortfolioOpt’s implementation of a minimum volatility portfolio and Graphical Lasso with cross-validation for covariance estimation.

If I make the font larger….

you might also observe the style of calling the manager. I’m feeding it one vector of model residuals at a time, and I’m saving the state s on its behalf from one invocation to the next. Once you get that part of the joke, the use of the precise package is trivial.

(Don’t worry about the use of e here. That’s a little performance hack. It tells the portfolio manager that we only care about the final w. I refer you to the documentation, such as it is, for more explanation of “skating”.)

The Portfolio and Combined Model

The covariance of model residuals on the test data set suggest to the manager a diversified portfolio as follows:

Once we have generated out-of-sample predictions for these models, we simply use a linear combination.

Linear combination of models

As an aside, I’m using a “long-only” manager, in financial parlance, for stability. In some cases, one might wish to relax that constraint, with due care.

Out of sample performance

Obviously, we don’t have a crystal ball to tell us which model will perform best out of sample, but I’ve produced that ex-post squared-error leaderboard anyway as a point of reference.

I’ve inserted into that impossible leaderboard our weighted portfolio of models, and also the best model (which in this example was OrthogonalMatchingPursuit). As you can see, the portfolio was better on this occasion.

Out of sample performance of a portfolio of sklearn models, set against the selected “best” model

If you look at the script version in precise/examples_ensembles_lazypredict there is a little Monte Carlo study. It strongly suggests that using a portfolio of models is superior to choosing the best one, at least for the Boston dataset. (I’ve also included the best model not retrained on the test set, to anticipate that comment.)

Choosing a Model Portfolio: An Open Problem?

There is a healthy stacking, mixture of experts, and ensembling literature and yet I think the question of the best use of financial portfolio theory in this context is a mostly open question.

One might push back and suggest that it may not be well answered by the empirical financial literature since portfolio methods and their out-of-sample performance depend on the nature of the data generating process quite strongly — and there are some characteristics of financial portfolios that don’t necessarily carry over to model residuals.

We shall find out soon enough, however. You can expect to see more Elo rating categories in the precise GitHub repo. These will try to get to the bottom of which types of portfolio construction are favored in different model combination contexts.

If you’d like to collaborate, find me here. I’d love to crowd-source some more model residuals, for instance, if you have them lying around (you do analyze your residuals, do you not?). Integration with popular AutoML packages may also bear fruit.

Automl
Portfolio Management
Data Science
Machine Learning
Recommended from ReadMedium