-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
256 lines (223 loc) · 12.3 KB
/
main.py
File metadata and controls
256 lines (223 loc) · 12.3 KB
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
244
245
246
247
248
249
250
251
252
253
254
255
256
import streamlit as st
st.set_page_config(layout="wide", page_title="Options Pricing", page_icon=":gear:")
from datetime import datetime, date, timedelta
from models.abstract import inputs
from models.openai_env import OptionEnv
from models.baseline_tfa_dqn import TFAModel
from option_types import MODELS, USOption, EUOption, ASOption
from polygon import Polygon
from utils.tickers import read_tickers
from utils.db_wrapper import read_rows_of_ticker
POLYGON = Polygon(yf_backup=True)
@st.cache_data
def get_tickers():
return read_tickers()
@st.cache_data
def env_ex(_test):
return _test.simulate_price_data()
@st.cache_data(ttl=60)
def check_nasdaq_status():
return POLYGON.exchange_status("nasdaq")
@st.cache_data(ttl=timedelta(hours=1))
def pull_close_prices():
return POLYGON.last_ticker_prices()
@st.cache_data
def get_custom_defaults():
defaults = {
"maturity": date.today() + timedelta(days=1),
"custom_maturity": date.today() + timedelta(days=365),
"risk_free_rate": POLYGON.risk_free_rate,
"spot": 100.0,
"strike": 100.0,
"implied_volatility": 0.20,
"dividend_rate": 0.01
}
return defaults
DEFAULTS = get_custom_defaults()
ALL_TICKERS = get_tickers()
NASDAQ_STATUS = check_nasdaq_status()
EOD_PRICES = pull_close_prices()
test_defs = {k: v for k, v in DEFAULTS.items() if k != "maturity"}
test_defs["maturity"] = test_defs["custom_maturity"]
test_env = OptionEnv(test_defs)
test_sim_data = env_ex(test_env)
st.title('Quantitative Global Options Pricing (US, EU, & Asian Markets)')
st.caption('Via Black Scholes, Binomial Trees, Monte Carlo Sampling, and a Deep Q-Network Model | By Alejandro Alonso and Roman Chenoweth')
nasdaq, american, eu, asia, dqn = st.tabs(["Options Pricing: NASDAQ-100", "Options Pricing: Custom American Option", "Options Pricing: Custom European Option", "Options Pricing: Custom Asian Option", "411: In-Depth Deep Q-Network Demo"])
with nasdaq:
st.info("Pricing A Range of Options from the NASDAQ-100")
message_type = {"open": st.success, "extended-hours": st.warning, "closed": st.error}
message_type[NASDAQ_STATUS](f"Market Status: {NASDAQ_STATUS.replace('-',' ').title()}")
with st.expander("Note on Data Source"):
st.caption("This project was originally designed to use real-time data from Polygon.io. All the infrastructure is present, however, due to financial constraints, we opted to terminate our subscription to Polygon.io after a month. So while this pricer can be easily reconfigured to use Polygon.io's data, we currently use a combination of EOD data from Polygon.io and Yahoo Finance [this also means you can use this pricer at all hours :) ].")
if True: #NASDAQ_STATUS == "open":
st.info("Unfortunately due to changes made to how yahoo_fin scrapes options data (specifically expiration dates) we are currently unable to showcase this part of the app. We are currently working on a replacement library as you read this :).")
# with st.form("nasdaq-price"):
# cola, colb = st.columns(2)
# ticker = cola.selectbox("Underlying Ticker", ALL_TICKERS)
# maturity = colb.selectbox("Expiration Date", POLYGON.expiration_dates(ticker))
# maturity = datetime.strptime(maturity, '%B %d, %Y').date()
# submit = st.form_submit_button("Update Contract Table", use_container_width=True)
# if submit:
# ticker_contracts = POLYGON.get_ticker_contracts_given_exp(ticker, expiration=maturity)
# ticker_contracts["spot"] = EOD_PRICES[ticker]
# st.dataframe(ticker_contracts, hide_index=True, use_container_width=True,
# column_order=("Contract ID", "Contract Name", "Type", "spot",
# "Strike", "Mark", "Implied Volatility", "Last Trade Date",
# "Last Price", "Bid", "Ask", "Open Interest"),
# column_config={
# "Contract Name": "Full Ticker",
# "Type": "Call/Put",
# "spot": st.column_config.NumberColumn("Spot Price", format="$%.2f"),
# "Strike": st.column_config.NumberColumn("Strike", format="$%.2f"),
# "Mark": st.column_config.NumberColumn("Mark (Mid)", format="$%.2f"),
# "Last Trade Date": "Last Trade Date",
# "Last Price": st.column_config.NumberColumn("Last Trade Price", format="$%.2f"),
# "Bid": st.column_config.NumberColumn("Bid", format="$%.2f"),
# "Ask": st.column_config.NumberColumn("Ask", format="$%.2f"),
# "Open Interest": "OI"
# })
# with st.form("price-contract"):
# cola, colb = st.columns(2)
# opt_id = colb.selectbox("Contract ID", ticker_contracts["Contract ID"])
# model = cola.selectbox("Model", MODELS["us"])
# contract = ticker_contracts.loc[ticker_contracts['Contract ID'] == opt_id].to_dict('records')[0]
# submittwo = st.form_submit_button("Calculate Fair Value", use_container_width=True)
# if submittwo:
# model_name = "all models" if model == "All Models" else f"a {model} model"
# opt = USOption(option_type=contract["Type"],
# strike=contract["Strike"], spot=EOD_PRICES[ticker],
# maturity=maturity,
# implied_volatility=float(contract["Implied Volatility"][:-1].replace(",","")) / 100,
# risk_free_rate=DEFAULTS["risk_free_rate"],
# dividend_rate=0.02)
# if model == "Deep Q-Network": st.warning("Options Pricing with the DQN may take a few minutes")
# with st.spinner(f"Pricing {ticker} option #{opt_id} using {model_name}..."):
# if model == "all models":
# priced_options = opt.all()
# else:
# priced_options = [opt.priced(model)]
# st.info(f"Contract Mark: {contract['Mark']}")
# for priced_option in priced_options:
# priced_option.st_visualize()
with american:
st.info("Price a Custom American Option")
with st.form("american-price"):
opttype, s0, k, volatility, risk_free_r, d, maturity, model, submit = inputs(MODELS["us"], DEFAULTS)
if (maturity - date.today()) / timedelta(days=1) < 0:
st.error("Contract Expired")
elif submit:
model_name = "all models" if model == "All Models" else f"a {model} model"
opt = USOption(option_type=opttype,
strike=k, spot=s0,
maturity=maturity,
implied_volatility=volatility,
risk_free_rate=risk_free_r,
dividend_rate=d)
if model == "Deep Q-Network": st.warning("Options Pricing with the DQN may take a few minutes")
with st.spinner(f"Pricing custom option spread using {model_name}..."):
if model == "all models":
priced_options = opt.all()
else:
priced_options = [opt.priced(model)]
for priced_option in priced_options:
priced_option.st_visualize()
with eu:
st.info("Price a Custom European Option")
with st.form("euro-price"):
opttype, s0, k, volatility, risk_free_r, d, maturity, model, submit = inputs(MODELS["eu"], DEFAULTS)
if (maturity - date.today()) / timedelta(days=1) < 0:
st.error("Contract Expired")
elif submit:
if maturity - date.today() < timedelta(days=1):
st.error("Maturity Date Already Passed")
else:
model_name = "all models" if model == "All Models" else f"a {model} model"
opt = EUOption(option_type=opttype,
strike=k, spot=s0,
maturity=maturity,
implied_volatility=volatility,
risk_free_rate=risk_free_r,
dividend_rate=d)
with st.spinner(f"Pricing custom option spread using {model_name}..."):
if model == "all models":
priced_options = opt.all()
else:
priced_options = [opt.priced(model)]
for priced_option in priced_options:
priced_option.st_visualize()
with asia:
st.info("Price a Custom Asian Option")
with st.form("asia-price"):
opttype, s0, k, volatility, risk_free_r, d, maturity, model, submit = inputs(MODELS["as"], DEFAULTS)
if (maturity - date.today()) / timedelta(days=1) < 0:
st.error("Contract Expired")
elif submit:
if maturity - date.today() < timedelta(days=1):
st.error("Maturity Date Already Passed")
else:
model_name = "all models" if model == "All Models" else f"a {model} model"
opt = ASOption(option_type=opttype,
strike=k, spot=s0,
maturity=maturity,
implied_volatility=volatility,
risk_free_rate=risk_free_r,
dividend_rate=d)
with st.spinner(f"Pricing custom option spread using {model_name}..."):
if model == "all models":
priced_options = opt.all()
else:
priced_options = [opt.priced(model)]
for priced_option in priced_options:
priced_option.st_visualize()
with dqn:
st.info("Deep Q-Network Breakdown")
st.subheader("Test Option Specs")
del test_defs["custom_maturity"]
ncols = len(test_defs)
def_keys = list(test_defs.keys())
columns = st.columns(ncols)
for n in range(ncols):
key = def_keys[n]
value = test_defs[key] if key != "maturity" else test_defs[key].strftime("%m/%d/%Y")
columns[n].metric(key.replace("_"," ").title(), str(value)[:10])
st.divider()
st.subheader("Simulated Option Data (Assuming No Early Excercise)")
sim_data = {"Option Price": test_sim_data, "Time-Steps": list(range(366))}
st.line_chart(sim_data, x="Time-Steps", y="Option Price")
st.divider()
st.subheader("Deep Q-Network Specs")
with st.form("Define Specs"):
cola, colb, colc, cold = st.columns(4)
n_iterations = cola.number_input("Number of Iterations", min_value=1, max_value=20000, value=200, step=1)
eval_interval = colb.number_input("Evaluate Return Every _ Steps", min_value=1, max_value=10000, value=50, step=1)
log_interval = colc.number_input("Log Every _ Steps", min_value=1, max_value=20000, value=10, step=1)
n_sims = cold.number_input("Number of Simulation Episodes", min_value=1, max_value=2000, value=20, step=1)
go = st.form_submit_button("Price Demo Option", use_container_width=True)
if eval_interval > n_iterations or log_interval > n_iterations:
st.error("Evaluation and Log Intervals must be less than the total number of iterations")
elif go:
st.subheader("Model")
tfa = TFAModel(OptionEnv, test_defs, iterations=n_iterations, eval_interval=eval_interval, log_interval=log_interval, n_sims=n_sims)
with st.status("Building Model...", expanded=True) as status:
st.write("Initializing Agent...")
tfa.init_agent()
st.write("Done | Building Replay Buffer...")
tfa.build_replay_buffer()
st.write("Done | Preparing to Train...")
tfa.train()
status.update(label="Model Built - Pricing Option", state="running", expanded=True)
tfa.calculate_npv()
status.update(label="Option Pricing Complete", state="complete", expanded=False)
st.divider()
tfa.st_visualize()
# with pull:
# with st.form("tmp_pull"):
# tmpkey = st.text_input("Polygon.io Key")
# pwd = st.text_input("Admin Passphrase")
# submitted = st.form_submit_button("Pull", use_container_width=True)
# if submitted:
# key = tmpkey if tmpkey.strip() != "" else None
# if pwd == "______":
# with st.spinner("Pulling..."):
# Polygon(key=key).store_eod_data()