Skip to content

Instantly share code, notes, and snippets.

@danilo-bc
Last active June 19, 2023 11:35
Show Gist options
  • Select an option

  • Save danilo-bc/b58336036a543679214cc9b0fa598714 to your computer and use it in GitHub Desktop.

Select an option

Save danilo-bc/b58336036a543679214cc9b0fa598714 to your computer and use it in GitHub Desktop.
using Random
using Statistics: mean
using BenchmarkTools
function calculate_call_price(S, K, r, sigma, T, iterations)
"""
Calculates the price of a vanilla call option using Monte Carlo simulation
Parameters:
S (float): Initial stock price.
K (float): Strike price.
r (float): Risk-free interest rate.
sigma (float): Stock price volatility.
T (float): Time to maturity in years.
iterations (int): Number of Monte Carlo iterations.
Returns:
float: Option price.
"""
dt = T / 365
drift = (r - 0.5 * sigma ^ 2) * dt
vol = sigma * sqrt(dt)
option_prices = []
for _ in 1:iterations
price_path = [S]
for _ in 1:Int(T)
push!(price_path, price_path[end] * exp(drift * vol * rand())) # broken
end
push!(option_prices, max(price_path[end] - K, 0))
end
return mean(option_prices) * exp(-r * T)
end
stock_price = 100.0
strike_price = 105.0
interest_rate = 0.05
volatility = 0.2
time_to_maturity = 1.0
num_iterations = 100000
# Uncomment the following 2 lines first to confirm the result it correct before benchmarking
# call_price = calculate_call_price(stock_price, strike_price, interest_rate, volatility, time_to_maturity, num_iterations)
# print("The price of the call option is: $(call_price)")
@btime calculate_call_price(stock_price, strike_price, interest_rate, volatility, time_to_maturity, num_iterations)
num_iterations = 1000000
@btime calculate_call_price(stock_price, strike_price, interest_rate, volatility, time_to_maturity, num_iterations)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment