About

An underrated feature of Metatrader's Backtester is its ability to define a custom fitness function for the genetic optimization process. Meaning that you no longer are limited to rather simple metrics like final balance or profit factor but can evaluate the quality of each test run with your own individual calculations.To give a quick overview of what is possible, we will be creating a custom fitness function that is optimizing for the 'straightness' of the equity curve using Lars Kestner's K-Ratio (1996).

K-Ratio

The K-Ratio is a statistical metric with an emphasis on consistency of returns, introduced by Lars Kestner in 1996 [1]. It has since then also been adapted by Zephyr Associates under the name “Zephyr K-Ratio” [2]. Having multiple different Equity curves, yielding the same amount of profit, the K-Ratio will prefer the curve with the most consistent gains (maximum smoothness).

Naturally, most investors also prefer a smooth equity curve over higher profits with deeper drawdowns. So the K-Ratio seems a promising metric to use for our optimization process. The k-ratio is defined as:

Simply speaking, we are drawing the best-fit line through our equity curve and divide the slope of this regression line through its standard error. Doing so, the numerator is becoming the profit component of the fraction and the denominator is representing the risk part.Additionally, this method favours curves with higher profits (increasing the slope) and a bigger number of trades (decreasing standard error). Generally speaking, the highest K-Ratio represents the smoothest equity curve (considering profit and number of trades).

When implementing this measure in Metatrader’s optimization process we have to take into account that we are only considering closed trades and therefore discard intra-trade drawdowns for simplicity reasons. In order to punish equity curves with big floating drawdowns, we are imposing a drawdown penalty on the k-score.

In order to reject insignificant test runs, we will also be applying an automated minimum sample size calculation, taking into account timeframe and duration of the backtest.

Sample Size Calculation

Let’s start with a simple sample size calculator. By doing a backtest/optimization for our trading algorithm we are trying to verify the assumptions we made, while creating this algorithm, against historical data. Following this logic, we are viewing the bars in this backtest as our population size and the resulting trades as samples. This assumption allows us to apply the sample size determination using z-scores known from statistics [3]. As a consequence, we simply need to define the confidence level and a margin of error to automatically retrieve the minimum number of trades in order to consider a test run for further analysis. We are using Cochran’s sample size formula for finite populations [4].

Metatrader K-Ratio Implementation

Having defined our minimum sample size, we are now going forward creating the k-ratio function. If we define the OnTester() function in MetaTrader, the optimizer is using the result of this function as the input value for its genetic optimization process.Inside the OnTester() function we are looping through all orders of the backtest in order to rebuild the equity curve into an array of doubles (k_profit) for later calculations. While doing so, we also convert the absolute returns to log returns in order to work with normalized values which are required for the following calculations.

As stated earlier we are calculating the k-ratio by dividing the slope of the regression line by its standard error. So let’s first calculate the slope of this best fit line through our equity curve.

In MQL we are summing all x-values (index points) and y-values (accumulated log profit) while looping through the orders in order to get the arithmetic mean afterwards.

Testrun

Now let’s put our code into action by including our k-ratio.mqh into the MACD Sample EA that comes with MT5. Afterwards, we start an optimization run over a 1-year period. In order to tell Metatrader to use our custom fitness function, we just have to choose “custom max” from the drop-down in the strategy tester.

Below are two equity curves with similar profits but with very different k-ratios.

Final Thoughts

We have seen that by using Metatrader’s custom fitness function, we can create very flexible optimization runs. This article doesn’t intend to illustrate k-ratio as the single best metric for evaluating trading strategies, as it has certain drawbacks as well.For one, you need a sufficient number of trades to get meaningful results as the k-ratio is pretty loss averse. Secondly, the k-ratio doesn’t tell you everything about the chronological consistency of the trades. We would prefer to have the trades distributed pretty evenly over our backtest. However, we can’t see from the k-ratio if all trades happened within one month or steadily over the whole backtest.

There are ways around this issue by calculating equity checkpoints at fixed time intervals in order to create a “time-conscious” equity curve. If we use small enough timespans, this would also allow us to refrain from having to use a drawdown penalty as the floating equity would already be included. However, depending on the number of checkpoints, this calculation will slow down the backtest quite a bit.

You could also combine the k-ratio with other metrics into a custom proprietary score to get a more nuanced picture of each test run.

CFDs are complex instruments and come with a high risk of losing money rapidly due to leverage. 73 % of retail investor accounts lose money when trading CFDs with this provider. You should consider whether you understand how CFDs work and whether you can afford to take the high risk of losing your money.