Skip to content

Commit bb00f2d

Browse files
committed
adding codes
1 parent 384df4a commit bb00f2d

File tree

4 files changed

+325
-0
lines changed

4 files changed

+325
-0
lines changed

doc/Programs/BlackScholes/bs.py

Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
import math
2+
from scipy.stats import norm
3+
4+
def black_scholes_call_price(S, K, T, r, sigma):
5+
"""
6+
Analytical solution to the Black-Scholes formula for a European call option.
7+
8+
Parameters:
9+
S - Current stock price
10+
K - Strike price
11+
T - Time to maturity (in years)
12+
r - Risk-free interest rate
13+
sigma - Volatility of the underlying asset
14+
15+
Returns:
16+
Call option price
17+
"""
18+
d1 = (math.log(S / K) + (r + 0.5 * sigma ** 2) * T) / (sigma * math.sqrt(T))
19+
d2 = d1 - sigma * math.sqrt(T)
20+
21+
call_price = S * norm.cdf(d1) - K * math.exp(-r * T) * norm.cdf(d2)
22+
return call_price
23+
24+
# Example usage
25+
S = 100 # Stock price
26+
K = 100 # Strike price
27+
T = 1 # Time to maturity (1 year)
28+
r = 0.05 # Risk-free interest rate
29+
sigma = 0.2 # Volatility
30+
31+
price = black_scholes_call_price(S, K, T, r, sigma)
32+
print(f"European Call Option Price: {price:.4f}")
33+
34+
35+
36+
# simple numerical solution with plain explicit finite difference
37+
38+
39+
import numpy as np
40+
import matplotlib.pyplot as plt
41+
42+
def black_scholes_fd_explicit(S_max, K, T, r, sigma, M=100, N=100):
43+
"""
44+
Finite Difference Method (Explicit Scheme) for Black-Scholes Equation
45+
46+
Parameters:
47+
S_max - Maximum stock price considered
48+
K - Strike price
49+
T - Time to maturity
50+
r - Risk-free interest rate
51+
sigma - Volatility
52+
M - Number of time steps
53+
N - Number of price steps
54+
55+
Returns:
56+
S - Stock prices
57+
V - Option values at t=0
58+
"""
59+
dt = T / M
60+
dS = S_max / N
61+
S = np.linspace(0, S_max, N + 1)
62+
V = np.maximum(S - K, 0) # Terminal payoff for a call option
63+
64+
for j in range(M):
65+
V_old = V.copy()
66+
for i in range(1, N):
67+
delta = (V_old[i + 1] - V_old[i - 1]) / (2 * dS)
68+
gamma = (V_old[i + 1] - 2 * V_old[i] + V_old[i - 1]) / (dS ** 2)
69+
V[i] = V_old[i] + dt * (0.5 * sigma ** 2 * S[i] ** 2 * gamma +
70+
r * S[i] * delta - r * V_old[i])
71+
V[0] = 0 # Option worthless if stock price is 0
72+
V[-1] = S_max - K * np.exp(-r * (T - (j + 1) * dt)) # Approximate boundary condition
73+
74+
return S, V
75+
76+
# Parameters
77+
S_max = 200
78+
K = 100
79+
T = 1
80+
r = 0.05
81+
sigma = 0.2
82+
83+
S, V = black_scholes_fd_explicit(S_max, K, T, r, sigma)
84+
plt.plot(S, V)
85+
plt.xlabel("Stock Price")
86+
plt.ylabel("Option Value")
87+
plt.title("European Call Option Price via Finite Difference Method")
88+
plt.grid(True)
89+
plt.show()
Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
import math
2+
from scipy.stats import norm
3+
4+
def black_scholes_call_price(S, K, T, r, sigma):
5+
"""
6+
Analytical solution to the Black-Scholes formula for a European call option.
7+
8+
Parameters:
9+
S - Current stock price
10+
K - Strike price
11+
T - Time to maturity (in years)
12+
r - Risk-free interest rate
13+
sigma - Volatility of the underlying asset
14+
15+
Returns:
16+
Call option price
17+
"""
18+
d1 = (math.log(S / K) + (r + 0.5 * sigma ** 2) * T) / (sigma * math.sqrt(T))
19+
d2 = d1 - sigma * math.sqrt(T)
20+
21+
call_price = S * norm.cdf(d1) - K * math.exp(-r * T) * norm.cdf(d2)
22+
return call_price
23+
24+
# Example usage
25+
S = 100 # Stock price
26+
K = 100 # Strike price
27+
T = 1 # Time to maturity (1 year)
28+
r = 0.05 # Risk-free interest rate
29+
sigma = 0.2 # Volatility
30+
31+
price = black_scholes_call_price(S, K, T, r, sigma)
32+
print(f"European Call Option Price: {price:.4f}")
33+
34+
35+
36+
# simple numerical solution with plain explicit finite difference
37+
38+
39+
import numpy as np
40+
import matplotlib.pyplot as plt
41+
42+
def black_scholes_fd_explicit(S_max, K, T, r, sigma, M=100, N=100):
43+
"""
44+
Finite Difference Method (Explicit Scheme) for Black-Scholes Equation
45+
46+
Parameters:
47+
S_max - Maximum stock price considered
48+
K - Strike price
49+
T - Time to maturity
50+
r - Risk-free interest rate
51+
sigma - Volatility
52+
M - Number of time steps
53+
N - Number of price steps
54+
55+
Returns:
56+
S - Stock prices
57+
V - Option values at t=0
58+
"""
59+
dt = T / M
60+
dS = S_max / N
61+
S = np.linspace(0, S_max, N + 1)
62+
V = np.maximum(S - K, 0) # Terminal payoff for a call option
63+
64+
for j in range(M):
65+
V_old = V.copy()
66+
for i in range(1, N):
67+
delta = (V_old[i + 1] - V_old[i - 1]) / (2 * dS)
68+
gamma = (V_old[i + 1] - 2 * V_old[i] + V_old[i - 1]) / (dS ** 2)
69+
V[i] = V_old[i] + dt * (0.5 * sigma ** 2 * S[i] ** 2 * gamma +
70+
r * S[i] * delta - r * V_old[i])
71+
V[0] = 0 # Option worthless if stock price is 0
72+
V[-1] = S_max - K * np.exp(-r * (T - (j + 1) * dt)) # Approximate boundary condition
73+
74+
return S, V
75+
76+
# Parameters
77+
S_max = 200
78+
K = 100
79+
T = 1
80+
r = 0.05
81+
sigma = 0.2
82+
83+
S, V = black_scholes_fd_explicit(S_max, K, T, r, sigma)
84+
plt.plot(S, V)
85+
plt.xlabel("Stock Price")
86+
plt.ylabel("Option Value")
87+
plt.title("European Call Option Price via Finite Difference Method")
88+
plt.grid(True)
89+
plt.show()

