1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208
| import numpy as np import matplotlib.pyplot as plt import scipy.stats as stats from matplotlib import cm import pandas as pd from mpl_toolkits.mplot3d import Axes3D
def black_scholes(S, K, T, r, sigma, option='call'): """ Calculate Black-Scholes option price for a call or put Parameters: S: Current stock price K: Strike price T: Time to maturity (in years) r: Risk-free interest rate sigma: Volatility option: 'call' or 'put' Returns: Option price """ d1 = (np.log(S / K) + (r + 0.5 * sigma**2) * T) / (sigma * np.sqrt(T)) d2 = d1 - sigma * np.sqrt(T) if option == 'call': price = S * stats.norm.cdf(d1) - K * np.exp(-r * T) * stats.norm.cdf(d2) else: price = K * np.exp(-r * T) * stats.norm.cdf(-d2) - S * stats.norm.cdf(-d1) return price
S_range = np.linspace(80, 120, 50) T_range = np.linspace(0.1, 1, 50) K = 100 r = 0.05 sigma = 0.2
S_mesh, T_mesh = np.meshgrid(S_range, T_range) option_price = np.zeros_like(S_mesh)
for i in range(len(T_range)): for j in range(len(S_range)): option_price[i, j] = black_scholes(S_mesh[i, j], K, T_mesh[i, j], r, sigma, 'call')
fig = plt.figure(figsize=(12, 8)) ax = fig.add_subplot(111, projection='3d') surf = ax.plot_surface(S_mesh, T_mesh, option_price, cmap=cm.coolwarm, alpha=0.8)
ax.set_xlabel('Stock Price ($)') ax.set_ylabel('Time to Maturity (years)') ax.set_zlabel('Call Option Price ($)') ax.set_title('Black-Scholes Call Option Price')
fig.colorbar(surf, ax=ax, shrink=0.5, aspect=5)
plt.savefig('black_scholes_3d.png') plt.show()
def bs_delta(S, K, T, r, sigma, option='call'): """Calculate option Delta""" d1 = (np.log(S / K) + (r + 0.5 * sigma**2) * T) / (sigma * np.sqrt(T)) if option == 'call': return stats.norm.cdf(d1) else: return stats.norm.cdf(d1) - 1
def bs_gamma(S, K, T, r, sigma): """Calculate option Gamma (same for calls and puts)""" d1 = (np.log(S / K) + (r + 0.5 * sigma**2) * T) / (sigma * np.sqrt(T)) return stats.norm.pdf(d1) / (S * sigma * np.sqrt(T))
def bs_theta(S, K, T, r, sigma, option='call'): """Calculate option Theta""" d1 = (np.log(S / K) + (r + 0.5 * sigma**2) * T) / (sigma * np.sqrt(T)) d2 = d1 - sigma * np.sqrt(T) if option == 'call': theta = -S * stats.norm.pdf(d1) * sigma / (2 * np.sqrt(T)) - r * K * np.exp(-r * T) * stats.norm.cdf(d2) else: theta = -S * stats.norm.pdf(d1) * sigma / (2 * np.sqrt(T)) + r * K * np.exp(-r * T) * stats.norm.cdf(-d2) return theta / 365
S_range = np.linspace(80, 120, 100) T = 0.5
delta_call = [bs_delta(S, K, T, r, sigma, 'call') for S in S_range] delta_put = [bs_delta(S, K, T, r, sigma, 'put') for S in S_range] gamma = [bs_gamma(S, K, T, r, sigma) for S in S_range] theta_call = [bs_theta(S, K, T, r, sigma, 'call') for S in S_range] theta_put = [bs_theta(S, K, T, r, sigma, 'put') for S in S_range]
fig, axs = plt.subplots(3, 1, figsize=(12, 15))
axs[0].plot(S_range, delta_call, 'b-', label='Call Delta') axs[0].plot(S_range, delta_put, 'r-', label='Put Delta') axs[0].axhline(y=0, color='k', linestyle='-', alpha=0.3) axs[0].axvline(x=K, color='k', linestyle='--', alpha=0.3) axs[0].set_xlabel('Stock Price ($)') axs[0].set_ylabel('Delta') axs[0].set_title('Option Delta vs Stock Price') axs[0].grid(True) axs[0].legend()
axs[1].plot(S_range, gamma, 'g-') axs[1].axhline(y=0, color='k', linestyle='-', alpha=0.3) axs[1].axvline(x=K, color='k', linestyle='--', alpha=0.3) axs[1].set_xlabel('Stock Price ($)') axs[1].set_ylabel('Gamma') axs[1].set_title('Option Gamma vs Stock Price') axs[1].grid(True)
axs[2].plot(S_range, theta_call, 'b-', label='Call Theta') axs[2].plot(S_range, theta_put, 'r-', label='Put Theta') axs[2].axhline(y=0, color='k', linestyle='-', alpha=0.3) axs[2].axvline(x=K, color='k', linestyle='--', alpha=0.3) axs[2].set_xlabel('Stock Price ($)') axs[2].set_ylabel('Theta ($ per day)') axs[2].set_title('Option Theta vs Stock Price') axs[2].grid(True) axs[2].legend()
plt.tight_layout() plt.savefig('option_greeks.png') plt.show()
def monte_carlo_option_pricing(S0, K, T, r, sigma, num_simulations=10000, option='call'): """ Price options using Monte Carlo simulation Parameters: S0: Initial stock price K: Strike price T: Time to maturity (in years) r: Risk-free interest rate sigma: Volatility num_simulations: Number of simulation paths option: 'call' or 'put' Returns: Option price """ z = np.random.standard_normal(num_simulations) ST = S0 * np.exp((r - 0.5 * sigma**2) * T + sigma * np.sqrt(T) * z) if option == 'call': payoff = np.maximum(ST - K, 0) else: payoff = np.maximum(K - ST, 0) option_price = np.exp(-r * T) * np.mean(payoff) return option_price, ST
np.random.seed(42) S0 = 100 num_simulations = 10000
mc_price, ST = monte_carlo_option_pricing(S0, K, T, r, sigma, num_simulations, 'call') bs_price = black_scholes(S0, K, T, r, sigma, 'call')
plt.figure(figsize=(12, 6)) plt.hist(ST, bins=50, alpha=0.5, color='blue', density=True)
x = np.linspace(min(ST), max(ST), 100) mu = S0 * np.exp(r * T) std = S0 * np.exp(r * T) * np.sqrt(np.exp(sigma**2 * T) - 1) plt.plot(x, stats.norm.pdf(x, mu, std), 'r-', linewidth=2)
plt.axvline(x=K, color='k', linestyle='--', label=f'Strike Price (K={K})') plt.axvline(x=S0, color='g', linestyle='-', label=f'Initial Price (S0={S0})')
plt.title(f'Monte Carlo Simulation of Stock Prices at Expiration (T={T} years)') plt.xlabel('Stock Price at Expiration ($)') plt.ylabel('Probability Density') plt.legend() plt.grid(True) plt.savefig('monte_carlo_simulation.png') plt.show()
print(f"Monte Carlo Call Option Price: ${mc_price:.4f}") print(f"Black-Scholes Call Option Price: ${bs_price:.4f}") print(f"Difference: ${abs(mc_price - bs_price):.4f}")
|