Skip to content

Commit ce065b4

Browse files
committed
option python file added
1 parent b401e01 commit ce065b4

File tree

3 files changed

+68
-0
lines changed

3 files changed

+68
-0
lines changed
Loading
Loading
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
# -*- coding: utf-8 -*-
2+
"""
3+
Created on Sun Jun 23 11:30:47 2024
4+
5+
@author: stefa
6+
"""
7+
8+
import numpy as np
9+
import matplotlib.pyplot as plt
10+
11+
def monte_carlo_option_pricing(S0, K, T, r, sigma, num_simulations, num_steps):
12+
dt = T / num_steps
13+
paths = np.zeros((num_simulations, num_steps + 1))
14+
paths[:, 0] = S0
15+
16+
for t in range(1, num_steps + 1):
17+
z = np.random.standard_normal(num_simulations)
18+
paths[:, t] = paths[:, t-1] * np.exp((r - 0.5 * sigma**2) * dt + sigma * np.sqrt(dt) * z)
19+
20+
option_payoffs = np.maximum(paths[:, -1] - K, 0)
21+
option_price = np.exp(-r * T) * np.mean(option_payoffs)
22+
23+
return option_price, paths
24+
25+
# Example usage
26+
S0 = 100 # Initial stock price
27+
K = 98.5 # Strike price
28+
T = 1 # Time to maturity (in years)
29+
r = 0.05 # Risk-free rate
30+
sigma = 0.2 # Volatility
31+
num_simulations = 10000
32+
num_steps = 252 # Number of trading days in a year
33+
34+
price, paths = monte_carlo_option_pricing(S0, K, T, r, sigma, num_simulations, num_steps)
35+
print(f"Estimated option price: {price:.3f}")
36+
37+
## Visualization
38+
plt.figure(figsize=(10, 6))
39+
plt.plot(paths[:100, :].T)
40+
plt.title("Sample Stock Price Paths")
41+
plt.xlabel("Time Steps")
42+
plt.ylabel("Stock Price")
43+
plt.show()
44+
plt.savefig("images/simulation_path.png", dpi=300)
45+
46+
plt.figure(figsize=(10, 6))
47+
plt.hist(paths[:, -1], bins=100)
48+
plt.title("Distribution of Final Stock Prices")
49+
plt.xlabel("Stock Price")
50+
plt.ylabel("Frequency")
51+
plt.vlines(S0, 0, 350, colors='r', linestyles='--', label=r'$S_0$')
52+
plt.legend()
53+
plt.show()
54+
plt.savefig("images/simulation_histogram.png", dpi=300)
55+
56+
57+
from scipy.stats import norm
58+
59+
def black_scholes_call(S0, K, T, r, sigma):
60+
d1 = (np.log(S0 / K) + (r + 0.5 * sigma**2) * T) / (sigma * np.sqrt(T))
61+
d2 = d1 - sigma * np.sqrt(T)
62+
return S0 * norm.cdf(d1) - K * np.exp(-r * T) * norm.cdf(d2)
63+
64+
65+
bs_price = black_scholes_call(S0, K, T, r, sigma)
66+
print(f"Black-Scholes price: {bs_price:.3f}")
67+
print(f"Monte Carlo price: {price:.3f}")
68+
print(f"Difference: {abs(bs_price - price):.4f}")

0 commit comments

Comments
 (0)