6.2 KiB
This code simulates stock returns using Geometric Brownian Motion (GBM) and calculates the premium for a barrier option. It defines a function to simulate GBM paths based on initial stock price, drift, volatility, and other parameters. The code then generates multiple simulated price paths, checks if the maximum value of each path exceeds a barrier, and calculates the option payoff accordingly. Lastly, it discounts the payoffs to present value and computes the average premium. This is useful for pricing exotic financial derivatives and analyzing risk.
import numpy as np import matplotlib.pyplot as plt
def simulate_gbm(s_0, mu, sigma, T, N, n_sims=10**3, random_seed=42): """ Function used for simulating stock returns using Geometric Brownian Motion. Parameters ------------ s_0 : float Initial stock price mu : float Drift coefficient sigma : float Diffusion coefficient T : float Length of the forecast horizon, same unit as dt N : int Number of time increments in the forecast horizon n_sims : int Number of simulation paths random_seed : int Random seed for reproducibility Returns ----------- S_t : np.ndarray Matrix (size: n_sims x (T+1)) containing the simulation results. Rows represent sample paths, while columns point of time. """ # Set random seed for reproducibility np.random.seed(random_seed) # Calculate time increment dt = T / N # Generate normally distributed random values for the Wiener process dW = np.random.normal(scale=np.sqrt(dt), size=(n_sims, N + 1)) # Simulate the evolution of the process using GBM formula S_t = s_0 * np.exp(np.cumsum((mu - 0.5 * sigma**2) * dt + sigma * dW, axis=1)) S_t[:, 0] = s_0 return S_t
Define initial stock price, drift, volatility, time horizon, and number of increments
S_0 = 55 r = 0.06 sigma = 0.2 T = 1 N = 252
Define barrier level and strike price for the option
BARRIER = 65 K = 60
Generate GBM simulations for the given parameters
gbm_sims = simulate_gbm(s_0=S_0, mu=r, sigma=sigma, T=T, N=N)
Plot the simulated price paths and the barrier level
plt.axhline(y=BARRIER, color='r', linestyle='-') plt.xlim(0, N) plt.plot(gbm_sims.T, linewidth=0.25)
Calculate the maximum value per path to determine if the barrier was breached
max_value_per_path = np.max(gbm_sims, axis=1)
Calculate the payoff of the barrier option based on the barrier breach condition
payoff = np.where( max_value_per_path > BARRIER, np.maximum(0, gbm_sims[:, -1] - K), 0 )
Calculate the discount factor and the average premium for the option
discount_factor = np.exp(-r * T) premium = discount_factor * np.mean(payoff) premium
PyQuant News is where finance practitioners level up with Python for quant finance, algorithmic trading, and market data analysis. Looking to get started? Check out the fastest growing, top-selling course to get started with Python for quant finance. For educational purposes. Not investment advise. Use at your own risk.
