Monte Carlo Simulation using Python

Dear All,



I have tried to simulate the Monte-Carlo simulation using python learned in SFM-03. Can someone help validate if the code is correct?



Below is the code. The input is 1Day Close Price for stock stored in 'df' dataframe





#Step1 : Calculate the Log Returns

df['log_returns'] = np.log(df.Close) - np.log(df.Close.shift(1))



#Step2 : Calculate the Mean(Average)



mean = df['log_returns'].mean()



#Step3  : Calculate the STD_DEV



std_dev = df['log_returns'].std()



#Setp4  : Calculate the Variance



var  = df['log_returns'].var()



#Setp5  : Calculate Drift



drift = (mean - (var/2))



last_price = df['Close'].tail(1).item()



print("last_price is %s"%last_price)



price_list = [last_price]



result =



No_Of_Days = 30



for i in range(1000000):



    price_list = [last_price]



    random_returns = np.random.normal(mean,std_dev,No_Of_Days)



    for x in random_returns:



        expected_value = price_list[-1]*math.exp((drift + x))



        price_list.append(expected_value)



    result.append(price_list)



print("5% quantile =",np.percentile(result,5))

print("95% quantile =",np.percentile(result,95))

Hi Chetan,

You have done well! Let us look at the whole process in a stepwise fashion:

 

Monte Carlo simulation tends to follow four simple steps, based on the Monte Carlo simulation definition:

https://quantra.quantinsti.com/glossary/Monte-Carlo-Simulation

1. Identify a mathematical model of the process you want to explore/analyze.

- Here you are using a Brownian model to simulate the price behaviour (drift), but you can use any other model, i.e. a fractal model.

 

2. Define the parameters (like mean and standard deviation) for each factor in your model.

- You are using the total mean and standard deviation.

 

3. Create random data according to those parameters.

- In this step, the input parameters need to be improved to generate random normal distribution.

 

4. Simulate and analyze the output of your process.

- This step is vital to get all the knowledge from the Monte Carlo simulation.

Keeping the above in mind, here is your code with minor modifications that we deemed fit : 

import numpy as np
import pandas as pd
import math 
import matplotlib.pyplot as plt
%matplotlib inline

df = pd.read_csv("MSFT_class.csv" , parse_dates=True , index_col=0)

#Step1 : Calculate the Log Returns
df['log_returns'] = np.log(df.Close) - np.log(df.Close.shift(1))
#Step2 : Calculate the Mean(Average)
mean = df['log_returns'].mean()
#Step3 : Calculate the STD_DEV
std_dev = df['log_returns'].std()
#Setp4 : Calculate the Variance
var = df['log_returns'].var()
#Setp5 : Calculate Drift
drift = (mean - (var/2))
last_price = df['Close'].tail(1).item()
print("last_price is %s"%last_price)
T = 252 #Number of trading days
S = df['Adj Close'][-1]

#choose number of runs to simulate - I have chosen 1000
for i in range(100):
  #create list of daily returns using random normal distribution
  daily_returns=np.random.normal(mean/T,std_dev/math.sqrt(T),T)+1
   
  #set starting price and create price series generated by above random daily returns
  price_list = [S]
   
  for x in daily_returns:
    price_list.append(price_list[-1]*x)

  #plot data from each individual run which we will plot at the end
  plt.plot(price_list)

#show the plot of multiple price series created above
plt.show()

 

For more info, check out:

https://quantra.quantinsti.com/glossary/Monte-Carlo-Simulation

https://blog.quantinsti.com/introduction-monte-carlo-analysis/

https://pythonforfinance.net/2016/11/28/monte-carlo-simulation-in-python/

 

We hope this helps.

 

Regards,

Support Team

 

Hi Team,



Thanks for update. I am trying to find why we are deviding by 'T' and dividing by sqrt(t) and adding 1 to below line in the code? Can you please explain.



  #create list of daily returns using random normal distribution

  daily_returns=np.random.normal(mean/T,std_dev/math.sqrt(T),T)+1



Thanks,

Chetan

Hello Chetan,



We have shared the response on your registered email address.





Regards,

Support Team

Thanks Laxmi for the detailed explanation. I will test it out and come back if more support required.



Rgds,

Chetan

 
Hi Chetan.
 
You're most welcome!
 
We are always here to support you if you need any assistance.  
 
Regards,
Support Team