-
Notifications
You must be signed in to change notification settings - Fork 0
/
BSOPM2.py
243 lines (201 loc) · 8.89 KB
/
BSOPM2.py
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
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
import streamlit as st
import pandas as pd
import numpy as np
from scipy.stats import norm
import plotly.graph_objects as go
from numpy import log, sqrt, exp # Make sure to import these
import matplotlib.pyplot as plt
import seaborn as sns
#######################
# Page configuration
st.set_page_config(
page_title="Black-Scholes Option Pricing Model",
page_icon="📊",
layout="wide",
initial_sidebar_state="expanded")
# Custom CSS to inject into Streamlit
st.markdown("""
<style>
/* Adjust the size and alignment of the CALL and PUT value containers */
.metric-container {
display: flex;
justify-content: center;
align-items: center;
padding: 8px; /* Adjust the padding to control height */
width: auto; /* Auto width for responsiveness, or set a fixed width if necessary */
margin: 0 auto; /* Center the container */
}
/* Custom classes for CALL and PUT values */
.metric-call {
background-color: #90ee90; /* Light green background */
color: black; /* Black font color */
margin-right: 10px; /* Spacing between CALL and PUT */
border-radius: 10px; /* Rounded corners */
}
.metric-put {
background-color: #ffcccb; /* Light red background */
color: black; /* Black font color */
border-radius: 10px; /* Rounded corners */
}
/* Style for the value text */
.metric-value {
font-size: 1.5rem; /* Adjust font size */
font-weight: bold;
margin: 0; /* Remove default margins */
}
/* Style for the label text */
.metric-label {
font-size: 1rem; /* Adjust font size */
margin-bottom: 4px; /* Spacing between label and value */
}
</style>
""", unsafe_allow_html=True)
# (Include the BlackScholes class definition here)
class BlackScholes:
def __init__(
self,
time_to_maturity: float,
strike: float,
current_price: float,
volatility: float,
interest_rate: float,
):
self.time_to_maturity = time_to_maturity
self.strike = strike
self.current_price = current_price
self.volatility = volatility
self.interest_rate = interest_rate
def calculate_prices(
self,
):
time_to_maturity = self.time_to_maturity
strike = self.strike
current_price = self.current_price
volatility = self.volatility
interest_rate = self.interest_rate
d1 = (
log(current_price / strike) +
(interest_rate + 0.5 * volatility ** 2) * time_to_maturity
) / (
volatility * sqrt(time_to_maturity)
)
d2 = d1 - volatility * sqrt(time_to_maturity)
call_price = current_price * norm.cdf(d1) - (
strike * exp(-(interest_rate * time_to_maturity)) * norm.cdf(d2)
)
put_price = (
strike * exp(-(interest_rate * time_to_maturity)) * norm.cdf(-d2)
) - current_price * norm.cdf(-d1)
self.call_price = call_price
self.put_price = put_price
# GREEKS
# Delta
self.call_delta = norm.cdf(d1)
self.put_delta = 1 - norm.cdf(d1)
# Gamma
self.call_gamma = norm.pdf(d1) / (
strike * volatility * sqrt(time_to_maturity)
)
self.put_gamma = self.call_gamma
return call_price, put_price
# Function to generate heatmaps
# ... your existing imports and BlackScholes class definition ...
# Sidebar for User Inputs
with st.sidebar:
st.title("📊 Black-Scholes Model")
st.markdown("<h4 style='font-size: 20px;'>Created by:</h4>", unsafe_allow_html=True) # Set font size for the "Created by" text
linkedin_url = "https://www.linkedin.com/in/mkulis/"
st.markdown(f'<a href="{linkedin_url}" target="_blank" style="text-decoration: underline; color: inherit; text-decoration-color: blue; font-size: 20px;"><img src="https://cdn-icons-png.flaticon.com/512/174/174857.png" width="25" height="25" style="vertical-align: middle; margin-right: 10px;">Matthew A. Kulis</a>', unsafe_allow_html=True) # Set font size for "Matt Kulis"
github_url = "https://github.com/Mattkulis/BlackScholesOPM"
st.markdown(f'<a href="{github_url}" target="_blank" style="text-decoration: underline; color: inherit; text-decoration-color: blue; font-size: 20px;"><img src="https://cdn-icons-png.flaticon.com/128/2504/2504911.png" width="25" height="25" style="vertical-align: middle; margin-right: 10px;">GitHub Repository</a>', unsafe_allow_html=True) # Set font size for GitHub link
current_price = st.number_input("Current Asset Price", value=100.0)
strike = st.number_input("Strike Price", value=100.0)
time_to_maturity = st.number_input("Time to Maturity (Years)", value=1.0)
volatility = st.number_input("Volatility (σ)", value=0.2)
interest_rate = st.number_input("Risk-Free Interest Rate", value=0.05)
st.markdown("---")
calculate_btn = st.button('Heatmap Parameters')
spot_min = st.number_input('Min Spot Price', min_value=0.01, value=current_price*0.8, step=0.01)
spot_max = st.number_input('Max Spot Price', min_value=0.01, value=current_price*1.2, step=0.01)
vol_min = st.slider('Min Volatility for Heatmap', min_value=0.01, max_value=1.0, value=volatility*0.5, step=0.01)
vol_max = st.slider('Max Volatility for Heatmap', min_value=0.01, max_value=1.0, value=volatility*1.5, step=0.01)
spot_range = np.linspace(spot_min, spot_max, 10)
vol_range = np.linspace(vol_min, vol_max, 10)
def plot_heatmap(bs_model, spot_range, vol_range, strike):
call_prices = np.zeros((len(vol_range), len(spot_range)))
put_prices = np.zeros((len(vol_range), len(spot_range)))
for i, vol in enumerate(vol_range):
for j, spot in enumerate(spot_range):
bs_temp = BlackScholes(
time_to_maturity=bs_model.time_to_maturity,
strike=strike,
current_price=spot,
volatility=vol,
interest_rate=bs_model.interest_rate
)
bs_temp.calculate_prices()
call_prices[i, j] = bs_temp.call_price
put_prices[i, j] = bs_temp.put_price
# Plotting Call Price Heatmap
fig_call, ax_call = plt.subplots(figsize=(10, 8))
sns.heatmap(call_prices, xticklabels=np.round(spot_range, 2), yticklabels=np.round(vol_range, 2), annot=True, fmt=".2f", cmap="RdYlGn", ax=ax_call)
ax_call.set_title('CALL')
ax_call.set_xlabel('Spot Price')
ax_call.set_ylabel('Volatility')
# Plotting Put Price Heatmap
fig_put, ax_put = plt.subplots(figsize=(10, 8))
sns.heatmap(put_prices, xticklabels=np.round(spot_range, 2), yticklabels=np.round(vol_range, 2), annot=True, fmt=".2f", cmap="RdYlGn", ax=ax_put)
ax_put.set_title('PUT')
ax_put.set_xlabel('Spot Price')
ax_put.set_ylabel('Volatility')
return fig_call, fig_put
# Main Page for Output Display
st.title("Black-Scholes Pricing Model")
# Table of Inputs
input_data = {
"Current Asset Price": [current_price],
"Strike Price": [strike],
"Time to Maturity (Years)": [time_to_maturity],
"Volatility (σ)": [volatility],
"Risk-Free Interest Rate": [interest_rate],
}
input_df = pd.DataFrame(input_data)
st.table(input_df)
# Calculate Put and Call values
bs_model = BlackScholes(time_to_maturity, strike, current_price, volatility, interest_rate)
call_price, put_price = bs_model.calculate_prices()
# Display Call and Put Values in colored tables
col1, col2 = st.columns([1,1], gap="small")
with col1:
# Using the custom class for CALL value
st.markdown(f"""
<div class="metric-container metric-call">
<div>
<div class="metric-label">CALL Value</div>
<div class="metric-value">${call_price:.2f}</div>
</div>
</div>
""", unsafe_allow_html=True)
with col2:
# Using the custom class for PUT value
st.markdown(f"""
<div class="metric-container metric-put">
<div>
<div class="metric-label">PUT Value</div>
<div class="metric-value">${put_price:.2f}</div>
</div>
</div>
""", unsafe_allow_html=True)
st.markdown("")
st.title("Options Price - Interactive Heatmap")
st.info("Explore how option prices fluctuate with varying 'Spot Prices and Volatility' levels using interactive heatmap parameters, all while maintaining a constant 'Strike Price'.")
# Interactive Sliders and Heatmaps for Call and Put Options
col1, col2 = st.columns([1,1], gap="small")
with col1:
st.subheader("Call Price Heatmap")
heatmap_fig_call, _ = plot_heatmap(bs_model, spot_range, vol_range, strike)
st.pyplot(heatmap_fig_call)
with col2:
st.subheader("Put Price Heatmap")
_, heatmap_fig_put = plot_heatmap(bs_model, spot_range, vol_range, strike)
st.pyplot(heatmap_fig_put)