How to Perform Monte Carlo Simulations in Python (With Example)

How to Perform Monte Carlo Simulations in Python (With Example)
Image by Editor (Kanwal Mehreen) | Canva

Monte Carlo simulations are a method for understanding uncertainty and predicting outcomes. In Python, we can use tools like NumPy and Matplotlib to run these simulations and analyze the results. This article explains how to perform Monte Carlo simulations in Python.

What is a Monte Carlo Simulation?

Monte Carlo simulations estimate probabilities using random sampling. They help model uncertainty and predict outcomes. The process involves:

  • Defining the problem and model.
  • Generating random inputs for uncertain variables.
  • Running the simulation multiple times with random inputs.
  • Analyzing the distribution of results.

Monte Carlo simulations are applied in fields like finance, engineering, physics, and operations research. They are particularly useful when it is difficult to find exact solutions due to uncertainty or complexity.

Define the Problem and Model

First, we must define the problem. For example, let’s simulate the profit of a business. We will make the following assumptions:

  • Sales: Normally distributed with a mean of 10,000 and a standard deviation of 2,000.
  • Price per Unit: Uniformly distributed between $10 and $20.
  • Fixed Costs: Constant at $80,000.

The profit formula can be expressed as: Profit = (Sales × Price per Unit) – Fixed Costs

This model assumes that sales volume and the price per unit are uncertain and need to be modeled using probability distributions.

Generate Random Inputs for Uncertain Variables

Next, we need to generate random values for the uncertain variables. We will use Python’s NumPy library to create random values for sales and price. In our case:

  • Sales will follow a normal distribution.
  • Price per unit will follow a uniform distribution.
  • Fixed Costs remain constant, so no random sampling is required for this variable.
import numpy as np

# Parameters for the model
mean_sales = 10000
std_dev_sales = 2000
price_min = 10
price_max = 20
fixed_costs = 80000
num_simulations = 10000  # Number of Monte Carlo simulations

# Generate random sales and price per unit
def generate_random_inputs():
    sales = np.random.normal(loc=mean_sales, scale=std_dev_sales)  # Sales follow normal distribution
    price_per_unit = np.random.uniform(low=price_min, high=price_max)  # Price follows uniform distribution
    return sales, price_per_unit

With the random inputs ready, we can now proceed to calculate the profit for each simulation.

Run the Simulation

We use these functions to generate random inputs and run the simulation multiple times. In each iteration, we generate new random inputs and calculate the resulting profit. This process creates a distribution of possible profit outcomes.

# Function to calculate profit
def calculate_profit(sales, price_per_unit):
    return (sales * price_per_unit) - fixed_costs

# Run the simulation and store the results
def monte_carlo_simulation(num_simulations):
    profits = []
    for _ in range(num_simulations):
        sales, price_per_unit = generate_random_inputs()
        profit = calculate_profit(sales, price_per_unit)
        profits.append(profit)
    return profits

# Run the Monte Carlo simulation
profits = monte_carlo_simulation(num_simulations)

# Output the results
print(f"Estimated Profit Distribution (First 5 samples): {profits[:5]}")

Output:

Estimated Profit Distribution (First 5 samples): [26711.763527541276, 51610.93783278327, 66156.91585649588, 107830.72599994956, 160145.6595554336]

At the end of the simulation, we have a list of simulated profit values, which we can now analyze.

Analyze the Distribution of Results

We can analyze the results by calculating key statistical measures. This includes the mean, standard deviation, and various percentiles. We can also visualize the data with a histogram to better understand its distribution.

import matplotlib.pyplot as plt

# Calculate statistical measures
mean_profit = np.mean(profits)
std_dev_profit = np.std(profits)
percentiles = np.percentile(profits, [5, 50, 95])

# Print out the results
print(f"Mean Profit: ${mean_profit:.2f}")
print(f"Standard Deviation of Profit: ${std_dev_profit:.2f}")
print(f"5th Percentile Profit: ${percentiles[0]:.2f}")
print(f"50th Percentile Profit (Median): ${percentiles[1]:.2f}")
print(f"95th Percentile Profit: ${percentiles[2]:.2f}")

# Plot the distribution of profits
plt.hist(profits, bins=50, color='skyblue', edgecolor='black')
plt.title('Monte Carlo Simulation: Profit Distribution')
plt.xlabel('Profit ($)')
plt.ylabel('Frequency')
plt.show()

results

Conclusion

Monte Carlo simulations provide a powerful way to understand uncertainty and predict a range of possible outcomes. By repeatedly sampling random values, we can estimate the probability of different results. In this example, we used a simulation to model business profit based on uncertain sales and pricing.

The results, including the average profit, standard deviation, and key percentiles, reveal the range of possible financial outcomes. A histogram provides a clear visual representation of how these potential profits are distributed.

Leave a Reply

Your email address will not be published. Required fields are marked *