doc/Programs/BlackScholes/bsfdm.py

Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
import math
2+
from scipy.stats import norm
3+
4+
def black_scholes_call_price(S, K, T, r, sigma):
5+
"""
6+
Analytical solution to the Black-Scholes formula for a European call option.
7+
8+
Parameters:
9+
S - Current stock price
10+
K - Strike price
11+
T - Time to maturity (in years)
12+
r - Risk-free interest rate
13+
sigma - Volatility of the underlying asset
14+
15+
Returns:
16+
Call option price
17+
"""
18+
d1 = (math.log(S / K) + (r + 0.5 * sigma ** 2) * T) / (sigma * math.sqrt(T))
19+
d2 = d1 - sigma * math.sqrt(T)
20+
21+
call_price = S * norm.cdf(d1) - K * math.exp(-r * T) * norm.cdf(d2)
22+
return call_price
23+
24+
# Example usage
25+
S = 100 # Stock price
26+
K = 100 # Strike price
27+
T = 1 # Time to maturity (1 year)
28+
r = 0.05 # Risk-free interest rate
29+
sigma = 0.2 # Volatility
30+
31+
price = black_scholes_call_price(S, K, T, r, sigma)
32+
print(f"European Call Option Price: {price:.4f}")
33+
34+
35+
36+
# simple numerical solution with plain explicit finite difference
37+
38+
39+
import numpy as np
40+
import matplotlib.pyplot as plt
41+
42+
def black_scholes_fd_explicit(S_max, K, T, r, sigma, M=100, N=100):
43+
"""
44+
Finite Difference Method (Explicit Scheme) for Black-Scholes Equation
45+
46+
Parameters:
47+
S_max - Maximum stock price considered
48+
K - Strike price
49+
T - Time to maturity
50+
r - Risk-free interest rate
51+
sigma - Volatility
52+
M - Number of time steps
53+
N - Number of price steps
54+
55+
Returns:
56+
S - Stock prices
57+
V - Option values at t=0
58+
"""
59+
dt = T / M
60+
dS = S_max / N
61+
S = np.linspace(0, S_max, N + 1)
62+
V = np.maximum(S - K, 0) # Terminal payoff for a call option
63+
64+
for j in range(M):
65+
V_old = V.copy()
66+
for i in range(1, N):
67+
delta = (V_old[i + 1] - V_old[i - 1]) / (2 * dS)
68+
gamma = (V_old[i + 1] - 2 * V_old[i] + V_old[i - 1]) / (dS ** 2)
69+
V[i] = V_old[i] + dt * (0.5 * sigma ** 2 * S[i] ** 2 * gamma +
70+
r * S[i] * delta - r * V_old[i])
71+
V[0] = 0 # Option worthless if stock price is 0
72+
V[-1] = S_max - K * np.exp(-r * (T - (j + 1) * dt)) # Approximate boundary condition
73+
74+
return S, V
75+
76+
# Parameters
77+
S_max = 200
78+
K = 100
79+
T = 1
80+
r = 0.05
81+
sigma = 0.2
82+
83+
S, V = black_scholes_fd_explicit(S_max, K, T, r, sigma)
84+
plt.plot(S, V)
85+
plt.xlabel("Stock Price")
86+
plt.ylabel("Option Value")
87+
plt.title("European Call Option Price via Finite Difference Method")
88+
plt.grid(True)
89+
plt.show()

