Understanding Monte Carlo Simulation and its implementation with Python (2024)

Before jumping on to Monte Carlo Simulation, lets understand deterministic and stochastic modelling first.

In supervised or unsupervised machine learning -we take a dataset, mostly historic data. We fit a model on the existing data and predict the future value on the basis of that — this type of modelling is called as deterministic modelling. Deterministic modeling gives us the same exact results for a particular set of inputs, no matter how many times you re-calculate the model. Here, the mathematical properties are known. None of them is random, and there is only one set of specific values and only one answer or solution to a problem. With a deterministic model, the uncertain factors are external to the model.

When we don’t have any past data to rely on we use random variables to design the model and predict the future values. This type of modeling is called stochastic modeling which forecasts the probability of various outcomes under different conditions, using random variables. Monte Carlo Simulation is one example of stochastic model.

In a Monte Carlo simulation, a random value is selected as an input for each of the tasks, based on the range of estimates. The model is calculated based on this random value. The result of the model is recorded, and the process is repeated. A typical Monte Carlo simulation calculates the model hundreds or thousands of times, each time using different randomly-selected values. When the simulation is complete, we have a large number of results from the model, each based on random input values. These results are used to describe the likelihood, or probability, of reaching various results in the model.

Principle behind Monte Carlo Simulation-

Till now we understood what monte carlo simulation is. Now we are trying to understand why we do monte carlo simulation and how it gives results.

To understand the principle behind monte carlo simulation, lets take an example of flipping a coin. when you flip a coin, the probability of getting ‘Head’ is 0.5. When we flip the coin for 50 times, it is hard to tell how many heads we will get. lets try using monte carlo simulation in this example.

Import the required libraries first and define the coin flip function which results either 0 or 1 -Head or Tail. Then defining a monte carlo simulation function to calculate the probability and appending the values to the results.

Understanding Monte Carlo Simulation and its implementation with Python (2)
Understanding Monte Carlo Simulation and its implementation with Python (3)

From above example we can see that as the number of iterations increases the accuracy of the probability increases. This is how we can use the Monte Carlo Simulation to find probabilities experimentally.

We will look into one more example to understand why do we perform so many iterations. In this example we will simply plot normal distribution of different size of samples.

Understanding Monte Carlo Simulation and its implementation with Python (4)

Above code gives us following result:

Understanding Monte Carlo Simulation and its implementation with Python (5)

From the above results we can see that as the sample size increases the accuracy of the results increases.

How to apply Monte Carlo Simulation:

Here we will see how we can run a simulation when trying to predict the future stock price of a company in Python.

Import the necessary libraries.

Understanding Monte Carlo Simulation and its implementation with Python (6)

In this example the company we will use is P&G. We will pull the data from 2010 as follows:

Understanding Monte Carlo Simulation and its implementation with Python (7)

This data contains the high, low, open, close value of stock , volume and the adj close price. We will use only the closing price of the stock. So lets create new dataframe called new_data to forecast P&G’s future stock price in this exercise.

Understanding Monte Carlo Simulation and its implementation with Python (8)

Lets plot our data

Understanding Monte Carlo Simulation and its implementation with Python (9)

There are two components to running a Monte Carlo simulation:

1) the equation to evaluate

2) the random variables for the input

Lets look in to the formula first to derive the equation to evaluate.

Today’s Stock Price = Yesterday’s Stock Price x e^r

where r = periodic daily return

Monte carlo simulation generates theoretical future ‘r’ values because the rate of return on an asset is a random number. To model the movement and determine possible future ‘r’ values we must use a formula that models random movements. Here we will use a formula of Brownian motion.

Brownian motion assumes that there are two parts to the random movement. The first is the overall driving force called as ‘drift’ and the second is the random component. Therefore the rate that the asset changes in value each day- the ‘r’ value that the e is raised to can be broken down into two parts-an overall drift and a random stochastic component.

