Algorithmic Trading Tips 14.

# MAXIMIZE PROFITS USING THE KELLY FORMULA.

### HOW TO OPTIMIZE THE POSITION SIZE OF YOUR INVESTMENTS SYSTEMATICALLY.

In order to maximize profits and reduce risks, the position size should always be defined depending on the quality of a trading strategy. In the present issue we show how the method developed by John Kelly works and how you can test it in Tradesignal by using the supplied Equilla codes.

WATCH VIDEO NOW. (6 minutes to improve your performance.)

LOAD WORKSPACE. (For users with Thomson Reuters.)

LOAD WORKSPACE. (For users with Bloomberg.)

#### By downloading you agree to the terms of use below.

## PROLOGUE.

Statement from Jörg Scherer, Head of Technical Analysis at HSBC Germany.

*Mr. Scherer, you have been working for many years in technical analysis. What are the advantages of this approach compared to fundamental methods?*

**Scherer**: Technical analysis is based on the premise that markets move in trends, that all the information is already included in the price and that the future has similarities with the past. It`s about using recurring patterns that result from mass psychological phenomena for profitable trading decisions.

*What is particularly important in the use of technical analysis in practice?*

**Scherer**: Technical analysis is not a holy grail, there are false signals and thus losses in trading. The preservation of capital should come first for any trader and investor! In other words: You have to take care of the losses, so that you survive drawdown phases – which inevitably occur – and then can continue to act. This is difficult for many market participants, because emotional factors such as fear and greed cloud decisions – such as closing a losing position – stand in the way. For this reason, it is always worthwhile to deal in detail with risk and money management.

*Which method to control position size do you favor?*

**Scherer**: There are of course many different money management approaches and each has its advantages and disadvantages. One thing that all methods have in common: If a trading strategy runs successfully, the capital amount is increased. If losses occur, the use of capital is systematically reduced. It is an anti-martingale strategy. The majority of market participants do the exact opposite: stakes are raised when things go bad. A good money management strategy takes care of two things: the preservation of capital and maximizing profits. So it not only ensures a better risk-return ratio, but also leads to more discipline in trading.

*John Kelly has done pioneering work in this field – what do you think of the Kelly formula?*

**Scherer**: The Kelly criterion, which was originally developed for gambling after decades has many followers and deservedly so. It takes into account explicitly the quality of a trading approach and thus provides an active position sizing. While this is associated with work, because again arises requiring adaptation portfolio – On balance, the implementation is always worthwhile, because especially bear markets can be mitigated or avoided. Over an entire market cycle the Kelly criterion enables an outperformance on a regular basis.

*Thank you, Mr. Scherer, for your opinion.*

## MAXIMIZE PROFITS USING THE KELLY FORMULA.

### HOW TO OPTIMIZE THE POSITION SIZE OF YOUR INVESTMENTS SYSTEMATICALLY.

The goal of every investor is obvious: in bull market phases one should be invested, in bear market phases, however, the exposure should be reduced to a minimum. In this Trading Tips issue, we want to show how to achieve this goal by an innovative use of the Kelly formula.

### Not too big, not too small – the question of optimal position size.

Before we go into practice, a simple dice game is used to underline the importance of position size dependant on the slope of the equity curve. The following rules apply:

- Player A receives 100 euro starting capital.
- Then, the dice are rolled.
- If the dice shows a number greater than 2, player A gets back his bet at double.
- If the dice shows 1 or 2, however, the player loses his bet.

In this situation it is a game that Player A cannot lose from a statistical point of view, the chances of winning on each roll, are 4 to 2 to his benefit. He may lose this game only if he relies too much on this advantage and thus can`t cope with a losing streak (drawdown). The higher the wager, the higher the risk of ruin. On the other hand, too small a bet likewise isn`t the perfect solution because it does not take advantage of the attractive chances given by this games rules.

The crucial question in this dice game – and also when using algorithmic trading strategies – is therefore:

**HOW MUCH SHOULD BE RISKED TO GENERATE A MAXIMUM CAPITAL GROWTH?**

### The Kelly criterion.

At this point, the ingenious solution of John Kelly, Jr., comes into play. In 1956, the scientist occupied himself with the question whether it is possible to calculate the ideal bet for such a game*. While he didn‘t have the stock market in mind at the start, Kelly and others discovered its relevance for the financial markets soon after. Kelly found a simple relationship with which the optimal fraction of the risk capital can be determined for a maximum profit growth. The essence of the Kelly formula is: The higher the statistical advantage, the lower the risk and so the higher the recommended position size.

The formula for calculating the ideal capital investment to maximize profit is as follows:

An interesting comparison of Kelly and Markowitz portfolio optimization can be found in the following blog post by Ernie Chan, speaker and author of several books on the topic “Algorithmic Trading”.

On closer inspection, this formula allows us to derive the following key statements:

- The higher the probability of winning, the higher the percentage of capital should be used and vice versa;
- The higher the ratio between average win and average loss, the higher the percentage of capital should be used and vice versa.

In the dice game mentioned above, the probability of winning is 67 percent, since four of six possible events (4/6 = 67 percent) lead to a win. The loss probability is 34 percent (100 percent-66 percent). The average gain is as high as the average loss, hence the ratio is equal to 1. Setting the numbers into the formula, we obtain the following result: 67 – (34: 1) = 33

This means that in order to gain the maximum benefit you should risk 33 percent of your available capital on the next dice roll or trade. Figure 1 shows the aggressiveness of the Kelly position sizing system.

In particular, if the probability of winning and/or the win-loss ratio reaches high values, the Kelly criterion recommends exorbitantly high position sizes that, due to the risk, are anything but sensible in the professional investment world.

FIG. 1: POSITION SIZE MATRIX BY KELLY.

The Kelly criterion is calculated based on the probability of winning (Win%) and the ratio between the average win and loss. It shows the ideal position size to maximize profits.

### Implementation of portfolio management.

Although the Kelly criterion is undoubtedly too risky as a tool to control position size, the concept behind it still provides valuable insights for portfolio management. We would like to introduce to you an innovative way to use this formula. The idea behind it: Instead of a dice roll, now the historical price trend of a stock serves as calculation basis for the ideal position size.

Before we present the practical implementation and the associated Equilla codes, a brief foray serves to illustrate the idea in more detail. For this purpose, the buy-and-hold approach is to be understood as a series of individual virtual trades. If a stock is held, for example, for five days, and its price increases over this period from 100 to 105, the traveled path could be very different. Figure 2 shows an example of the progression of stock A and stock B.

**IN WHICH STOCK ONE SHOULD INVEST MORE CAPITAL?**

FIG. 2: HYPOTHETICAL PRICE DEVELOPMENT OF TWO STOCKS.

calculation of the ideal position size, the Kelly criterion takes into account the ratio of positive to negative periods and the relationship between average win and loss for each period. While both stocks rise by the same amount, stock A is preferable due to the lower drawdowns and higher winning percentage and should be weighted higher than stock B in a portfolio.

Compared to the stock B, stock A has a high winning percentage (increase in 4 of 5 trading periods), at the same time losses are considerably lower. So share A is preferable of share B. From the perspective of the Kelly criterion the choice also falls on stock A, because the expected value is higher here.

Of course, a time frame of only five periods is too short to draw conclusions on the level of the ideal weight – but what if you choose e.g. one year as the observation period?

## Calculation example & Equilla code.

Looking at the weekly price changes of a stock similar to a profit-loss curve of a dice game, one can derive the ideal positions size by using the Kelly formula. Take a look at the following example which applies a observation period of 54 weeks for the calculation.

**EXAMPLE:**

29 positive weeks and 25 negative weeks

**WINNING PROBABILITY = 29/25 = 53,7%**

In the next step the indicator calculates the average result in profit and loss, resulting in the win-loss ratio.

**EXAMPLE:**

Average profit during positive weeks: 0,226 Euro

Average win / loss ratio: 0,251 Euro

**AVERAGE WIN / LOSS RATIO: 0,90**

Using these two numbers the optimal position size for each predetermined risk can be calculated.

**EXAMPLE:**

Position size as percentage of trading capital

= %Win – [ %Loss / (avg.Win/avg.Loss)]

**53,7-[46,3/0,9] = 2,25 %**

If the risk capital for this stock amounts 100,000 Euros, the position size is calculated as follows:

**EXAMPLE: **

100.000 Euro * 0,0225 = 2.250 Euro

Average weekly loss = 0,251 Euro

**RECOMMENDED POSITION SIZE = 8.964 SHARES**

Should the statistical values deteriorate in the future, the Kelly formula would recommend to reduce the number of shares to be held. With a strong upward trend, the number of shares, however, is greatly increased due to the improved hit ratio and profit-loss ratio. The following indicator therefore does nothing more than look at the stock price history as a sequence of dice rolls. Based on the performance of last year (54 weeks) the Kelly indicator each week calculates the ideal share number for the following week.

The following indicator therefore does nothing more than look at the stock price history as a sequence of dice rolls. Based on the performance of last year (54 weeks) the Kelly indicator each week calculates the ideal share number for the following week.

meta: shortcode("Kelly"); Inputs: Lookback(54),Capital(1000), Show_me(Positionsize,KellyNumber, WinLose),Long_only(true); Var: i(0), numwin, numlose, win, lose, sumwin, sumlose; Var: avwin, avlose, percentwin,riskpercent, sharestohold; Var: global::kellyshares;

// The Kelly number is calculated based on Lookback bars

If Lookback>0 then begin

numwin=0;

numlose=0;

win=0;

lose=0;

sumwin=0;

sumlose=0;

avwin=0;

avlose=0;

riskpercent=0;

for i=0 to Lookback-1 begin // calculation of winning/losing probability, average loss and average win

if close[i]-close[i+1] > 0 then begin // profit

numwin=numwin+1;

win=close[i]-close[i+1];

sumwin=sumwin+win;

if numwin<>0 then avwin=sumwin/numwin else avwin=0;

end;

if close[i]-close[i+1] <= 0 then begin // loss

numlose=numlose+1;

lose=-1*(close[i]-close[i+1]);

sumlose=sumlose+lose;

if numlose<>0 then avlose=sumlose/numlose else avlose=0;

end;

end;

percentwin=numwin/Lookback; // percentage of winning bars

if avlose<>0 and avwin<>0 then riskpercent=(percentwin((1-percentwin)/(avwin/avlose)))else riskpercent=0; // Kelly Formel

end;

// for Lookback=0 the kelly number is calculated based on the whole data history

If Lookback=0 then begin

if isbarone then begin

numwin=0;

numlose=0;

win=0;

lose=0;

sumwin=0;

sumlose=0;

avwin=0;

avlose=0;

riskpercent=0;

end;

if close-close[1] > 0 then begin // profit

numwin=numwin+1;

win=close-close[1];

sumwin=sumwin+win;

if numwin>0 then avwin=sumwin/numwin else avwin=0;

end;

if close-close[1] <= 0 then begin // loss

numlose=numlose+1;

lose=-1*(close-close[1]);

sumlose=sumlose+lose;

if numlose>0 then avlose=sumlose/numlose else avlose=close;

end;

if numwin>0 then percentwin=numwin/(numwin+numlose) else percentwin=0;

if avlose<>0 and avwin<>0 then riskpercent=(percentwin((1-percentwin)/(avwin/avlose))) ;

// kelly formula

end;

if avlose>0 then sharestohold=round(Capital*riskpercent/avlose,0);

// calculation of shares for defined risk capital

if Show_me=positionsize then drawline(iff(Long_only,maxlist(0,sharestohold),sharestohold),"sharestohold");

if Show_me=KellyNumber then drawline(iff(Long_only,maxlist(0,100*riskpercent),100*riskpercent),"KellyPercent");

if Show_me=winlose then begin

drawline(avlose*numlose,"%lose*avglose",StyleSolid,1,red);

drawline(avwin*numwin,"%win*avgwin",StyleSolid,1,darkgreen);

end;

FIGURE 3: EQUILLA CODE OF THE KELLY INDICATOR.

The Kelly indicator calculates the ideal position size (number of stocks) for a freely selectable risk capital by using the Kelly formula.

For a description of the indicator and the availability of inputs, we consider the Adidas weekly chart. The setting of the parameters is as follows:

- Lookback:
**54**(The calculation is based on the performance of the last 54 weeks) - Capital:
**1.000**(1000 Euro risk per week) - Show_me: Position Size (position size)

Further options:

**Kelly-Number**(recommended position size in percentage of trading capital)

**WinLose**(positive vs. negative periods during the observation period) - Long_only:
**True**(calculation and display of the position size takes place on long basis, ie short position sizes will not be displayed)

**FIG. 4: WEEKLY CHART (OBSERVATION PERIOD OF 54 WEEKS) WITH KELLY COMPONENTS.**

The position size (orange) is calculated as a function of historical hit ratio and win-loss ratio and is adjusted for each new period.

Figure 4 shows the recommended number of shares (orange) to be held when the Kelly formula is being applied. The number of shares rises the stronger the trend becomes (see Figures 2 and 3). If the trend weakens or there are any unexpected adverse events, a portion of the position is closed (1). In sideways and downward phases (4) the Kelly approach holds the portfolio manager far from the market as was the case between May 2008 and October 2009, for example. In 2014, the Kelly indicator proved to be an effective tool: Since the end of March, the weighting of the Adidas stock stands at nil. A long position will only be rebuilt when signs of a strong upward trend reemerge.

### Too much of a good thing?

In view of the aforementioned benefits one disadvantage cannot be hidden. Originally the Kelly formula was not designed for the financial markets, but to calculate the optimal bet size in poker games. The difference between financial markets and games like poker is that the maximum loss is exactly known in poker. For this reason we assume that the maximum loss for each stock is equal to its average weekly loss. By using the Kelly criterion as it was shown here, the position size can go up to the maximum (see fig. 1) when the underlying stock has only a few loss weeks during the observation period. Finally, the formula assumes a “bet” on this stock will not lose and therefore concludes that a very high percentage of capital should be risked on the next trade. This assumption requires a limitation of position size. The solutions here are:

- Manual limitation of the maximum position size, because the Kelly formula does not take into account the available capital
- fixing a minimum risk

### Putting the Kelly-position sizing strategy to the test.

If the Kelly formula makes sense, then it should be proven by using a back test. The following Equilla code can be used as a trading strategy on your Tradesignal workstation, and provide answers. The trading strategy calculates the ideal position size of stocks recommended by Kelly. The buy and sell instructions at the end of the code are used for the periodic adjustment of each position.

For correct execution of the strategy, the following settings for the position size must be defined in the money managment section.

FIG. 5: MONEY MANAGEMENT SETTINGS.

For the correct application of the Kelly strategy the pyramiding option must be enabled, while the maximum number of open entries has to be set to 10000 or higher.

Inputs: Lookback(54),Capital(1000),Lot(10,1),Long_only(true); Var: i(0), numwin, numlose, win, lose, sumwin, sumlose; Var: avwin, avlose, percentwin,riskpercent, sharestohold, wunsch;

// The Kelly number is calculated based on Lookback bars only

If Lookback>0 then begin

numwin=0;

numlose=0;

win=0;

lose=0;

sumwin=0;

sumlose=0;

avwin=0;

avlose=0;

riskpercent=0;

for i=0 to Lookback-1 begin // calculation of winning/losing probability, average loss and average win

if close[i]-close[i+1] > 0 then begin // profit

numwin=numwin+1;

win=close[i]-close[i+1];

sumwin=sumwin+win;

if numwin<>0 then avwin=sumwin/numwin else avwin=0;

end;

if close[i]-close[i+1] <= 0 then begin // loss

numlose=numlose+1;

lose=-1*(close[i]-close[i+1]);

sumlose=sumlose+lose;

if numlose<>0 then avlose=sumlose/numlose else avlose=0;

end;

end;

percentwin=numwin/Lookback; // percentage of winning bars

if avlose<>0 and avwin<>0 then riskpercent=(percentwin-((1-percentwin)/(avwin/avlose)))

else riskpercent=0; // kelly formula

end;

// for Lookback=0 the kelly number is calculated based on the whole data history

If Lookback=0 then begin

if isbarone then begin

numwin=0;

numlose=0;

win=0;

lose=0;

sumwin=0;

sumlose=0;

avwin=0;

avlose=0;

riskpercent=0;

end;

if close-close[1] > 0 then begin // profit

numwin=numwin+1;

win=close-close[1];

sumwin=sumwin+win;

if numwin>0 then avwin=sumwin/numwin else avwin=0;

end;

if close-close[1] <= 0 then begin // loss

numlose=numlose+1;

lose=-1*(close-close[1]);

sumlose=sumlose+lose;

if numlose>0 then avlose=sumlose/numlose else avlose=close;

end;

if numwin>0 then percentwin=numwin/(numwin+numlose) else percentwin=0;

if avlose<>0 and avwin<>0 then riskpercent=(percentwin-((1-percentwin)/(avwin/avlose))) ;

end;

if avlose>0 and lot>0 then sharestohold=round(Capital*riskpercent/avlose/lot,0)*Lot;

if Long_only then wunsch=maxlist(0,sharestohold) else wunsch=sharestohold;

if wunsch>=0 then begin

if marketposition<1 and Wunsch>0 then buy ("Initial Entry") Wunsch contracts this bar on close;

// no position

if marketposition=1 and Wunsch>currentcontracts then buy ("Buy") (Wunsch-currentcontracts) contracts

this bar on close; // buy additional contracts

if marketposition=1 and Wunsch<currentcontracts then sell ("Sell") (currentcontracts-wunsch) contracts

total this bar on close; // sell surplus contracts

end;

if wunsch<0 then begin

if marketposition>-1 and Wunsch<0 then short ("Initial SEntry") -1*Wunsch contracts this bar on close;

// no position

if marketposition=-1 and Wunsch<currentcontracts*marketposition then short ("Sell")

(-1*Wunsch-currentcontracts) contracts this bar on close; // buy additional contracts

if marketposition=-1 and Wunsch>currentcontracts*marketposition then cover ("Buy")

(currentcontracts-(-1*wunsch)) contracts total this bar on close; // sell surplus contracts

end;

FIG. 6: EQUILLA CODE FOR KELLY POSITION SIZE STRATEGY.

The trading strategy after each period calculates the optimal position size for the given risk capital.

This procedure for position sizing provides respectable results for portfolios with many individual shares – across all market phases. Figure 6 shows the performance of the DAX 30 stock basket, if you’re willing to risk up to 1000 Euros per week in each underlying stock. As expected, it is heavily invested in bull markets; In the 2000-2003 bear market however, the equity curve is flat, as Kelly does not invest when the winning probability is negative.

FIG. 7: EQUITY CURVE FOR DAX STOCK BASKET USING THE KELLY POSITION SIZE STRATEGY.

The dynamic control of the position size by using the Kelly criterion ensures that investors benefit from strong trend phases, while weak and negative phases are largely avoided.

If the recommended number of stocks changes, then the position size will be adjusted at the market open next week. You can see how the process works in practice: In strong bull phase positions are built up quickly. This can be recognized as the orange line for the open profits is rising fast, while the blue line for the closed profits remains unchanged. If the market crashes very quickly, only a part of the open gains can be realized and a significant part of the accrued profits are given away (as in 1998). In the 2000-2003 bear market, traders and investors using the Kelly formula largely remained away from the market. The same is true for the bear market from mid-2007 to early 2009.

Figure 8 shows the same procedure applied to the MDAX and this time using daily data and daily adjustment of the position size. Again, the Kelly criterion has done a good job. Whether the rebalancing of portfolios is performed weekly or daily, does not seem to be of high importance, this also applies to the length of the observation period.

FIG. 8: EQUITY CURVE FOR MDAX STOCK BASKET USING THE KELLY POSITION SIZE STRATEGY.

The dynamic control of the position size also shows the MDAX good results, thus demonstrating the effectiveness of the Kelly criterion as a trend indicator.

### Kelly – a creative trend indicator.

The results presented here confirm that the innovative application of the Kelly criterion offers promising opportunities for the development of trading strategies. The goal of creating an absolute return equity basket has been achieved: Weak market phases left the portfolio unscathed and strong uptrend could be used for generating Alpha. With the flexible programming language Equilla you can translate all ideas into action – entering unconventional paths is worthwhile and can yield surprising results.

Try the Kelly criterion on your workstation today and download the indicator, but also a prefabricated workspace with Reuters and Bloomberg shortcuts for free.

That`s it for today – take care, take profit.

