Click here to Skip to main content
15,888,600 members
Articles / Programming Languages / C#

The Kelly Criterion in C#

Rate me:
Please Sign up or sign in to vote.
5.00/5 (3 votes)
14 Aug 2014CPOL 10.1K   4   5
The Kelly Criterion in C#

Given a bank roll, a stake you have already bet and a potential pot of winnings, the Kelly Criterion should calculate for you the optimal amount you should bet to maximize your winnings in the long run.

So, here’s what looks like a trivial piece of code, but is actually quite powerful:

C#
public class KellyEvaluator
{
private decimal proportion;
public KellyEvaluator(decimal proportion = 1.0M)
{
this.proportion = proportion;
}

public decimal MaxBankRoll(decimal bankRoll, decimal pot, decimal stake, decimal ourWinPercentage)
{
return bankRoll * MaxFraction(bankRoll, pot, stake, ourWinPercentage);
}

//given our current bankroll, a pot, an amount we’ve already staked, 
//our win percentage and the mean for the # of players,
//what is the maximum value we should allow ourselves to bet?
public decimal MaxNormalisedBankRoll(decimal bankRoll, decimal pot, decimal stake,
decimal ourWinPercentage, decimal meanWinPercentage)
{
return bankRoll * 
MaxNormalisedFraction(bankRoll, pot, stake, ourWinPercentage, meanWinPercentage);
}

//given a win% and an amount we’ve already staked, whatis the max we can bet
public decimal MaxNormalisedFraction(decimal bankRoll, decimal pot, decimal totalStaked,
decimal ourWinPercentage, decimal meanWinPercentage)
{
decimal f = 0.0M;
decimal proposedBet = bankRoll;
decimal max = 0.0M;
while (proposedBet > 0.0M)
{
f = NormalisedFraction
(bankRoll, pot – totalStaked, proposedBet, ourWinPercentage, meanWinPercentage);
if (f >= 0.0M)
max = f;
proposedBet -= 1.0M;
}

return max;
}

//given a win% whatis the max we can bet
public decimal MaxFraction
(decimal bankRoll, decimal pot, decimal totalStaked, decimal ourWinPercentage)
{
decimal f = 0.0M;
decimal proposedBet = bankRoll;
decimal max = 0.0M;
while(proposedBet > 0.0M)
{
f = Fraction(bankRoll, pot – totalStaked, proposedBet, ourWinPercentage);
if (f >= 0.0M)
max = f;
proposedBet -= 1.0M;
}

return max;
}

private decimal NormalisedFraction(decimal bankRoll, decimal potentialWinnings, decimal ourStake,
decimal ourWinPercentage, decimal meanWinPercentage)
{
decimal delta = ourWinPercentage – meanWinPercentage;
decimal edgePercentage = delta / meanWinPercentage;

return Fraction(bankRoll, potentialWinnings, ourStake, edgePercentage);
}

private decimal Fraction(decimal bankRoll, decimal potentialWinnings, 
                         decimal ourStake, decimal ourWinPercentage)
{

//b:1 i.e., if pot is 100 and call value is 20 and we’ve staked nothing else so far, then 5:1
decimal b = potentialWinnings / (ourStake);
decimal f = ((b * ourWinPercentage) – (1 – ourWinPercentage)) / b;

return f * proportion;
}
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Technical Lead Alpha Integralis Limited
United Kingdom United Kingdom
CatchExAs aka Nick Wilton runs Alpha Integralis, a software development consultancy to companies in the City of London.

Main interests include exploring Algo-Trading, Quant Development and Physics using C# and Java.

www.nickwilton.info/Blog

Comments and Discussions

 
QuestionSmall question Pin
Alexey KK14-Aug-14 22:40
professionalAlexey KK14-Aug-14 22:40 
Good day!
This formula is always discussed. But it is based on serie of profits and losses of the same size. If i remember right it was developped in Bells Laboratories and the main purpose was to avoid or minimize connection delays and errors.
But in theory there is much more powerfull set of rules called Optf and based on maximizing geometrical mean of returns even better than also known sharp ratio. This Optf gives same results as Kelly for same size serie of P/L's but where you ll find serie of profits/losses of the same size? So it s developed for series of different sizes of profits and losses. Main idea and result of this optf - the difference even in 3% from optimal bet size gives significal error(or better say difference in net returns) and worse angle of equity line. As for my opinion positive angle of equity curve with small drawdowns is the most important thing. OptF gives it together.
There is no exact formula - there are only some computing algorithms.
As for poker (the most known decision making based on fuzzy informatioin) - in mostly tournaments you have no choice of optimal bet size - on weak table - overbetting, hard tables - something like not convenient odds for opponent predicted hand, sometimes pushh and that's all and when you do preflop analysis before participating in hand you mostly think of current and potential odds 2.5, 3 for current and more than 20 for example for potential, look after your left stack size and mostly that's all (as we know dealt preflop cards are not enough to make decision). Player's mathmatical level is mostly based on playing skills with big stack and such analysis ( All feelings and psycological tricks are left outside). In the middle and late part of tournament you dont even have to many options - mostly push if you are first and have convenient situation (stack size often becomes less than 20 big blinds). There are hard proven rules - if you refuse to participate in 2.5-4 odds bank with mid level cards you have negative winning expectations ( even convenient for cash games).
So optimal size you may compute is only how big your Buy-In for tournament incash should be. (5% of bankroll best sizeSmile | :) fact known without any calculator). Btw most often found rule of portfolio assets weigths. Dont you know why?Smile | :)

Why i am asking that - real example. I have some set of rules in strategy with 3-5 parameters wich can be optmized using evolutionary algorithm. As for fitness function you have options: Maximization of Net Profit, average profit, different ratios etc (i mostly use Net Profit for first criteria and recovery factor as second ) or minimizing loss, drawdowns etc. So thre is no to much place left to any kelly formula. Certainly strategy may use after 20-th trade result optimization criteria. But there is another answer you may optimize strategy for one contract or use of starting capital (strategy will always be bying or selling number of contracts depending on current equity). Sure bet size is convenient for second example. But i didnt find any improvement using Kelly.
The most funny thing - with such kind of optimization optimal sizing methods separately are not needed at all.
Found parameters with found results ( type of equity curve, statistics of returns etc) already consist bet sizing.
Certainly it is not what pure mathematicians expect, but true physicians respect itSmile | :)

Do you really know that anybody uses Kelly formula of something else in real backtesting and trading? I have heard many discussions about it but never seen anybody really using kelly. Let's say i know few people who use Optf. But there are some additional conditions.

To be honest im really interested in any practical improvement. So pls dont hesitate to tell fairly if i am wrong.
Seems i have finished with code where i realised all general approaches: multipleExpressionsProgramming, Boosting etc based on fast series computings, more or less fast real graphics (let's say 8 panels and much more than 10.000 elements updated at least in 20 ms, based on some background computing too). C# with WPF may be really supper fast. I needed all optimizations are done in real time. Conclusion - everything is possible in 2-3 msSmile | :) . What i m doing now - i transfer some code from libraries i used before to my new tradestation and trying to optimize some overall speed. But i m always thinking about bet sizing. There is always relationshop between odds and your decision. Some poker ideas: let'say Phil Ivey style helped me to be more realistic. The main problem - without real limit order (try bet) and following trade you ll never get any reaction. (All predictions based OHLCV series with fed rate are for kinder garden). Maintaining position i would say is much more important than open signal. Before open position you you may only try to understand what other algo traders or investors expect to do. Only one thing you may optimize here - timeframeSmile | :) Shorter - less unpredicted factors. So who payes more for the same risk and for unconvenient odds is loosing. Such analysis is the key. So your bet size will mostly depend on strategy requirements you ll realise: mean reverting based on momentum liquidity for example. But size i use depends on momentum liquidity. So from this look difficult to use any optimal bet sizing. Only one choice: participate or not. This is kind of strategies with minimal position size but with high frequence of trades. I cant place there too much. If i use something like market neutral approach (spot/futures spread, delta hedged positions in options/underlying assets) i dont need optimal sizing too because i dont have any dispertion in returns - spread is fixed on trade initializaton. There is fair comparison - yield on cash involved. If one trade give me 20% per annum and another 40% nothing to choose: second one. If i m market neutral only one risk i have - is settlement (delivery) == exchange clearing house risk. All other styles cant be expressed in formulas.Smile | :) . If i decide to really risk (without maths)....my trade should be based on "inside" knowledge. I m not sure if anybody crazy left on markets. If there is such fish just show where to find it plsSmile | :)
To be honest i know only one theoretical case when to use optimal bet size - when you use portfolio of stategies with volatile profits/losses. But as i told before - you may get what you need under optimization. And it s all concerning porfolios without fixed income.
Alexey


modified 15-Aug-14 8:39am.

AnswerRe: Small question Pin
CatchExAs15-Aug-14 1:53
professionalCatchExAs15-Aug-14 1:53 
GeneralRe: Small question Pin
Alexey KK15-Aug-14 2:31
professionalAlexey KK15-Aug-14 2:31 
GeneralRe: Small question Pin
CatchExAs15-Aug-14 3:05
professionalCatchExAs15-Aug-14 3:05 
GeneralRe: Small question Pin
Alexey KK15-Aug-14 3:18
professionalAlexey KK15-Aug-14 3:18 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.