Skip to content

Instantly share code, notes, and snippets.

@XerxesZorgon
Created October 10, 2020 17:19
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 XerxesZorgon/33d4fb8d521a1508d52d0792a5c7204c to your computer and use it in GitHub Desktop.
Save XerxesZorgon/33d4fb8d521a1508d52d0792a5c7204c to your computer and use it in GitHub Desktop.
Kelly return ratio plot and Monte Carlo simulation
# -*- coding: utf-8 -*-
"""
Created on Mon Sep 21 14:56:39 2020
Kelly Criterion functions
@author: johnx
"""
import numpy as np
import matplotlib.pyplot as plt
def plotReturnRatio(p,w):
"""
Parameters
----------
p : TYPE Real, 0 <= p <= 1
Probability of winning
w : TYPE Real, 0 < w
Winnings per bet
Returns
-------
Plot of return ratio for bet fraction b, 0 <= b <= 1
"""
# Return ratio function
R = lambda b,p,w: (1-b+b*w)**p * (1-b)**(1-p)
# Bet fractions
b = np.linspace(0,1,num = 100)
# Return ratio for each bet fraction
r = [R(beta,p,w) for beta in b]
# Optimal b and r
b_max = (p*w - 1)/(w-1)
r_max = R(b_max,p,w)
# Plot curve
plt.plot(b,r)
plt.plot(b_max,r_max,color = 'red', marker = 'o')
plt.xlabel('Bet fraction, b')
plt.ylabel('Return ratio, R')
plt.title('Kelly Criterion')
def KellyMC(p,w):
"""
Parameters
----------
p : TYPE Real, 0 <= p <= 1
Probability of winning.
w : TYPE Real, 0 < w
Winnings per bet.
Returns
-------
S : Money on hand after each bet for 3 different betting strategies
"""
# Number of MC experiments
nMC = 100
# Betting fraction error
b_err = 0.05
# Series of win/loss experiments
nWL = int(np.round(p*nMC))
WL = np.random.permutation(np.concatenate((np.ones(nWL),np.zeros(nMC-nWL)),axis=0))
# Net value on hand after each experiment
S = np.zeros((3,nMC))
# Optimal betting fraction
b = (p*w-1)/(w-1)
# Bet fractions
B = np.array([b - b_err, b, b + b_err])
# Play each hand (1st hand assumes initial stash = 1)
S[:,0] = 1 - B + w*B*WL[0]
for k in range(1,nMC):
S[:,k] = S[:,k-1] * (1 - B + w*B*WL[k])
# Plot results
games = np.array(range(1,nMC+1)).transpose()
plt.plot(games,S[0,:], label = "Bet-")
plt.plot(games,S[1,:], label = "Optimal")
plt.plot(games,S[2,:], label = "Bet+")
plt.xlabel('Game number')
plt.ylabel('Net value')
plt.legend('loc','upper left')
plt.title('Monte Carlo Kelly Experiment')
plt.grid()
plt.legend(["Bet-","Optimal","Bet+"])
return S
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment