Link Search Menu Expand Document

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 and tails.
  • πŸ’° 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 get win_return.
  • πŸ‘‡πŸΌ There is a probability of losing 1-prob_win. If we lose we lose lose_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 a no_bet parameter that indicates the percentage that is not bet. Explore how this change affects the outcome and its relationship with Kelly’s criterion.