Simulating bets with numpy
Letβs see how to simulate a bet using numpy
. We will simulate a bet with the following characteristics:
- πͺ We have a coin with
heads
andtails
. - π° We start with a
initial_money
. - π² We bet a number of times
num_bets
. - ππΌ There is a probability of winning
prob_win
. If we win we getwin_return
. - ππΌ There is a probability of losing
1-prob_win
. If we lose we loselose_return
.
import numpy as np
def bet(initial_money, prob_win,
win_return, lose_return, num_bets):
money = [initial_money]
p = [prob_win, 1 - prob_win]
for _ in range(num_bets):
if np.random.choice(['heads', 'tails'], p=p) == 'heads':
money.append(money[-1] * (1 + win_return))
else:
money.append(money[-1] * (1 + lose_return))
return money
As you can see if the probability of winning is prob_win
, the probability of losing is 1-prob_win
. This is because both have to add up to 1
.
We use np.random.choice
to simulate the random event of flipping the coin. In a fair coin, p=0.5
, meaning there is an equal probability of landing on heads or tails.
Now, we can use the function with the following parameters. The result of the simulation is the evolution of the money over all bets. We display the money after 20
bets. Since this is a random process, the outcome will vary each time.
simulation = bet(
initial_money=1000,
prob_win=0.5, # 50% chance to win
win_return=0.8, # +80% if you win
lose_return=-0.5, # -50% if you lose
num_bets=20)
print(f"Final money (β¬): {simulation[-1]:.0f}")
# Final money (β¬): 349
βοΈ Exercises:
- Plot the evolution of the bet with the y-axis representing money and the x-axis representing the number of bets.
- Graphically represent the evolution of
1000
people making the same bet, with each line in a different color. - Modify the
bet
function to change the strategy. Instead of betting everything each time, add ano_bet
parameter that indicates the percentage that is not bet. Explore how this change affects the outcome and its relationship with Kellyβs criterion.