<jupyter_start><jupyter_text>A Monte Carlo Simulation to simulate a Random Walk  The code below uses a Monte Carlo SImulation to simulate a price evolution known as "Random Walk". That is the potential evolution of asset prices over time, assuming that their daily returns follows a normal distribution.<jupyter_code>import numpy as np
import math
import matplotlib.pyplot as plt
from scipy.stats import norm
from pandas_datareader import data
%matplotlib inline<jupyter_output><empty_output><jupyter_text>First we extract our asset data (in this case, the Google stock prices) to a Pandas Dataframe.<jupyter_code>google = data.DataReader('GOOG', 'yahoo', start='1/1/2000')
google<jupyter_output><empty_output><jupyter_text>Calculate the compound annual growth rate (CAGR). That gives us the mean return input (MU)<jupyter_code>days = (google.index[-1] - google.index[0]).days
cagr = (((google['Adj Close'][-1] / google['Adj Close'][1])) ** (365.0/days)) - 1
print('CAGR = ',str(round(cagr,4)*100)+"%")
mu = cagr<jupyter_output>CAGR =  24.349999999999998%<jupyter_text>Create a series of percentage returns and calculate the annual volatility of returns<jupyter_code>google['Returns'] = google['Adj Close'].pct_change()
vol = google['Returns'].std()*math.sqrt(252)
print("Annual Volatility = ", str(round(vol,4)*100)+"%")<jupyter_output>Annual Volatility =  30.28%<jupyter_text>Now, we do the Monte Carlo stuff<jupyter_code>S = google['Adj Close'][-1]
T = 252
mu = 0.24
vol = 0.42<jupyter_output><empty_output><jupyter_text>Create a list of daily returns using random normal distribution<jupyter_code>daily_returns = np.random.normal((mu/T), vol/math.sqrt(T), T)+1
price_list = [S]

for x in daily_returns:
    price_list.append(price_list[-1]*x)
plt.plot(price_list)
plt.show
plt.hist(daily_returns-1,100)
plt.show()<jupyter_output><empty_output><jupyter_text>This code generates only a single simulation of price evolution during a year  Now, lets make some more simulations so we can have more insight into the risk.<jupyter_code>for i in range(1000):
    daily_returns = np.random.normal((mu/T), vol/math.sqrt(T), T)+1
    price_list = [S]
    for x in daily_returns:
        price_list.append(price_list[-1]*x)
    plt.plot(price_list)
plt.show()<jupyter_output><empty_output><jupyter_text>This is the outcome of 1000 simulations (!)  Now, let's try to make sense of all these simulations with a histogram. That will show us the distribution of the ending simulations values, rather then the returns for an only simulation<jupyter_code>result = []
for i in range(1000):
    daily_returns = np.random.normal((mu/T), vol/math.sqrt(T), T)+1
    price_list = [S]
    for x in daily_returns:
        price_list.append(price_list[-1]*x)
    result.append(price_list[-1])
    plt.plot(price_list)
plt.show()
plt.hist(result,bins=50)
plt.show()<jupyter_output><empty_output><jupyter_text>Now, if we calculate the mean of this distribution, we will be able to extract our expected value for the stock<jupyter_code>print(round(np.mean(result),2))<jupyter_output>1456.8
{'fraction_non_alphanumeric': 0.11818478615736207, 'fraction_numerical': 0.0287300032647731, 'mean_word_length': 5.869955156950673, 'pattern_counts': {'":': 0, '<': 34, '<?xml version=': 0, '>': 34, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 1, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '9', 'dir': 'jupyter-structured-clean-dedup', 'id': '248509', 'license': 'MIT', 'n_tokens_mistral': 1083, 'n_tokens_neox': 1015, 'n_words': 291, 'path': 'simulations/RandomWalk.ipynb', 'repo_name': 'joaopppobr/MonteCarloPython', 'size': '3063'}