Python Risk Management: Monte Carlo Simulations | by Lester Leong | Towards Data Science

In this article, we’ll go over Monte Carlo simulations, which can be applied to offer insights on modeling future events. The whole idea of this article came from a combination of two factors. First was from an experiment I am running off of options trading, the journey can be found here. The second was the other Python Risk Management article about Kelly Criterion was pretty popular, so I thought of expanding the topic, which the original article is found here. Without further ado, let’s begin the discussion on Monte Carlo simulations for asset pricing!
A common way Monte Carlo simulations is taught is thinking about any form of chance, hence the slot machine image. At any given time, multiple events can occur in the next time step based on an action. Now, I believe in learning simple examples first to understand complex ones, so let’s think about throwing a fair six-sided die. We all know that dice have 6 possible chances numbering from 1 to 6. But to figure out how much experimentally, we would have to roll the die a few times and record the results. With Monte Carlo simulations, we can perform as many amount of trials we want within the simulation.
In a more technical definition, Monte Carlo are taken from a probability distribution to provide a multivariate model of risk or present multiple what if events [1]. The base formula for Monte Carlo boils down to:
Basically, the formula is made up of 3 major components. First, is the data over time of the asset we are looking at. In our article, it would be the cryptocurrency Tezos and the stock ticker AMD. The next piece is drift, which is the direction the asset has been moving in the past. The third component is a random component taken from a distribution. In our case, we will use the normal distribution to simulate asset volatility. Volatility is normally seen as the crazy movement a stock does on a usual basis that kind of looks random.
As stated earlier, Monte Carlo is a good way to map out a problem with multiple possible outcomes. In finance and specifically the financial markets, an asset could go to multiple different price levels in the future. Besides asset pricing, Monte Carlo simulation can be applied in projecting financial line items such as cash flow [2].
Tezos is another crypto currency that applies smart contracts like Etherium [3]. I just got curious about it, since there is an interesting feature dividend like feature about it. At least in my Tezos holdings in Coinbase, it actually paid roughly 5% for holding it (Tezos rewards), which is similar to a dividend yield in stocks — image below:
Just a heads up, I got the Tezos for free by learning about in Coinbase and you can get $10 for signing up with this affiliate link. To get the earn the Tezos, you have to scroll down in your dashboard and should see an earn page. The just complete the tutorial and you should see rewards available. One example of the crypto EOS can be found in this affiliate link. On to the Tezos Monte Carlo simulation example, daily data taken from investing.com:
#Import Librariesimport numpy as np  import pandas as pd  import pandas_datareader as wb  import matplotlib.pyplot as plt  from scipy.stats import norm%matplotlib inline﻿#Settings for Monte Carlo asset data, how long, and how many forecasts ticker = 'XTZ_USD' # tickert_intervals = 30 # time steps forecasted into futureiterations = 25 # amount of simulations#Acquiring datadata = pd.read_csv('XTZ_USD Huobi Historical Data.csv',index_col=0,usecols=['Date', 'Price'])data = data.rename(columns={"Price": ticker})#Preparing log returns from datalog_returns = np.log(1 + data.pct_change())#Plot of asset historical closing pricedata.plot(figsize=(10, 6));
#Plot of log returnslog_returns.plot(figsize = (10, 6))
#Setting up drift and random component in relation to asset datau = log_returns.mean()var = log_returns.var()drift = u - (0.5 * var)stdev = log_returns.std()daily_returns = np.exp(drift.values + stdev.values * norm.ppf(np.random.rand(t_intervals, iterations)))#Takes last data point as startpoint point for simulationS0 = data.iloc[-1]price_list = np.zeros_like(daily_returns)price_list[0] = S0#Applies Monte Carlo simulation in assetfor t in range(1, t_intervals):    price_list[t] = price_list[t - 1] * daily_returns[t]﻿﻿﻿#Plot simulationsplt.figure(figsize=(10,6))plt.plot(price_list);
One thing to note is the large volatility in these simulations. From today’s price of 1.50, Tezos can potentially swing from 1.00 to 2.75! From these small number of simulations, I can see why some people like to take a chance on Bitcoin and similar cryptos due to the slightly favored upside potential.
I just decided to do AMD due to my other posts trading AMD options found here. Now, let’s get to the Advanced Micro Devices Monte Carlo simulation.
#Import Librariesimport numpy as np  import pandas as pd  import pandas_datareader as wb  import matplotlib.pyplot as plt  from scipy.stats import norm%matplotlib inline﻿﻿﻿#Settings for Monte Carlo asset data, how long, and how many forecasts ticker = 'AMD' # stock tickert_intervals = 30 # time steps forecasted into futureiterations = 25 # amount of simulations#Acquiring datadata = pd.DataFrame()data[ticker] = wb.DataReader(ticker, data_source='yahoo', start='2018-1-1')['Adj Close']#Preparing log returns from datalog_returns = np.log(1 + data.pct_change())#Plot of asset historical closing pricedata.plot(figsize=(10, 6));
#Plot of log returnslog_returns.plot(figsize = (10, 6))
The log returns are looking pretty good from the closing prices above. Now on to setting up the drift and random components.
#Setting up drift and random component in relatoin to asset datau = log_returns.mean()var = log_returns.var()drift = u - (0.5 * var)stdev = log_returns.std()daily_returns = np.exp(drift.values + stdev.values * norm.ppf(np.random.rand(t_intervals, iterations)))#Takes last data point as startpoint point for simulationS0 = data.iloc[-1]price_list = np.zeros_like(daily_returns)price_list[0] = S0#Applies Monte Carlo simulation in assetfor t in range(1, t_intervals):    price_list[t] = price_list[t - 1] * daily_returns[t]﻿﻿﻿#Plot simulationsplt.figure(figsize=(10,6))plt.plot(price_list);
Looks like the overall trend of AMD from the Monte Carlo simulations is up, which is a good sign due to my bullish positions at the time of the challenge!
Monte Carlo simulations permit investors and traders to transform investment possibilities into decisions. The upside of Monte Carlo is its capacity to factor in a scope of qualities for different possible events. This is likewise its most noteworthy downside is it sometimes fails to accurately gauge extreme events. For example, multiple Monte Carlo simulations failed during the great bear crisis. So, this model-like others are restricted by the data and settings applied. One possible solution to this weakness is to take a non-normal probably distribution for the random component simulated.
— — — — — — — — — — — — — — — — — — — — — — — — — —
References
[1] Stammers, R. (2020, January 3). How to Use Monte Carlo Analysis to Estimate Risk. Retrieved from https://www.investopedia.com/articles/financial-theory/08/monte-carlo-multivariate-model.asp
[2] Agarwal, K. (2019, November 18). What Can The Monte Carlo Simulation Do For Your Portfolio? Retrieved from https://www.investopedia.com/articles/investing/112514/monte-carlo-simulation-basics.asp
[3] Coinbase. (2019). Earn Tezos. Retrieved from https://www.coinbase.com/earn/tezos
— — — — — — — — — — — — — — — — — — — — — — — — — —
To get into Coinbase click this affiliate link, so we both get $10.
This article was created due to Options $100k Challenge.
Disclaimers: All things stated in this article are of my own opinion and not of any employer. Investing carries serious risk and consult your investment advisor for all investment decisions. I may actively trade assets stated in this article. This post contains affiliate links.