Skip to content

Instantly share code, notes, and snippets.

@rjwebb
Created December 12, 2017 00:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rjwebb/8626d7b909877535e51ae3b78d264003 to your computer and use it in GitHub Desktop.
Save rjwebb/8626d7b909877535e51ae3b78d264003 to your computer and use it in GitHub Desktop.
experiment generating coin flips to test kelly criterion
import decimal
import math
import random
from matplotlib import pyplot as plt
def bet(p):
return random.random() < p
def game(r, p):
"""
One round of coin flip bet
r: the amount of the pot that will be wagered on each round
p: the probability that a coin flip wins, from 0 to 1
returns: the value of the pot at the end of the game
"""
# starting value of the pot, this is arbitrary
pot = 1.0
i = 0
while pot > 0.1 and i < 100:
wager = r * pot
if bet(p):
pot += wager / p
else:
pot -= wager
pot = max(pot, 0)
i += 1
return pot
def kelly(p, r, num_trials):
wins = 0
losses = 0
pots = []
for x in range(num_trials):
# Play one game
pot = game(r, p)
# Record logarithm of the result
pots.append(math.log(pot))
return sum(pots)
p = 0.6
x_values = list(arange(0, 1, step=0.01))
y_values = []
for r in x_values:
y_values.append( (r, kelly(p, r, 1000)) )
plt.plot(x_values, y_values)
plt.show()
# optimal value of 'r' (the amount of money you should wager for each coin flip at p=0.6)
# should be around 0.2, or 20%
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment