# Mastering Monte Carlo Simulations in Python: A Practical Guide

Written on

## Understanding Monte Carlo Simulations

A Monte Carlo simulation is a computational technique used to estimate the likelihood of various outcomes in situations that involve random variables. By performing repeated random sampling, this method seeks to gauge the probability of uncertain events. Essentially, it simulates an event numerous times with different random inputs to derive estimations. This approach has applications in diverse fields including finance, engineering, and gaming, making it a valuable tool across various professions.

To grasp the fundamentals of Monte Carlo simulations, it’s beneficial to begin with a straightforward model. In this guide, we’ll explore a simple dice game to illustrate the concept. The saying “the house always wins” will be evident as we examine the player's potential earnings versus the house's advantages.

### The Dice Game

Our game involves rolling two six-sided dice. For the player to win, both dice must display the same number. Each die has six possible outcomes (1 through 6), leading to a total of 36 combinations when rolling two dice (6 x 6 = 36). The house has a significant edge, winning in 30 of these scenarios while the player wins only in 6.

Suppose the player begins with a balance of $1,000, ready to wager $1 on each roll, and plans to roll the dice 1,000 times. If the player wins, they’ll receive four times their bet. For instance, winning the first roll increases their balance to $1,004. In a hypothetical scenario where they win all 1,000 rolls, they could end up with $5,000. Conversely, losing every roll would leave them with nothing—a classic risk-reward scenario.

### Importing Required Python Libraries

To simulate this game, we need to import essential Python libraries: Matplotlib’s Pyplot for visualizing results and the random library to generate dice rolls.

# Importing Packages

import matplotlib.pyplot as plt

import random

### Defining the Dice Roll Function

Next, we’ll create a function to generate random integers between 1 and 6 for both dice, simulating a roll. This function will check if the two dice show the same number, returning a Boolean value that will guide our later decisions in the code.

# Creating Roll Dice Function

def roll_dice():

die_1 = random.randint(1, 6)

die_2 = random.randint(1, 6)

# Checking if the dice are the same

same_num = die_1 == die_2

return same_num

### Identifying Inputs and Tracking Variables

Each Monte Carlo simulation requires clear identification of inputs and the desired outcomes. For our game, we established that the player will perform 1,000 rolls, betting $1 each time. Additionally, we will determine how many simulations we wish to run, with a variable named num_simulations to represent this count. The higher this number, the closer our predicted probabilities will align with true values.

We will monitor the win probability (wins per game divided by total rolls) and the ending balance for each simulation, initializing these as lists to be updated after each game.

# Inputs

num_simulations = 10000

max_num_rolls = 1000

bet = 1

# Tracking Variables

win_probability = []

end_balance = []

### Setting Up the Figure

Before running the simulation, we’ll set up our figure. This allows us to add lines to our graph post-simulation, enabling us to visualize results efficiently.

# Creating Figure for Simulation Balances

fig = plt.figure()

plt.title("Monte Carlo Dice Game [" + str(num_simulations) + " simulations]")

plt.xlabel("Roll Number")

plt.ylabel("Balance [$]")

plt.xlim([0, max_num_rolls])

### Running the Monte Carlo Simulation

In the code below, an outer loop iterates through our set number of simulations (10,000), while a nested loop simulates each game with 1,000 rolls. We initialize the player's balance at $1,000 at the start of each game and keep track of rolls and wins.

During each game, we roll the dice and utilize the Boolean result from roll_dice() to determine the outcome. If the dice match, we increase the balance by four times the bet; otherwise, we decrease it.

# For loop to run for the number of simulations desired

for i in range(num_simulations):

balance = [1000]

num_rolls = [0]

num_wins = 0

# Simulating 1,000 rolls

while num_rolls[-1] < max_num_rolls:

same = roll_dice()

if same:

balance.append(balance[-1] + 4 * bet)

num_wins += 1

else:

balance.append(balance[-1] - bet)

num_rolls.append(num_rolls[-1] + 1)

# Store tracking variables and plot results

win_probability.append(num_wins / num_rolls[-1])

end_balance.append(balance[-1])

plt.plot(num_rolls, balance)

### Interpreting the Results

Once the simulations are complete, we can visualize the results and calculate the average win probability and ending balance.

# Displaying the plot after the simulations are finished

plt.show()

# Averaging win probability and end balance

overall_win_probability = sum(win_probability) / len(win_probability)

overall_end_balance = sum(end_balance) / len(end_balance)

# Displaying the averages

print("Average win probability after " + str(num_simulations) + " runs: " + str(overall_win_probability))

print("Average ending balance after " + str(num_simulations) + " runs: $" + str(overall_end_balance))

The average win probability from our simulations is approximately 0.1667, indicating that the player wins about 1 out of every 6 rolls. Despite the house’s generous payout, the average ending balance after 10,000 simulations is $833.66, showcasing that the house maintains its advantage.

## Conclusion

This example provides a foundation for experimenting with different betting strategies and game mechanics. By utilizing this Monte Carlo simulation, you can gain valuable insights into probability and gaming strategies. If the house were to pay 5 times the bet, the player would break even on average, while payouts exceeding this would likely lead to the house’s downfall.

Thank you for reading! I hope this guide aids you in developing effective Monte Carlo simulations. For more Python-related content, feel free to follow my articles!

## Chapter 2: Video Resources

To further enhance your understanding of Monte Carlo simulations, check out these informative videos:

This video provides an introduction to Monte Carlo simulations in Python, breaking down the fundamental concepts.

This video demonstrates a Monte Carlo simulation applied to a stock portfolio, showcasing practical applications in finance.