-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathOptionsMonitor.py
More file actions
583 lines (503 loc) · 26.3 KB
/
OptionsMonitor.py
File metadata and controls
583 lines (503 loc) · 26.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
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
import tkinter as tk
from tkinter import ttk, messagebox
import yfinance as yf
import csv
import os
import sys
from datetime import datetime, time
import pytz
import math
import time as time_module
import threading
from concurrent.futures import ThreadPoolExecutor, as_completed
class OptionsMonitor:
def __init__(self, root):
self.root = root
self.root.title("Options Monitor 1.10")
self.data_file = r"C:\ProgramData\ShadowWhisperer\OptionsMonitor\data.csv"
self.data = self.load_data()
self.price_cache = {}
self.sort_reverse = {}
self.last_market_status = None
self.refresh_interval = None
self.last_interval = "15 Mins"
self.last_updated_label = None
self.DevMode = 0
self.current_sort_col = None
self.current_sort_reverse = False
self.setup_gui()
self.populate_treeview()
threading.Thread(target=self.fetch_initial_prices, daemon=True).start()
def load_data(self):
os.makedirs(os.path.dirname(self.data_file), exist_ok=True)
try:
with open(self.data_file, 'r', newline='') as f:
reader = csv.reader(f)
data = []
for row in reader:
if not row or row[0] == "Ticker": # skip header if present
continue
try:
if len(row) == 6:
premium = float(row[4]) if row[4].strip() else 0.0
data.append([row[0], row[1], row[2], int(row[3]), premium, float(row[5])])
elif len(row) == 5:
premium = float(row[4]) if row[4].strip() else 0.0
data.append([row[0], row[1], row[2], int(row[3]), 0.0, premium])
except ValueError:
continue
return data
except FileNotFoundError:
return []
def save_data(self):
os.makedirs(os.path.dirname(self.data_file), exist_ok=True)
with open(self.data_file, 'w', newline='') as f:
writer = csv.writer(f)
writer.writerow(["Ticker", "Ends", "Option", "Contracts", "Premium", "Strike"])
for row in self.data:
writer.writerow([
row[0],
row[1],
row[2],
str(row[3]),
str(row[4]),
str(row[5])
])
def setup_gui(self):
self.root.grid_rowconfigure(0, weight=1)
self.root.grid_rowconfigure(1, weight=0)
self.root.grid_rowconfigure(2, weight=0)
self.root.grid_columnconfigure(0, weight=1)
cols = ("Ticker", "Ends", "Option", "Contracts", "Premium", "Strike", "Current", "Diff", "Outcome", "Value")
self.tree = ttk.Treeview(self.root, columns=cols, show="headings")
for col in cols:
width = 20
self.tree.heading(col, text=col, command=lambda c=col: self.sort_column(c), anchor="w")
self.tree.column(col, width=width, anchor="w")
self.sort_reverse[col] = False
self.tree.tag_configure('oddrow', background='#f0f0f0')
self.tree.tag_configure('evenrow', background='#ffffff')
self.tree.tag_configure('redrow', background='#ffcccc')
self.tree.tag_configure('green_diff', foreground='green')
self.tree.tag_configure('red_diff', foreground='red')
self.tree.grid(row=0, column=0, pady=2, sticky="nsew")
self.tree.bind("<Double-1>", self.on_double_click)
button_frame = tk.Frame(self.root, height=30)
button_frame.grid(row=1, column=0, pady=2, sticky="ew")
self.refresh_button = tk.Button(button_frame, text="Refresh", command=self.refresh_data, width=10)
self.refresh_button.pack(side="left", padx=(15, 5))
tk.Button(button_frame, text="Add", command=self.add_option, width=10).pack(side="left", padx=(10, 5))
tk.Button(button_frame, text="Remove", command=self.remove_selected, width=10).pack(side="left", padx=(10, 5))
tk.Button(button_frame, text="Remove All", command=self.confirm_remove_all, width=10).pack(side="left", padx=(10, 5))
self.last_updated_label = tk.Label(button_frame, text="")
self.last_updated_label.pack(side="right", padx=1)
self.interval_var = tk.StringVar(value="5 Mins")
self.interval_combo = ttk.Combobox(
button_frame,
textvariable=self.interval_var,
values=["Don't Update", "5 Mins", "10 Mins", "15 Mins", "30 Mins", "1 Hour", "2 Hours"],
width=16, state="readonly"
)
self.interval_combo.pack(side="right", padx=(0, 0))
self.interval_combo.bind("<<ComboboxSelected>>", self.schedule_refresh)
style = ttk.Style()
style.configure("Red.TCombobox", foreground="red")
style.map("Red.TCombobox", foreground=[("disabled", "red")])
self.filter_var = tk.StringVar(value="All")
tk.Radiobutton(button_frame, text="Puts", variable=self.filter_var, value="Put", command=self.populate_treeview).pack(side="right", padx=(1, 1))
tk.Radiobutton(button_frame, text="Calls", variable=self.filter_var, value="Call", command=self.populate_treeview).pack(side="right", padx=(1, 1))
tk.Radiobutton(button_frame, text="All", variable=self.filter_var, value="All", command=self.populate_treeview).pack(side="right", padx=(1, 1))
self.status_frame = tk.Frame(self.root)
self.status_frame.grid(row=2, column=0, sticky="ew")
self.update_market_status()
self.schedule_refresh()
def is_market_open(self):
if self.DevMode == 1:
return True
now = datetime.now(pytz.timezone('US/Eastern'))
return now.weekday() < 5 and time(9, 30) <= now.time() <= time(16, 0)
def update_market_status(self):
now = datetime.now(pytz.timezone('US/Eastern'))
is_open = self.is_market_open()
market_open_time = datetime.combine(now.date(), time(9, 30)).replace(tzinfo=pytz.timezone('US/Eastern'))
time_to_open = (market_open_time - now).total_seconds()
is_near_open = 0 <= time_to_open <= 300
if self.last_market_status != is_open:
self.refresh_button.config(state="normal" if is_open else "disabled")
if is_open:
self.interval_combo.config(values=["Don't Update", "5 Mins", "10 Mins", "15 Mins", "30 Mins", "1 Hour", "2 Hours"], state="readonly", style="TCombobox")
self.interval_var.set(self.last_interval)
self.schedule_refresh()
else:
self.interval_combo.config(values=["Markets Closed"], state="disabled", style="Red.TCombobox")
self.interval_var.set("Markets Closed")
if self.refresh_interval is not None:
self.root.after_cancel(self.refresh_interval)
self.refresh_interval = None
if (is_open and self.last_market_status is False) or (not is_open and self.last_market_status is True):
self.refresh_data()
self.last_market_status = is_open
self.root.after(30000 if is_near_open else 10000, self.update_market_status)
def schedule_refresh(self, event=None):
if self.refresh_interval is not None:
self._just_refreshed = True
self.root.after_cancel(self.refresh_interval)
self.refresh_interval = None
interval = self.interval_var.get()
if interval == "Don't Update" or interval == "Markets Closed":
return
self.last_interval = interval
try:
if "Hour" in interval:
ms = int(interval.replace(" Hour", "").replace("s", "")) * 60 * 60 * 1000
else:
ms = int(interval.replace(" Mins", "")) * 60 * 1000
except ValueError:
return
def refresh_if_open():
if self.is_market_open():
self._just_refreshed = True
self.refresh_data()
self.refresh_interval = self.root.after(ms, refresh_if_open)
self.refresh_interval = self.root.after(ms, refresh_if_open)
def add_option(self):
add_window = tk.Toplevel(self.root)
add_window.title("Add")
add_window.resizable(False, False)
if getattr(sys, 'frozen', False):
add_window.iconbitmap(os.path.join(sys._MEIPASS, 'om.ico'))
else:
add_window.iconbitmap('om.ico')
root_x = self.root.winfo_x()
root_y = self.root.winfo_y()
root_width = self.root.winfo_width()
root_height = self.root.winfo_height()
window_width = 260
window_height = 280
x = root_x + (root_width - window_width) // 2
y = root_y + (root_height - window_height) // 2
add_window.geometry(f"{window_width}x{window_height}+{x}+{y}")
form_frame = tk.Frame(add_window)
form_frame.pack(pady=6, padx=6)
tk.Label(form_frame, text="Ticker").grid(row=0, column=0, sticky="e", padx=4, pady=4)
ticker_entry = tk.Entry(form_frame)
ticker_entry.grid(row=0, column=1, pady=4)
tk.Label(form_frame, text="Option").grid(row=1, column=0, sticky="e", padx=4, pady=4)
call_put_var = tk.StringVar(value="Call")
option_frame = tk.Frame(form_frame)
tk.Radiobutton(option_frame, text="Call", variable=call_put_var, value="Call").pack(side="left")
tk.Radiobutton(option_frame, text="Put", variable=call_put_var, value="Put").pack(side="left")
option_frame.grid(row=1, column=1, pady=4)
tk.Label(form_frame, text="Contracts").grid(row=2, column=0, sticky="e", padx=4, pady=4)
contracts_entry = tk.Entry(form_frame)
contracts_entry.grid(row=2, column=1, pady=4)
tk.Label(form_frame, text="Premium").grid(row=3, column=0, sticky="e", padx=4, pady=4)
premium_entry = tk.Entry(form_frame)
premium_entry.grid(row=3, column=1, pady=4)
tk.Label(form_frame, text="Strike").grid(row=4, column=0, sticky="e", padx=4, pady=4)
strike_entry = tk.Entry(form_frame)
strike_entry.grid(row=4, column=1, pady=4)
tk.Label(form_frame, text="Close (M/D)").grid(row=5, column=0, sticky="e", padx=4, pady=4)
close_date_entry = tk.Entry(form_frame)
close_date_entry.grid(row=5, column=1, pady=4)
tk.Button(add_window, text="Add Option", command=lambda: self._submit_option(
ticker_entry, call_put_var, contracts_entry, premium_entry, strike_entry, close_date_entry, add_window), width=12
).pack(pady=8)
def _submit_option(self, ticker_entry, call_put_var, contracts_entry, premium_entry, strike_entry, close_date_entry, window):
ticker = ticker_entry.get().upper().strip()
call_put = call_put_var.get().capitalize()
contracts = contracts_entry.get().strip()
premium_str = premium_entry.get().strip()
strike_price = strike_entry.get().strip()
close_date = close_date_entry.get().strip()
if close_date and not close_date.count('/') == 1:
messagebox.showerror("Error", "Close must be M/D format or empty.")
return
if ticker and call_put in ["Call", "Put"]:
try:
premium = float(premium_str) if premium_str else 0.0
new_row = [ticker, close_date, call_put, int(contracts), premium, float(strike_price)]
self.data.append(new_row)
self.populate_treeview()
self.save_data()
threading.Thread(target=self.fetch_initial_prices, daemon=True).start()
window.destroy()
except ValueError:
messagebox.showerror("Error", "Check Contracts, Premium & Strike.")
else:
messagebox.showerror("Error", "Invalid Ticker.")
def fetch_price_for_ticker(self, ticker):
for attempt in range(3):
try:
yf_ticker = yf.Ticker(ticker)
quote = yf_ticker.get_info().get('regularMarketPrice', None)
if quote is None or (isinstance(quote, float) and math.isnan(quote)):
history = yf_ticker.history(period="1d")
quote = round(history["Close"].iloc[-1], 2) if not history.empty and not math.isnan(history["Close"].iloc[-1]) else None
result = quote if quote is not None and not math.isnan(quote) else "?"
if self.DevMode == 1:
print(f"[{datetime.now().strftime('%H:%M:%S')}] Lookup {ticker}: {result}")
return ticker, result
except Exception as e:
if self.DevMode == 1:
print(f"[{datetime.now().strftime('%H:%M:%S')}] Lookup {ticker}: Failed, Error: {str(e)}")
if attempt < 2:
time_module.sleep(1)
return ticker, "?"
def fetch_initial_prices(self):
unique_tickers = {row[0] for row in self.data if len(row) == 6}
tickers_to_fetch = [t for t in unique_tickers if t not in self.price_cache or self.price_cache[t] in ["....", "?"]]
# Set initial state
for ticker in tickers_to_fetch:
self.price_cache[ticker] = "...."
if not tickers_to_fetch:
return
# Fetch prices concurrently
with ThreadPoolExecutor(max_workers=10) as executor:
futures = {executor.submit(self.fetch_price_for_ticker, ticker): ticker for ticker in tickers_to_fetch}
for future in as_completed(futures):
ticker, price = future.result()
self.price_cache[ticker] = price
# Update UI after each price is fetched
self.root.after(0, self.populate_treeview)
def populate_treeview(self):
# Clear tree
for item in self.tree.get_children():
self.tree.delete(item)
selected_filter = self.filter_var.get() if hasattr(self, 'filter_var') else "All"
unique_tickers = {row[0] for row in self.data if len(row) == 6}
for ticker in unique_tickers:
if ticker not in self.price_cache:
self.price_cache[ticker] = "...."
for index, row in enumerate(self.data):
if len(row) != 6:
continue
if selected_filter != "All" and row[2] != selected_filter:
continue
ticker, ends, option = row[0], row[1], row[2]
contracts = row[3]
premium = row[4]
strike_price = row[5]
current_price = self.price_cache.get(ticker, "....")
outcome = ""
diff = float('nan')
diff_fmt = ""
value = ""
value_fmt = ""
if current_price not in ["....", "?"] and not math.isnan(current_price):
if option == "Call":
diff = current_price - strike_price
else: # Put
diff = strike_price - current_price
diff_fmt = f"+{round(diff, 2):.2f}" if diff > 0 else f"-{round(abs(diff), 2):.2f}" if diff < 0 else ""
outcome = self.calculate_outcome(option, current_price, strike_price)
intrinsic = max(0.0, diff)
if outcome:
if option == "Put" and outcome == "Purchase":
effective_cost = strike_price - (premium / (contracts * 100)) if contracts > 0 else strike_price
value_num = (current_price - effective_cost) * (contracts * 100)
else:
value_num = (diff * (contracts * 100)) - premium
if option == "Call" and outcome == "Sell":
value_num = -value_num
value = round(value_num, 2)
value_fmt = f"+{value:,.0f}" if value > 0 and value.is_integer() else \
f"+{value:,.2f}" if value > 0 else \
f"{value:,.0f}" if value.is_integer() else f"{value:,.2f}"
else:
value = ""
value_fmt = ""
diff_tag = 'green_diff' if not math.isnan(diff) and diff > 0 else 'red_diff' if not math.isnan(diff) and diff < 0 else ''
strike_price_fmt = int(strike_price) if strike_price == int(strike_price) else round(strike_price, 2)
current_price_fmt = current_price if current_price in ["....", "?"] else (
int(current_price) if current_price == int(current_price) else round(current_price, 2)
)
# Format premium display
premium_fmt = int(premium) if premium == int(premium) else round(premium, 2)
tag = 'redrow' if outcome else ('oddrow' if index % 2 else 'evenrow')
item = self.tree.insert("", "end", tags=(tag, f"list_index_{index}"), values=(
ticker, ends, option, contracts, premium_fmt, strike_price_fmt, current_price_fmt, diff_fmt, outcome, value_fmt
))
if diff_tag:
self.tree.set(item, "Diff", diff_fmt)
# Only update time if price checked
if getattr(self, "_just_refreshed", False):
self.last_updated_label.config(text=f"{datetime.now().strftime('%H:%M:%S')}")
self._just_refreshed = False
def calculate_outcome(self, call_put, current_price, strike_price):
# returns Sell for Calls (if ITM), Purchase for Puts (if ITM)
if call_put == "Put":
return "Purchase" if strike_price > current_price else ""
else: # Call
return "Sell" if strike_price < current_price else ""
def refresh_data(self):
"""Refresh all prices asynchronously"""
self._just_refreshed = True
unique_tickers = {row[0] for row in self.data if len(row) == 6}
if not unique_tickers:
return
with ThreadPoolExecutor(max_workers=10) as executor:
futures = {executor.submit(self.fetch_price_for_ticker, ticker): ticker for ticker in unique_tickers}
for future in as_completed(futures):
ticker, price = future.result()
self.price_cache[ticker] = price
self.root.after(0, self.populate_treeview)
def remove_selected(self):
selected = self.tree.selection()
if selected:
indices_to_drop = []
for item in selected:
tags = self.tree.item(item, "tags")
for tag in tags:
if tag.startswith("list_index_"):
indices_to_drop.append(int(tag.replace("list_index_", "")))
break
if indices_to_drop:
self.data = [row for i, row in enumerate(self.data) if i not in indices_to_drop]
self.populate_treeview()
self.save_data()
def confirm_remove_all(self):
if messagebox.askyesno("Confirm", "Remove all options?"):
self.remove_all()
def remove_all(self):
self.data = []
self.price_cache = {}
self.populate_treeview()
self.save_data()
def sort_column(self, col):
self.current_sort_col = col
self.current_sort_reverse = not self.sort_reverse.get(col, False)
self.sort_reverse[col] = self.current_sort_reverse
# Data rows: [Ticker, Ends, Option, Contracts, Premium, Strike]
def get_sort_key(item):
# item is one of the rows from self.data
if len(item) != 6:
return (float('inf'), "")
ticker = item[0]
if col == "Ticker":
return (item[0], ticker)
if col == "Ends":
try:
month, day = map(int, item[1].split('/'))
current_year = datetime.now().year
return ((current_year, month, day), ticker)
except Exception:
return ((9999, 12, 31), ticker)
if col == "Option":
return (item[2], ticker)
if col == "Contracts":
return (item[3], ticker)
if col == "Premium":
return (item[4], ticker)
if col == "Strike":
return (item[5], ticker)
if col == "Current":
current_price = self.price_cache.get(ticker, float('nan'))
return (current_price, ticker) if current_price not in ["....", "?"] and not math.isnan(current_price) else (float('inf'), ticker)
if col == "Diff":
current_price = self.price_cache.get(ticker, float('nan'))
strike_price = item[5]
if item[2] == "Call":
if current_price not in ["....", "?"] and not math.isnan(current_price):
diff = current_price - strike_price
return (diff, ticker)
else: # Put
if current_price not in ["....", "?"] and not math.isnan(current_price):
diff = strike_price - current_price
return (diff, ticker)
return (float('inf'), ticker)
if col == "Value":
current_price = self.price_cache.get(ticker, float('nan'))
strike_price = item[5]
contracts = item[3]
premium = item[4]
if current_price not in ["....", "?"] and not math.isnan(current_price):
if item[2] == "Call":
intrinsic = max(0.0, current_price - strike_price)
else:
intrinsic = max(0.0, strike_price - current_price)
value = (intrinsic * (contracts * 100)) - premium
return (value, ticker)
return (float('inf'), ticker)
if col == "Outcome":
return (self.calculate_outcome(item[2], self.price_cache.get(ticker, float('nan')) if self.price_cache.get(ticker, float('nan')) not in ["....", "?"] else float('nan'), item[5]), ticker)
return (str(item[0]), ticker)
self.data = sorted(self.data, key=get_sort_key, reverse=self.current_sort_reverse)
self.populate_treeview()
def on_double_click(self, event):
item = self.tree.identify_row(event.y)
if item:
column = self.tree.identify_column(event.x)
if column in ("#1", "#2", "#3", "#4", "#5", "#6"):
self.editing_item = item
self.start_editing(item, column)
def start_editing(self, item, column):
current_value = self.tree.set(item, column)
entry = tk.Entry(self.root)
bbox = self.tree.bbox(item, column)
if bbox:
entry.place(x=bbox[0], y=bbox[1], width=bbox[2], anchor="nw")
entry.insert(0, current_value)
entry.focus_set()
def save_edit(event=None):
new_value_raw = entry.get().strip()
col_map = {"#1": 0, "#2": 1, "#3": 2, "#4": 3, "#5": 4, "#6": 5}
col_index = col_map.get(column)
if col_index is None:
entry.destroy()
return
try:
if col_index == 0: # Ticker
if len(new_value_raw) > 5:
messagebox.showerror("Error", "Ticker cannot exceed 5 characters.")
entry.destroy()
return
new_value = new_value_raw.upper()
elif col_index == 1: # Ends (M/D)
if new_value_raw and not new_value_raw.count('/') == 1:
messagebox.showerror("Error", "Close must be M/D format or empty.")
entry.destroy()
return
new_value = new_value_raw
elif col_index == 2: # Option
new_value = new_value_raw.capitalize()
if new_value not in ["Call", "Put"]:
messagebox.showerror("Error", "Option must be Call or Put.")
entry.destroy()
return
elif col_index == 3: # Contracts
new_value = int(new_value_raw)
elif col_index == 4: # Premium
new_value = float(new_value_raw) if new_value_raw else 0.0
elif col_index == 5: # Strike
new_value = float(new_value_raw)
else:
new_value = new_value_raw
except ValueError:
messagebox.showerror("Error", "Invalid numeric value.")
entry.destroy()
return
row_values = self.tree.item(item, "values")
if row_values:
ticker, ends, option = row_values[0], row_values[1], row_values[2]
strike = float(row_values[5])
for i, row in enumerate(self.data):
if (len(row) == 6 and row[0] == ticker and row[1] == ends
and row[2] == option and row[5] == strike):
self.data[i][col_index] = new_value
break
self.populate_treeview()
self.save_data()
entry.destroy()
entry.bind("<Return>", save_edit)
entry.bind("<FocusOut>", save_edit)
if __name__ == "__main__":
root = tk.Tk()
if getattr(sys, 'frozen', False):
icon_path = os.path.join(sys._MEIPASS, 'om.ico')
else:
icon_path = 'om.ico'
root.iconbitmap(icon_path)
root.geometry("740x300") # Width x Height
app = OptionsMonitor(root)
root.mainloop()