Home Python Trading Strategy How To Do A Monte Carlo Simulation Using Python – (Example, Code,...

# How To Do A Monte Carlo Simulation Using Python – (Example, Code, Setup, Backtest)

Quant strategists employ different tools and systems in their algorithms to improve performance and reduce risk. One is the Monte Carlo simulation, which is quite powerful regarding option pricing or risk management problems.

A Monte Carlo simulation represents the likelihood of various outcomes in a process that is challenging to predict due to the involvement of random variables. Its primary purpose is to gain insights into the effects of risk and uncertainty.

In this post, we will show you a step-by-step guide of how to do a Monte Carlo simulation using Python.

Related reading:- We have many trading strategies for sale

Table of contents:

## What is Monte Carlo simulation?

If you are new to trading, you might wonder what Monte Carlo simulation is. Please read our article about Monte Carlo simulation in trading.

## Import libraries and downloading data

The first step is importing the necessary libraries. In this case, they are pandas, numpy, matplotlib, finance, and scipy. If you want to know more about how to download historical stock prices using yfinance check our previous post on how to download data for your trading strategy using Python.

In this example, the company we will use is Apple. We will pull the data since its inception as follows:

Now we have all the historical open, high, low, close, adjusted close, and volume values for Apple since 1980!

## Calculating the logarithmic returns and drift

Next, we need to calculate the logarithmic returns, which is done with the following function from the numpy library(np.log). Note that this equation differs from the usual percentage change formula.

The drift is the expected periodic daily rate of return. The formula is:

Drift = Average Daily Return – (0.5*Variance)

For this, we need to calculate the mean and the variance using the numpy functions as follows:

Then, we create a new variable called drift and use the formula from above. As you can see, the drift of Apple stock is 0.000835.

## Generate random variables

In this step, we have to generate random variables for every day forecasted and for every simulation trial we will run.

First, we are going to calculate the standard deviation using the numpy function std().

Now, we must define how many trials and days we want to forecast. In this case, we are going to do 50 days and 100 different trails.

Then we generate a matrix which we call Z of shape(days, trials) filled with random numbers sampled from a standard normal distribution. It does so by first calling np.random.rand(days, trials), which generates random values between 0 and 1, and then applies the inverse of the cumulative distribution function of the standard normal distribution(norm.ppf) to transform these random values into numbers that follow a standard normal distribution.

The code then initializes a new variable called daily_returns and multiplies each value in the Z matrix by the standard deviation and adds the drift. The result is then exponentiated using np.exp to obtain the daily returns.

After this, we initialize an array called price_paths with zeros, of the same size as the daily_returns array. The first element of price_paths is the last closing price of Apple. Then, the code runs a loop from the second day up to the fifty day, calculating the price for each subsequent day based on the previous day’s price and the corresponding daily return.

The multiplication of the previous day’s price with the daily return simulates the price change for each day, considering the random nature of daily returns.

## Plot the price paths in Python

Lastly, we have to plot the results. For this, we will use the matplotlib library with just two lines of code:

Here is the output:

Now, we can see the simulated stock prices for the next 50-days of Apple based on the same level of volatility it has historically had. The stock can end up in the range between \$342 and \$110. The mean value is \$198, and because the distribution is normal, there is an equal chance that the stock ends up higher or lower than that.

## Advantages and disadvantages of a Monte Carlo Simulation

The Monte Carlo method is a valuable tool for investors to estimate the chances of gaining or losing on an investment.

However, no simulation can precisely predict an exact outcome. The Monte Carlo method strives to provide a more reliable estimate of the probability that an outcome will deviate from a projected value.

The key distinction from other methods is that the Monte Carlo method involves testing multiple random variables and averaging them rather than starting with an average.

## How To Do a Monte Carlo Simulation Using Python – conclusion

To summarize, we learned how to do a Monte Carlo simulation using Python. Although it can’t predict exactly what will happen, it can be a valuable resource to add to your risk management system and better measure risk and outcomes.