Monte-carlo simulation of stock prices (using Python)

In one of my posts I have introduced the concept of random walk forecasting, using Python for implementation. In this post I want to conduct a monte carlo simulation of stock price random walks. For this I will use a the following fictional stock price history:

# declare list with fictional daily stock closing prices
history_prices = [180,192,193,195,191,199,198,200,199,203,205,207,205,208,201,203,204,201,205,206,207]
[180, 192, 193, 195, 206, 211, 191, 204, 215, 190, 205, 207, 205, 211, 222, 215, 245, 201, 205, 206, 214]

In preparation of next steps I will now import all relevant Python modules:

# import statistics for calculating e.g. standard deviation of price history
import statistics as stat
# import pyplot for plotting
import matplotlib.pyplot as plt
# import random for random number generations
import random as rnd

Assuming random stock price movement I derive standard deviation from relative changes in fictional price history such that I will be be able to model random stock price movements:

relative_prices = []
for i in range(0,len(history_prices)):
    if i == 0:
std_prices = stat.stdev(relative_prices)

Now I model one exemplaric random price walk for 100 days into the future, assuming random price movement based on the standard deviation of random prices. I assume a random normal distribution. The last known price in history serves as starting point:

# modeling a random price walk over 100 days
# -- conduct calculation, define function
def randomWalk(stdev,pastPrices):
    days = [i for i in range(1,101)]
    prices = []
    price = pastPrices[-1]
    for i in range(1,101):
        price = price + price*rnd.normalvariate(0,stdev)
# -- conduct calculation, use function
prices = randomWalk(std_prices,history_prices)
# -- visualize random walk in a line plot
plt.title("random price walk")
plt.ylabel("stock price")
Text(0, 0.5, 'stock price')

I can repeat this process, by re-calculating additional random walks, thereby creating a monte-carlo simulation of stock price movements. In below example I repeat the random walk process for 30 separate walks:

for i in range(0,30):
    prices = randomWalk(std_prices,history_prices)
plt.title("monte-carlo simulation of stock price development")
plt.ylabel("stock price")
Text(0, 0.5, 'stock price')

Leave a Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.