Philipp Kahler

### DISCLAIMER.

© Copyright Tradesignal Ltd., London.

Distribution allowed under a Creative Commons Attribution-Noncommercial license

http://creativecommons.org/licenses/by-nc/3.0/

Tradesignal® is a registered trademark of Tradesignal GmbH. Unauthorized use or misuse is specifically prohibited. All other protected brands and trademarks mentioned in this document conform, without restriction, to the provisions of applicable trademark law and the copyrights of the respective registered owners.

Tradesignal Ltd. obtains information from sources it considers reliable, but does not guarantee the accuracy or completeness of its information contained therein. Tradesignal Ltd. and its affiliates make no representation or warranty, either express or implied, with respect to the information or analysis supplied herein, including without limitation the implied warranties of fitness for a particular purpose and merchantability, and each specifically disclaims any such warranty. In no event shall Tradesignal Ltd. or its affiliates be liable to for any decision made or action taken in reliance upon the information contained herein, lost profits or any indirect, consequential, special or incidental damages, whether in contract, tort or otherwise, even if advised of the possibility of such damages. This material does not constitute an offer or a solicitation of an offer or a recommendation to buy or sell securities. All expressions of opinion are subject to change without notice.

This code is provided free of charge and “as is”, without warranty of any kind, express or implied, including but not limited to the warranties of fitness for a particular purpose and noninfringement. In no event, shall Tradesignal Ltd. be liable for any claim, damages or other liability, whether in an action of contract, tort or otherwise, arising from, or of or in connection with this code or the use of this code.

.