doc/Programs/BlackScholes/bsmc.py

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
# Monte Carlo implementation (With Antithetic Variates)
2+
import numpy as np
3+
def monte_carlo_black_scholes_option(S0, K, T, r, sigma,
4+
num_simulations=100000,
5+
option_type='call',
6+
use_antithetic=True):
7+
"""
8+
Monte Carlo simulation for European call/put option with variance reduction.
9+
10+
Parameters:
11+
S0 - Initial stock price
12+
K - Strike price
13+
T - Time to maturity (in years)
14+
r - Risk-free interest rate
15+
sigma - Volatility
16+
num_simulations - Number of Monte Carlo simulations
17+
option_type - 'call' or 'put'
18+
use_antithetic - Whether to use antithetic variates for variance reduction
19+
20+
Returns:
21+
Estimated option price
22+
"""
23+
n = num_simulations // 2 if use_antithetic else num_simulations
24+
Z = np.random.normal(size=n)
25+
26+
# Simulate asset prices at maturity
27+
ST1 = S0 * np.exp((r - 0.5 * sigma**2) * T + sigma * np.sqrt(T) * Z)
28+
29+
if use_antithetic:
30+
ST2 = S0 * np.exp((r - 0.5 * sigma**2) * T - sigma * np.sqrt(T) * Z)
31+
ST = np.concatenate([ST1, ST2])
32+
else:
33+
ST = ST1
34+
35+
# Calculate payoff
36+
if option_type.lower() == 'call':
37+
payoff = np.maximum(ST - K, 0)
38+
elif option_type.lower() == 'put':
39+
payoff = np.maximum(K - ST, 0)
40+
else:
41+
raise ValueError("option_type must be 'call' or 'put'")
42+
43+
# Discount to present value
44+
price = np.exp(-r * T) * np.mean(payoff)
45+
return price
46+
47+
# Example usage
48+
S0 = 100
49+
K = 100
50+
T = 1
51+
r = 0.05
52+
sigma = 0.2
53+
54+
call_price = monte_carlo_black_scholes_option(S0, K, T, r, sigma, option_type='call')
55+
put_price = monte_carlo_black_scholes_option(S0, K, T, r, sigma, option_type='put')
56+
57+
print(f"Monte Carlo Estimated Call Price (Antithetic): {call_price:.4f}")
58+
print(f"Monte Carlo Estimated Put Price (Antithetic): {put_price:.4f}")

0 commit comments

Comments
 (0)