How should you backtest a new trading strategy idea?
Yeah, yeah. I hear you say. I know how to do this. I've read all your books mate. Twice. And everything on the blog. I need to use data that doesn't look forward. I need to avoid survivorship bias. I should use a backward looking expanding or rolling window. I need to use robust fitting methods, like those you have elucidated in recent blogposts. Then I need to be sure that the improvement is statistically significant. If all that works out, I'll add the idea to my portfolio. Otherwise I'll kill the idea.
Not bad. It's certainly better than what most people do.
But in fact that backtesting process will still lead you open to two kinds of in sample fitting. I discussed the three kinds here but briefly:
- Explicit: Optimising parameters using in sample data
- Implicit: Making decisions based on in sample results, but not formal optimisation
- Tacit: Only trying ideas you already know will work
- The original idea may have been developed using forward looking information; books, academic research, market folkore, or in the current climate an LLM trained on data up until quite recently. This is tacit fitting.
- We kill poorly performing ideas or select the best idea from multiple options. We do this once we've seen the backtest results. This is implicit fitting.
How do we get round this? The two big ideas I propose in this blog are:
- Backtests should be symmetric. We consider both the positive and the negative version of a trading strategy when optimising. That way we avoid tacit fitting as much as possible. As a handy side-effect, we also remove an arbitrary restriction on the degrees of freedom when fitting that may result in better out of sample performance.
- Backtests should be write only. You can add new ideas, but once they are in the backtest they stay there. There is no killing of bad ideas. There are no bad ideas! A really bad idea would be negative-d and become a great idea (assuming it wasn't bad purely because of trading costs). A weak idea would end up with a low allocation, but because of robust fitting it's unlikely to be zero. An idea that does get a zero allocation by the end of the backtest would have a positive allocation earlier, thus ensuring performance results are honest.
Backtesting that is both write only and symmetric combined with robust out of sample fitting, can be considered to be True Backtesting. The true backtesting protocol substantially reduces tacit fitting and ensures there is no implicit or explicit fitting. It ensures we get realistic ideas of historic performance.
I will incorporate these ideas into a python library I call Autofitter.
This blogpost won't reveal all the various details of the true backtesting protocol. That would fill a book - and it will indeed fill my next book, once I start writing it. I'll also be keeping the source code of Autofitter private to future buyers of the book, although implementing these concepts isn't exactly hard (in any case the code is still in a fairly sketchy form!).
Programming notes:
1 - The original subtitle I was going to use was "A Backtesting Protocol in the Era of Artifical Intelligence" a reference to this paper, which is probably one of the best finance papers ever written. Of course True Backtesting is relevant even if you don't use AI at all like me, but I think it's even more relevant in a world with AI.
2 - This is a standalone blogpost; but I will link to previous posts if you wish to explore the ideas further.
3 - This may well be the most important blogpost I write. I feel like I've cracked a problem I've been thinking about for 20 years. I know, I know. It probably won't live up to the hype, but read on anyway.
Prior Art
I am pretty sure that True Backtesting is an original idea, although of course it builds on earlier work. I'm certainly not claiming to have invented robust out of sample portfolio optimisation!
The idea of recording every backtest done has been advocated before by, most famously by Lopez de Prado*. However this is done to ensure you can properly do a correction for the number of tests, and is quite different from the idea of maintaining a single backtest to which you only ever add ideas. The closest that comes to this idea is a relatively obscure masters thesis by Mads Hofstedt Jæger**. His work on pairs trading suggests tracking every pair of stocks ever considered: "The framework suggest to never remove a pair from the pool of pairs, inducing data to increase in time". Again this is pretty different from having a single backtest with all the strategies you've ever thought of; arguably it's just an extension of the idea of ensuring there is no survivorship bias.
The idea of testing both the long and short versions of a strategy isn't novel, and I believe was first developed by David Aronson***. However, David did this in a standard test-accept or kill framework which is then subject to multiple testing corrections.
In summary then I'm pretty sure this is an original idea.
*** David Aronson (2006) — Evidence-Based Technical Analysis
Backtesting done (relatively) badly
I'm going to start off running through an example of backtesting done in an old school way - not true backtesting; but also avoiding most of the common mistakes. I'll note where it's problematic in this font but not yet explain how to deal with those problems by using True Backtesting. That's the next bit.
Let's start with a simple model. We want to predict the price of the S&P 500 future, for which I have price data back to 1982. We'll assume the data is accurately timestamped and not subject to revisions, clearly the S&P 500 future is still around and it's the only instrument we have so survivorship bias isn't relevant.
We could argue that selecting the very well performing S&P 500 is itself an in sample decision - but that discussion is for another blog post or possibly book chapter.
We'll do this in a normal Rob Carver way: by using a trading rule which calculates a forecast proportional to expected Sharpe Ratio, with an average absolute value of 10. Positions in the future can be long/short, can be leveraged, and will be inverse volatility scaled to hit an average absolute risk target (though our actual expected risk will vary depending on the forecast).
How should we predict this price?
Well Rob, I know how much you love trend following, how about an exponentially weighted moving average crossover with spans N and 4N? From 2,8 up to 64,256...?
Here is our first big mistake. We are tacit fitting. We are using information that would not have been available in 1982 to make a decision: the choice of EWMACN,4N. Choosing EWMAC to find trends is fine; pure theory or fake data can justify this. But you know trend following works with real data because you've seen my own backtests of trend following SP500; and also that I prefer the N,4N ratio although you probably can't articulate exactly why; again it's probably because it's empirically profitable.
Formally we are using prior knowledge to decide the universe of trading rule variations we are going to consider:
- The bounds of the universe: we only consider trend following rules in the space of N between 4 and 64
- The granularity of the parameter set (N=2,4,8... 64 rather than N=2,3,4.5...)
- We've also imposed a constraint by using N,4N rather than generally X,Y
Note this would still be a problem if rather than me your source was the journal of finance, chatgpt or something your broker mate told you in the pub.
Our next job is to work out what pairs of spans to use for our EWMAC (my name for these are variations). There are a few competing ways to do this. We can eithier:
- select the best unique variation
- select a combination of variation with some linear weighting (I call these weightings forecast weights)
- select a combination with non linear weightings
We know from theory that ensembles outperform single variations out of sample, especially if you're concerned with the variation of possible outcomes, so that knocks out 1. 3 will involve an outrageous explosion in parameters and complexity, and in any case it's always possible to create non linear forecasting rules that can be combined linearly and get the same outcome (not that we are doing this here in this simple example!). So we stick with 2. There are two broadly competing technologies for fitting linear weights in quant finance:
- Linear regression
- Mean variance optimisation (MVO)
I'm going to use 2, entirely because I'm more familiar with it (1 is used mainly by equity neutral types and I don't get invited to the same parties as them). Of course there isn't a massive difference between these two techniques (see here) and it's just as possible to do robust regression (using eg ridge regression, lasso) as it is to do robust MVO (using eg bootstrapping, shrinkage).
Anyway, these are the candidates we have:
Of course we'd never do explicit in sample fitting and just pick the best of these (which is the slowest - there happens to be a perfect monotonic relationship between speed and performance here - not down to costs!). Nor would we do non robust fitting that would probably pick a sparse portfolio that will do badly out of sample (and with higher variance of expected outcomes). I'm also not a fan of single in sample / out of sample fits. I prefer a (long) rolling window where we re-estimate parameters each year based purely on past data, and test with those parameters for the following 12 months. This does the best job of simulating what we could actually have done in the past where we starting from scratch.
Let's do a robust 20 year rolling out of sample MVO that uses some shrinkage parameters: SR shrinkage 0.5, correlation 0.75 that I derived in my recent series on fitting (in fact, I use more conservative shrinkage if there is less data).
[Note: If you've been following my optimisation series you will know I usually advocate pooling (only one instrument here, so not relevant) and clustering (portfolio not big enough to justify it here so let's keep it simple)]
There is a debate to be had about where those parameters and the 20 year window come from and whether they are forward looking, but that will come later in the post.
OK let's look at the time varying forecast weights, fitted annually:
After an initial 'learning process' we do indeed stick to trading the three slowest and most profitable rules. Here is the gross and net p&l for the S&P 500 using those time varying forecast weights:OK. We have a not bad at all strategy. We sit around and trade it for a while, and then think - let's add something else.
It's carry isn't it Rob. Trend and Carry. You love them, don't you. You really really love that combo.
We'll add.... carry. Unlike trend it's possible to specify a futures carry trading rule without almost no reference to empirical evidence. The only parameter in my carry rule we need is a smoothing parameter; which I'm going to set to 10 days (normally the fastest parameter I use). In my own actual strategy I use multiple parameters, but they are highly correlated. For simplicity let's pick just one. The details of my carry strategy can be found in my 4th book, and on the blog, so I won't go into detail.
Again, the choice of parameter smoothing 10 is arguably tacit in sample fitting. However it's less egregerious than the choice of N, 4N given the high correlation of different smoothed carry variations.
Again I would never normally look at this before evaluating it, but here is the carry p&l:
[The 'hazy' early p&l is because there are gaps in the forecasts due to periods when contracts aren't priced at the same time - this is preliminary code and I need to add a forward fill somewhere to remove this effect. But it won't affect the results.]
Now there are many ways of evaluating the performance of this rule, but in the framework we're using here we're just going to add it to the existing machinery of forecast weight optimisation:
Carry in pink ends up with quite a big weight most of the time, due to it's diversification. However the astonishing post COVID drop in performance then reduces it's weight somewhat.The above plot again shows the backtested performance with time varying forecast weights. Adding carry has made things worse. At this point the traditional backtesting decision would be to kill this new fangled 'carry' idea, and move on to the next one. Of course there are different ways this story can be told, with for example old school in sample/out of sample testing, sensitivity analysis, Whites Reality Check to correct for multiple tests.... however all these have the same ending. This is still a test-keep/kill process.
Here is our second big mistake. We have implicit fitting. We are using information that would not have been available in 1982 to make a decision: to kill carry. That decision has been made using performance not available until 44 years after 1982. The fact the performance is derived using nice out of sample rolling fitting is irrelevant.
There is a more subtle, third mistake, that is evident in this particular test. The final weight for carry in the backtest is positive (and would be for almost any optimisation except one with inappropriately low SR shrinkage, or an inappropriately short rolling window). So we are ignoring the information given to us by the carefully calibrated robust fitting process and setting the weight of carry to an arbitrary value of zero.
That won't always be true - sometimes the final weight to the new variation(s) will be zero anyway. In this case your final trading strategy will end up being the same with no carry actually surviving into your production system, but your past backtest results will still be inflated by future information.
True Backtesting
Now let's repeat the above cycle, but this time we're going to use True Backtesting. In an ideal world, we wouldn't have any pre concieved trading rules at all. Instead we'd have highly general rules that could exhibit almost any behaviour given a set of parameters. There are possible ways of this happening with e.g. genetic algorithims, but personally I find the loss of intuition and control of fitting process to be too scary. Thus we're going to have to start with a simple trading rule like EWMAC with a couple of parameters. This does require tacit knowledge, but as I will shortly explain the use of symmetrical backtesting will alleviate the effect of this knowledge on backtest performance.
However this time we won't specify the ratio N, 4N; instead we'll just use EWMAC X, Y. This still leaves us to set the bounds for X and Y, and the granularity within those bounds. We want to set these without using real data, or that would be implicit fitting. The information we require to set these bounds is:
- Correlation - we want to reject highly correlated pairs like EWMAC22,44 and EWMAC23,44
- Turnover - we want to reject pairs that trade too quickly for our instrument, and those with very slow turnover since (i) under the law of active management they will have very low profitability, (ii) it's unlikely we'll able to evaluate their performance with any statistical confidence.
We do not need, and should not use, performance statistics for these decisions. We can do this in three ways:
- Using theory (not always possible, but if you assume a random walk you can certainly do this with EWMAC)
- Using 'fake data' as discussed here
- Using a small amount of real data from the start of the backtest. Since we use the first year of data to calculate the initial forecast weights, this period could also be used to calibrate rules. I call this the burn in period. When evaluating performance it should be excluded from the backtest.
Other approaches I have used in the past include using a longer sample of a single instrument for calibration. Again, this is not in the spirit of True Backtesting where we try and avoid using any forward looking information at all costs.
Using a combination of theory and fake data, I set the possible values for both X and Y as follows: 2, 4, 8, 16, 32, 64, 128, 256. That's a series of doubling values, since that gives approximately constantly spaced correlations between adjacent values (we can show this with theory, but fake or burn in data will give similar results). SP500 is cheap, so we can use small values of X and Y. Anything above 64 leads to turnover that is too slow (I used fake data to find this result; again burn in data will also do, whilst theory requires too many price structure parameters to be calibrated).
I'm also going to constraint Y>X. This means we only consider trend following rules. If I took away this constraint I could also test the opposite: mean reversion (If you take EWMACX,Y and reverse it, you have EWMACY,X. So reversing is equivalent to swapping the parameters round which is possible without the Y>X constraint). However I'm going to use the more general method of symmetric backtesting to test out mean reversion strategies, since this option of using the parameters to generate a negative variation isn't always possible (not with carry for example).
This gives us 28 possible pairs of X and Y. I won't plot their performance, since it's a mess - a graph that's mostly legend. But here's the SR for each variation over the full sample:
Anyway, with all that in mind, for consistency and simplicity let's do a robust 20 year rolling out of sample MVO that uses SR shrinkage 0.5, correlation 0.75 with more conservative shrinkage if there is less than five years of data.
Importantly however, this is going to be a symmetric backtest. For each optimisation we follow the following procedure:
- If a given trading rule variation has negative p&l in the rolling period before costs, then we reverse the sign of it's forecasts and thus it's pre cost p&l will become positive.
- Costs are then deducted. There may be some expensive variations that have a negative p&l after costs, but most will be positive p&l.
- We then do the optimisation. In the optimisation as usual we don't allow negative weights; this would be highly problematic here since even after shrinkage the reversed forecasts are probably highly negatively correlated with other variations, resulting in potentially extreme positive and negative weights were they allowed.
- Any rule we had to reverse then has it's forecast weight reversed.
(This also means that weights don't add up to 1. This isn't a problem, as we can access leverage it's actually irrelevant what our weights add up to)
An important point here is that this goes against what I, and many others, have preached before. Which is that you should use ideas first testing where ideas have an economic hypothesis behind them. A hypothesis can then be proven, or disproved. If disproved, we don't go off and use the exact opposite rule, which would go against our original idea! But with symmetric fitting we allow ourselves to do this. This doesn't mean that we shouldn't start with an idea or hypothesis with theory behind it. But that hypothesis will inevitably be contaminated with future information. Therefore we should test the opposite idea as well, at least initially, to ensure the backtest is done fairly without knowing about the future.
Anyway, to show the time series of all these forecast weights would be tiresome; so here are the final values:
8 of the 28 weights are negative - mean reversion. These are mostly quicker pairings. How does the total performance shake out?Overall this isn't as profitable over the entire time series as the backtest above. There is a longer 'learning' period when it loses money as it's still allocating to unprofitable variations. But after 1995 it's performance is far more consistent. This is because the symettric True Backtest allows EWMAC to trade mean reversion at some faster frequencies, which for SP500 turns out to be profitable. That won't always be the case; if for example we examined an instrument that consistently made money in all the original six EWMAC pairings (but did badly in everything else) then the symettric backtest with 28 pairs will look worse for longer, and may never 'learn' that the six pairings are the best.But the important point here is that the original test was tainted by tacit information. Here we've made that significantly less of an influence. Yes we need to know that eithier trends or mean reversion work, and yes we need to know that EWMAC can detect trends. But that doesn't require any forward looking information.
Now as before, let's add carry. As I already noted it's possible to specify a futures carry model just from theory, with just one parameter to select, and the choice of a smooth parameter of 10 could easily be made with a short burn in period. I could of course do things properly and have multiple smooths, as I do in my current trading system, but because the smoothed carry variations are so correlated it will hardly change the results. So let's keep things simple, even though in a super strict True Backtest we'd certainly include a number of carry variations.
I won't show the forecast weights, but again carry ends up with a weight of around 6% at the end of the backtest. Since it had a positive weight before (around 10%), symmetry doesn't effect the sign of the weight (though obviously it will change the magnitude a little due to the inclusion of more positive, reversed, forecasts).
Now, as it happens, on this occasion the overall performance is almost unchanged whether carry is included or not. In a previous incarnation I'd probably say 'go with the simpler option unless performance is significantly better - kill carry'. But we are now True Backtesting. So, irrespective of the performance after including carry:- We will not 'kill' carry
- Going forward the trading strategy we use will have the final forecast weights, which include carry as a strategy (with a 6% weight).
- This will remain the case until a future re-fit ends up giving carry a zero weight (if it's performance continues to be poor - of course it's likely at that point we'll give it a negative weight).
- Carry will stay in our backtest forever even if it ends up with a zero weight in the future. Our backtest is now write only.
Hopefully you can now see that we're avoiding the second mistake - killing carry is implicit fitting; and the third mistake - we're not setting the weight of carry in our live model to an arbitrary level of zero.
Note that whenever we run another backtest adding another rule with another set of variations we're not making it more likely we'll find a winning strategy which we trade to the exclusion of everything else, thus obviating the need for multiple testing. Instead of multiple backtests, we have multiple vintages of a single backtest. Earlier vintages have an incomplete set of the possible universe of trading rules. Later vintages include more of the trading rules in the possible universe. As long as those rules were concievable at the start of the backtest, with parameters yet to to be discovered, that's absolutely fine. Whilst that's unrealistic in practice, the use of symettry means the use of tacit information will be much less dangerous.
One final important point to make is this: a backtest has several purposes, which partially contradict each other, and which a single type of back test cannot give you:
- It shows you how well you could have done trading a strategy in the past
- It tells you the (expected) best strategy to trade from this point onwards
- It advises you of the behaviour of your strategy in the future
We can see the strategy slowing down as we deallocate from the quicker markets after 1995. To get an idea of likely turnover and other characteristics like return skew, we'd have to run a backtest with the final forecast weights held right from the start. But the performance of that backtest will be inflated by in sample fitting, and shouldn't be used to make any evalulation or assumptions about performance. In particular, optimal leverage, p&l available to pay trading costs, and expected drawdown should not be derived from the in sample test - use the True Backtest for those.




























