
If you’d rather watch than read, check out the YouTube video where I walk through the code, logic, and visualization step-by-step. It’s perfect for beginners and intermediate Python users alike.
Let’s start coding this Monte Carlo Simulation to determine if a portfolio with an investment of $1million dollars and a withdrawal rate of 4% will be successful over the next 30 years given our strategy assumptions and allocations. Also, I just want to point out that I misspelled withdrawal rate in the program but hopefully that won’t stop you from learning or enjoying this article :).
Step 1: Import Your Libraries and Setup Your Parameters
#Import the libraries
import numpy as np
import matplotlib.pyplot as plt
#Create some parameters for the F.I.R.E. portfolio
initial_portfolio_value = 1_000_000
withdrawl_rate = 0.04 # Withdrawal rate per year (e.g. 4%)
annual_spending = initial_portfolio_value * withdrawl_rate #Amount withdrawn from the portfolio
years = 30
simulations = 1000
#Create the asset allocation & assumptions
#Defining how the portfolio is split among different asset classes
weights = {
‘stocks’: 0.6, # 60% of the portfolio is invested in stocks
‘bonds’: 0.3, # 30% of the portfolio is invested in bonds
‘cash’: 0.1 # 10% of the portfolio is invested in cash
}
#Define the expected average annual return for each asset class
returns = {
‘stocks’: 0.08, # 8% expected return on stocks
‘bonds’: 0.03, # 3% expected return on bonds
‘cash’: 0.01 # 1% expected return on cash
}
#Define the annual volatility (standard deviation) for each asset class
volatility = {
‘stocks’: 0.15, # 15% volatility on stocks
‘bonds’: 0.05, # 5% volatility on bonds
‘cash’: 0.01 # 1% volatility on cash
}
Step 2: Simulate Retirement Outcomes
#Monte Carlo Simulation
def simulate_fire():
all_simulations = [] # List to store the portfolio value history for each simulation
for _ in range(simulations): # Repeat the simulation ‘simulation’ times
balance = initial_portfolio_value # Initialize the portfolio value
portfolio_history = [] # List to store the portfolio value history
for _ in range(years): #Simulate each year of retirement
annual_return = 0 #Initializing the annual return for this year
#Calculate the weighted return based on each asset’s random performance
for asset in weights:
asset_return = np.random.normal(returns[asset], volatility[asset]) #Simulate the asset return using normal distribution
annual_return += weights[asset] * asset_return #Add weighted return to the total annual return
#Update the portfolio value after applying the return and subtracting spending
balance = balance * (1 + annual_return) – annual_spending
portfolio_history.append(balance) #Record the portfolio value for this year
if balance 0:
successful_count += 1
#Calculate the success rate as a percentage
success_rate = (successful_count / len(simulated_paths))
#Print the success rate
print(f”Success rate: {success_rate:.2%} of simulations lasted {years} years.”)
Success rate: 98.30% of simulations lasted 30 years.
Step 4: Visualize the Results
#Visualize the data
plt.figure(figsize=(12, 6))
#Plot 100 simulated paths
for path in simulated_paths[:100]:
plt.plot(path, alpha=0.3)
#Drawing a line at zero to indicate bankruptcy
plt.axhline(0, color=’red’, linestyle = ‘–‘, label = ‘Bankruptcy Threshold’)
#Add the title and axis labels
plt.title(“Monte Carlo Simulation of F.I.R.E. Portfolio”)
plt.xlabel(“Years into Retirement”)
plt.ylabel(“Portfolio Value ($)”)
plt.legend()
plt.tight_layout()
#Show the plot
plt.show()
📈 What Does the Chart Tell You?
Each line represents a possible future. Some portfolios thrive, others crash and burn. The red line marks the bankruptcy threshold — if your portfolio dips below it, retirement ends early.
The success rate gives you a probabilistic answer to the question: “Can I stay retired?”.
🎬 Final Thoughts
This simulation is more than a financial model — it’s a reality check. By embracing uncertainty and modeling thousands of outcomes, you gain clarity on how much risk your FIRE plan can tolerate.
Want to expand this into a web app, add ETF backtesting, or integrate dynamic withdrawal strategies? Let’s build it together.
For more annotated code, tutorials, and financial tools, check out my Patreon and subscribe to the YouTube channel. Your future self will thank you.
Python Books:
* LearningPythonhttps://amzn.to/3OMjcQx
* Hands-On Machine Learning with Scikit-Learn and TensorFlow: Concepts, Tools, and Techniques to Build Intelligent Systemshttps://amzn.to/49sFrEG
* Machine Learning for Algorithmic Trading: Predictive models to extract signals from market and alternative data for systematic trading strategies with Pythonhttps://amzn.to/4gpv4nl

