Instantly share code, notes, and snippets.

# ShaneLee/retirement_portfolio_5.py

Last active January 2, 2020 17:28
Show Gist options
• Save ShaneLee/827e601501d962aecc155d296d0309b0 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
 def get_simulation(data): # Get the logarithmic returns of the % change of prices from one trading day to the next. log_returns = np.log(1 + data.pct_change()) # Get the mean of these returns u = log_returns.mean() # Get the variance of these returns var = log_returns.var() # Get the change in the average value of these values drift = u - (0.5 * var) # Get the standard deviation stdev = log_returns.std() # How many days are we going to run the stimulation for t_intervals = DAYS_IN_YEAR * YEARS # How many simulations of this financial instrument are we going to run? iterations = 10 # Create the Monte Carlo stimulation of daily percent changes of the financial instruments. daily_returns = np.exp(drift + stdev * norm.ppf(np.random.rand(t_intervals, iterations))) # Create an numpy array filled with zeros with the same shape as the daily_returns numpy array. price_list = np.zeros_like(daily_returns) # Set the most recent trading day's data as the start prices price_list[0] = Sdata.iloc[-1] # For each day in the simulation, compute the price of the stock after multiplying # the previous's price by the current day's price. for t in range(1, t_intervals): price_list[t] = price_list[t - 1] * daily_returns[t] # Get all the percentage returns for all the simulations for this financial instructment. asset_returns = price_list[-1] / price_list[0] # Get and return the geometric mean (because we are dealingn with percentages) # of all these simulations for this financial instrument. return gmean(asset_returns)

### DBremen commented Jan 2, 2020

Hi, Shane thanks a lot for sharing. I found two typos:

• Line 21: Missing definition of S0 `price_list[0] = data.iloc[-1]`
• Line 28: Missing open parenthesis: `asset_returns = price_list[-1] / (price_list[0])`

### ShaneLee commented Jan 2, 2020

Hi Dirk,

Thanks for you comments. I'd missed those errors when I was copying and pasting the code to create the gists.

Thanks again

Shane

to join this conversation on GitHub. Already have an account? Sign in to comment