Monte Carlo Simulation in Python

Monte Carlo Simulation in Python

Here is to share knowledge and oversee advantages in using Python coding. With the example of the Monte Carlo (MC) simulation we can learn Python language and can easily compare to the existing solutions in Financial models, which might be long outdated and can be easily replaced.

Examples also explore implementation of the well known algorithms of the stock pricing and option pricing using Black Scholes Merton formulas implemented in the following code.

Get started

Lets go straight to the coding and prepare framework for our final product of the Monte Carlo (MC) simulation.

# we start with references to open source libraries used for the Python programming

import numpy as num_lib
import pandas as data_lib 
from pandas_datareader import data as wb

# define underlying security ticker and obtain source of historical records

ticker = 'AMZN'
data = data_lib.DataFrame()
data[ticker] = wb.DataReader(ticker, data_source="yahoo", start="2017-07-01", end="2018-07-01")["Adj Close"]

# calculate stock price return, mean and variance

log_returns = num_lib.log(1 + data.pct_change())

u = log_returns.mean()
variance = log_returns.var()

drift = u - 0.5 * var

std_dev = log_returns.std()

Percentage change between the current and a prior element is powerful time series function from pandas library. Function allows to maintain output by period and frequency, methods to handle NAs.

#transfer value into array

drift.values
std_dev.values

# define random variable

x = num_lib.random.rand(10, 2)

# define number of the time intervals and iterations for MC simulation steps

t_intervals = 1000
iterations = 10

Simulation of the daily return derived from drift and standard deviation. With the following code we create array of 1000 rows and 10 columns of daily_returns outcomes.

daily_returns = num_lib.exp(drift.values + stdev.values * norm.ppf(num_lib.random.rand(t_intervals, iterations)))

As we can see Python is very elegant and intuitive programming language. It allows skip numerous lines of loops, counters and array length limitations. One simple line eliminates number of mishaps and becomes easy tool for newcomer coders.

Now stock prices will be based on 10000 daily return simulations

In following code we initialize S_0 and generate simulation of stock prices

S_0 = data.iloc[-1]
S = num_lib.zeros_like(daily_returns)
S[0] = S_0

# with this simple line we will receive array of 1000 rows and 10 columns of stock price outcomes

for t in range (1, t_intervals):
S[t] = S[t - 1] * daily_returns[t]

Monte Carlo with Black-Scholes-Merton formula

Additional scipy.stats statistics library for cumulative distribution function required for Black-Scholes-Merton formula.

import scipy.stats import norm

From the Python language perspective Black-Scholes-Merton formula is example of the definition of the functions with the function:

def d1(S, K, r, stdev, T)
return
(num_lib.log(S / K) + ( r + stdev ** 2 / 2) * T) / ( stdev * num_lib.sqrt(T))

def d2(S, K, r, stdev, T)
 return
(num_lib.log(S / K) + ( r - stdev ** 2 / 2) * T) / ( stdev * num_lib.sqrt(T))

def BSM (S, K, r, stdev, T)
 return 
(S * norm.cdf(d1(S, K, r, stdev, T))) 
- (K * num_lib.exp(-r * T) * norm.cdf(d2(S, K, r, stdev, T)))

Calculate option price

Now we have 10000 simulation of stock prices in the matrix S[t]. Value of the call option will be based on the discounted to present value of the average from the results of 10000 simulations.

# will create an array that containes either zeros or the numbers equal to the differences

# code will return length of the array, expected number of rows will be equal to 10000

p = num_lib.maximum(S[-1] - K, 0)
p.shape

Now calculate value of the call option as a discounted to present value average of the prices obtained through Monte Carlo simulation

c = num_lib.exp(-r * T) * num_lib.sum(p) / num_iterations

Again, one line of code replaces numerous functions in, for example, long outdated VBA. Python code proves to be very appealing in terms of performance for scalable tasks. Finally, intuitive nature of coding is attractive for programmers with different level of proffeciency.

To view or add a comment, sign in

Others also viewed

Explore content categories