library("quantmod")
S0 <- 100
K <- 100
r <- 0.05
sigma <- 0.2
T <- 1
n <- 252
simulate_stock_prices <- function(S0, r, sigma, T, n) {
dt <- T/n
t <- seq(0, T, by = dt)
W <- c(0, cumsum(sqrt(dt) * rnorm(n)))
S <- S0 * exp((r - 0.5 * sigma^2) * t + sigma * W)
return(S)
}
monte_carlo_option_price <- function(S0, K, r, sigma, T, n, num_simulations) {
option_prices <- numeric(num_simulations)
for (i in 1:num_simulations) {
ST <- simulate_stock_prices(S0, r, sigma, T, n)[n + 1]
option_prices[i] <- pmax(ST - K, 0)
}
option_price <- mean(option_prices) * exp(-r * T)
return(option_price)
}
num_simulations <- 10000
option_price <- monte_carlo_option_price(S0, K, r, sigma, T, n, num_simulations)
cat("Option price:", option_price, "\n")