Amount change in stock Price = Fixed drift rate + Random stochastic variable

To create a monte carlo simulator to model future outcomes we need to find theses two parts- the drift and the random stochastic component.

The first thing we’ll do is estimate its historical log returns.

Understanding Monte Carlo Simulation and its implementation with Python (10)

Plotting historic log returns:

Understanding Monte Carlo Simulation and its implementation with Python (11)

The first part — Drift is expected periodic daily rate of return. The formula we will use here will be-

Drift = Average Daily Return− (Variance​/2)

Calculating Drift:

Understanding Monte Carlo Simulation and its implementation with Python (12)

To calculate the second part- create a variable stdev which is a standard deviation of historic log returns

Understanding Monte Carlo Simulation and its implementation with Python (13)

The central limit theorem tells us that if we plot enough periodic daily returns of an asset the graph should form a normal distribution, bell shaped graph.

To create get the random stochastic component we will use the norm.ppf formula as follows:

Understanding Monte Carlo Simulation and its implementation with Python (14)

If an event has a 95% chance of occurring, the distance between this event and the mean will be approximately 1.65 standard deviations. we will use the numpy rand function to randomize this component. we want a multidimensional array so we will insert to arguments.

Understanding Monte Carlo Simulation and its implementation with Python (15)

We will include this random element within the “PPF” distribution to obtain the distance from the mean corresponding to each of these randomly generated probabilities.

Understanding Monte Carlo Simulation and its implementation with Python (16)

Now we have understood how to create a random component. lets put it in to formula. If we want stock price predictions of next 1000 days with 20 iterations, we will define variables as follows:

Understanding Monte Carlo Simulation and its implementation with Python (17)

We have got above result which is 1000 by 20 array-with daily return values — 20 sets of 1,000 random future stock prices.

As we have got the daily return values we can calculate the future stock price by this formula:

S1 = S0 x daily return

here S0= stock price at t day

S1 = stock price at t+1 day

We will create an 1000 by 20 array with all zero values, then replace the first row with the last stock price as follows:

Understanding Monte Carlo Simulation and its implementation with Python (18)

lets write down the simulation by using -for loop.

Understanding Monte Carlo Simulation and its implementation with Python (19)

lets plot the results

Understanding Monte Carlo Simulation and its implementation with Python (20)
Understanding Monte Carlo Simulation and its implementation with Python (21)

From the line plots above, we can see the simulated stock prices can spread from about $100 to $400. This has given us an idea about the potential price range for the stock based on the same level of volatility. We will do further analysis on our simulated stock prices to gain more insights.

lets calculate the Mean of the simulated last prices, Quantile (5%) and Quantile (95%) of the simulated last prices.

Understanding Monte Carlo Simulation and its implementation with Python (22)

From the result above, we can see there is a 5% of probability that the stock price will be below $129.09 and a 5% of probability the price will be above $310.13. Our expected stock price at the year-end is $194.63.

In this article we understood the concept of Monte Carlo Simulation, Principle behind monte carlo simulation with two simple examples and predicted the stock prices with monte carlo simulation.

I wish you enjoy reading this article.

Understanding Monte Carlo Simulation and its implementation with Python (2024)
Top Articles
Latest Posts
Article information

Author: Saturnina Altenwerth DVM

Last Updated:

Views: 6095

Rating: 4.3 / 5 (64 voted)

Reviews: 95% of readers found this page helpful

Author information

Name: Saturnina Altenwerth DVM

Birthday: 1992-08-21

Address: Apt. 237 662 Haag Mills, East Verenaport, MO 57071-5493

Phone: +331850833384

Job: District Real-Estate Architect

Hobby: Skateboarding, Taxidermy, Air sports, Painting, Knife making, Letterboxing, Inline skating

Introduction: My name is Saturnina Altenwerth DVM, I am a witty, perfect, combative, beautiful, determined, fancy, determined person who loves writing and wants to share my knowledge and understanding with you.