Python for Finance #1: Monte Carlo Simulation

Semih KÖKSAL
3 min readOct 16, 2023

--

In this article, I will explain how the Monte Carlo simulation, as previously discussed in my earlier article, can be implemented in Python. Let’s get started without further ado!

Let’s Code!

Let’s get started by adding the necessary Python libraries to our application. The NumPy library allows us to work with multidimensional arrays and matrices, enabling us to perform mathematical operations. Matplotlib, on the other hand, is a visualization library for Data Science studies that allows us to obtain numerical mathematical calculations as 2 or 3-dimensional visual outputs. Both are libraries of the Python language.

import numpy as np
import matplotlib.pyplot as plt

Further, let’s assign the initial investment and return statistics required to set up the simulation to variables:

initial_investment = 10000 #initial investment amount $
mean_return = 0.15 #Average annual stock return
return_std = 0,18 #Standard deviation of annual stock return
number_of_years = 10 #Number of years for the simulation

Now, let’s define a variable that specifies the number of different simulations we will perform. This variable will represent the number of times we want to simulate the investment to assess its performance.

number_of_simulations = 1000 #Number of simulations

Next, let’s set up a storage array that we will use to plot each scenario simulation on a single graph. Each of the different simulations, as defined above, will be collected in this array.

portfolio_values = np.zeros((number_of_simulations, number_of_years + 1))

After defining the necessary statistics and variables, we can start generating simulations. Since we aim to create a specific number of simulations, I’ve chosen to use a “for” loop for this purpose.

for i in range(number_of_simulations):
#simulate returns for each year
annual_returns = np.random.normal(mean_return, return_std, number_of_years) +1
#Update portfolio value each year
portfolio_values[i][0] = initial_investment
for j in range(number_of_years):
portfolio_values[i][j+1] = portfolio_values[i][j] * annual_returns[j]

Up to this point, we have actually generated 1000 different simulations and stored them in an array. Now, we will visualize these simulations on a graph.

for i in range(number_of_simulations):
plt.plot(range(number_of_years+1), portfolio_values[i])

Next, we will make adjustments to the graph labels and add the average values of the simulations to the graph.

mean_portfolio_values = np.mean(portfolio_values, axis=0)

Above, we first defined a variable called mean_portfolio_values to calculate the average returns of the simulations. We assigned the value of the average of the values in the portfolio_values array to this variable using np.mean().Further,

plt.plot(range(number_of_years + 1), mean_portfolio_values, 'k-', linewidth=3, label='Average')

plt.title('Monte Carlo Simulation - Stock Portfolio')
plt.xlabel('Year')
plt.ylabel('Portfolio Value')
plt.legend()
plt.grid(True)
plt.show()

In this part, we are defining the properties of the simulation graph.

When you run the code, the expected output should look like this. The meaning of this plot and how to interpret it have been explained in my previous article. Here is the link to the article for further reference.

To sum up…

In the code provided above, I did not go into details about parts that require historical or price forecasting data, such as “average annual stock return” or “standard deviation of annual stock return.” Briefly, in this context, we assigned a value to these variables, but how these variables are calculated is a separate and extensive topic of stochastic or deterministic modeling. I am also planning to write an article on how to calculate these variables. Thank you for your reading, and you can access the entire code through the GitHub link below if you want to try it by yourself:
https://github.com/semihkksl/PythonforFinance

--

--

Semih KÖKSAL

METU graduate, Treasury - ALM strategist at Turkiye Isbank, Finance, Economics , Statistics, Pol-Sci