-
Notifications
You must be signed in to change notification settings - Fork 0
/
GuiOptions.py
693 lines (599 loc) · 31.8 KB
/
GuiOptions.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
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
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
#!/usr/bin/env python3
import tkinter as tk
import pandas as pd
from tkinter.ttk import Style
from tkinter import messagebox
import sys
# noinspection SpellCheckingInspection
import datetime
# noinspection SpellCheckingInspection
import tkcalendar as cal
from DbFinance import FinanceDB
import Utilities
from AddPosition import AddPosition as addPos
from ListPositions import ListPositions as listPos
from ChartOptions import ChartOptions
from matplotlib.backends.backend_tkagg import (FigureCanvasTkAgg, NavigationToolbar2Tk)
from matplotlib.figure import Figure
from dateutil import parser
from Prediction import Prediction
import argparse
# noinspection PyUnusedLocal
class GuiOptions(tk.ttk.Frame):
def __init__(self, root):
super().__init__()
self.tk_root = root
self.close_button = None
# self.surface_chart_button = None
# self.line_chart_button = None
# self.strike_chart_button = None
self.delete_option_button = None
self.status_label = None
self.plot_frame = None
self.symbol_var = tk.StringVar(self)
self.expiration_var = tk.StringVar(self)
self.strike_var = tk.StringVar(self)
self.is_date_filter_on = tk.IntVar(value=0)
self.start_date = None
self.end_date = None
self.shadow_expiration = dict()
self.popup_symbol_menu = None
self.popup_expiration_menu = None
self.popup_strike_menu = None
self.start_cal = None
self.end_cal = None
self.status_var = tk.StringVar(self)
self.bid_extrinsic_value = tk.IntVar(self)
self.init_ui()
arg_parser = argparse.ArgumentParser()
arg_parser.add_argument('-d', '--db', action='store', type=str, help="Database to use")
args = arg_parser.parse_args()
database = args.db
self.clear_symbol_menu()
self.clear_expiration_menu()
self.clear_strike_menu()
self.toggle_date_filter()
self.update_chart_button_enable()
if database is not None:
self.options_db = FinanceDB(db_name_schema=database)
else:
self.options_db = FinanceDB()
self.options_db.initialize()
self.get_symbols()
self.extrinsic_value_radio = None
self.bid_value_radio = None
def get_symbols(self):
df_symbols = self.options_db.get_all_symbols()
symbol_set = []
for i_row, symbol_row in df_symbols.iterrows():
symbol_set.append(symbol_row["symbol"])
symbol_set = sorted(symbol_set)
self.update_symbols(symbol_set)
# noinspection PyUnusedLocal
@staticmethod
def quit_app(event):
print("Exit command")
sys.exit()
def clear_plot_frame(self):
for widget in self.plot_frame.winfo_children():
widget.destroy()
def delete_option(self, event):
if not self.expiration_var.get():
message = "Do you want to delete all options for symbol {0}?".format(self.symbol_var.get())
else:
message = "Do you want to delete all options for symbol {0} with expiration date {1}?". \
format(self.symbol_var.get(), self.expiration_var.get())
answer = tk.messagebox.askquestion("Delete Option", message, icon='warning')
if answer == 'yes':
option_expire_id = -1
if self.expiration_var.get() != ' ':
row = self.shadow_expiration[self.expiration_var.get()]
option_expire_id = row['option_expire_id']
symbol = self.symbol_var.get()
self.options_db.delete_options(symbol, option_expire_id)
self.clear_symbol_menu()
self.clear_expiration_menu()
self.clear_strike_menu()
self.get_symbols()
else:
print("not deleted....")
# noinspection PyUnusedLocal
def create_line_chart(self, event=None):
self.close_button.focus_force()
self.status_var.set("Creating chart...")
self.update()
self.update_idletasks()
if bool(self.shadow_expiration):
self.clear_plot_frame()
fig = Figure(figsize=(10, 6))
canvas = FigureCanvasTkAgg(fig, master=self.plot_frame)
chart = ChartOptions()
row = self.shadow_expiration[self.expiration_var.get()]
success = chart.prepare_options(self.options_db,
self.symbol_var.get(),
row["option_expire_id"], put_call="CALL",
start_date=self.start_date,
end_date=self.end_date,
option_type='extrinsic' if self.bid_extrinsic_value.get() == 1 else 'bid')
if success:
chart.line_chart_option(fig, self.symbol_var.get(),
self.options_db.get_name_for_symbol(self.symbol_var.get()),
"Call", row["expire_date"])
self.show_figure(canvas)
self.status_var.set("Done")
else:
self.status_var.set("No data available")
# noinspection PyUnusedLocal
def create_surface_chart(self):
self.close_button.focus_force()
self.status_var.set("Creating chart...")
self.update()
self.update_idletasks()
if bool(self.shadow_expiration):
self.clear_plot_frame()
fig = Figure(figsize=(10, 6))
canvas = FigureCanvasTkAgg(fig, master=self.plot_frame)
chart = ChartOptions()
row = self.shadow_expiration[self.expiration_var.get()]
success = chart.prepare_options(self.options_db,
self.symbol_var.get(),
row["option_expire_id"], put_call="CALL",
start_date=self.start_date,
end_date=self.end_date,
option_type='extrinsic' if self.bid_extrinsic_value.get() == 1 else 'bid')
if success:
chart.surface_chart_option(fig, self.symbol_var.get(),
self.options_db.get_name_for_symbol(self.symbol_var.get()),
"Call", row["expire_date"])
self.show_figure(canvas)
self.status_var.set("Done")
else:
self.status_var.set("No data available")
def create_current_bid_ask_chart(self, event=None):
self.create_current_bar_chart(bid_ask=True)
def create_current_delta_theta_chart(self, event=None):
self.create_current_bar_chart(bid_ask=False)
def create_current_bar_chart(self, bid_ask:bool):
self.close_button.focus_force()
self.status_var.set("Creating Bid/Ask...")
self.update()
self.update_idletasks()
if bool(self.shadow_expiration):
success = False
self.clear_plot_frame()
fig = Figure(figsize=(10, 6))
canvas = FigureCanvasTkAgg(fig, master=self.plot_frame)
chart = ChartOptions()
row = self.shadow_expiration[self.expiration_var.get()]
web = Utilities.get_options_API()
expire_date = self.options_db.get_expire_date_from_id(row["option_expire_id"]).strftime('%Y-%m-%d')
option = web.get_options_for_symbol_and_expiration(self.symbol_var.get(), expire_date, put_call="CALL")
success = False
if bool(option) and type(option["options_chain"]["calls"]) == pd.DataFrame:
if bid_ask is True:
success = chart.create_bid_ask_bar_chart(fig,
self.symbol_var.get(),
self.options_db.get_name_for_symbol(self.symbol_var.get()),
row["expire_date"],
option["current_value"],
option["options_chain"]["calls"],
put_call="CALL")
else:
success = chart.create_delta_theta_bar_chart(fig,
self.symbol_var.get(),
self.options_db.get_name_for_symbol(self.symbol_var.get()),
row["expire_date"],
option["current_value"],
option["options_chain"]["calls"],
put_call="CALL")
if success:
self.show_figure(canvas)
self.status_var.set("Done")
else:
self.status_var.set("No data available")
# noinspection PyUnusedLocal
def create_strike_profit_chart(self, event=None):
self.close_button.focus_force()
self.status_var.set("Creating strike chart...")
self.update()
self.update_idletasks()
def training_event(message):
self.status_var.set(message)
self.update()
self.update_idletasks()
if bool(self.shadow_expiration) and self.strike_var.get() != "":
self.clear_plot_frame()
fig = Figure(figsize=(10, 6))
canvas = FigureCanvasTkAgg(fig, master=self.plot_frame)
chart = ChartOptions()
row = self.shadow_expiration[self.expiration_var.get()]
strike = self.strike_var.get()
forecast = Prediction(self.options_db,
self.symbol_var.get(),
row["option_expire_id"],
row["expire_date"],
strike,
"CALL",
"bid",
training_event)
last_day_predictions, next_day_predictions = forecast.calculate_predictions()
success = chart.create_strike_profit_chart(self.options_db,
fig,
self.symbol_var.get(),
self.options_db.get_name_for_symbol(self.symbol_var.get()),
row["option_expire_id"],
strike,
row["expire_date"],
last_day_predictions, next_day_predictions,
put_call="CALL",
start_date=self.start_date,
end_date=self.end_date,
option_type='extrinsic' if self.bid_extrinsic_value.get() == 1 else 'bid')
if success:
self.show_figure(canvas)
self.status_var.set("Done")
else:
self.status_var.set("No data available")
def create_strike_metrics_chart(self, event=None):
self.close_button.focus_force()
self.status_var.set("Creating strike chart...")
self.update()
self.update_idletasks()
if bool(self.shadow_expiration) and self.strike_var.get() != "":
self.clear_plot_frame()
fig = Figure(figsize=(10, 6))
canvas = FigureCanvasTkAgg(fig, master=self.plot_frame)
chart = ChartOptions()
row = self.shadow_expiration[self.expiration_var.get()]
strike = self.strike_var.get()
success = chart.create_strike_metrics_chart(self.options_db,
fig,
self.symbol_var.get(),
self.options_db.get_name_for_symbol(self.symbol_var.get()),
row["option_expire_id"],
strike,
row["expire_date"],
put_call="CALL",
start_date=self.start_date,
end_date=self.end_date)
if success:
self.show_figure(canvas)
self.status_var.set("Done")
else:
self.status_var.set("No data available")
def create_bid_ask_chart(self, event=None):
self.close_button.focus_force()
self.status_var.set("Creating bid/ask chart...")
self.update()
self.update_idletasks()
if bool(self.shadow_expiration) and self.strike_var.get() != "":
self.clear_plot_frame()
fig = Figure(figsize=(10, 6))
canvas = FigureCanvasTkAgg(fig, master=self.plot_frame)
chart = ChartOptions()
row = self.shadow_expiration[self.expiration_var.get()]
strike = self.strike_var.get()
success = chart.create_strike_bid_ask(self.options_db,
fig,
self.symbol_var.get(),
self.options_db.get_name_for_symbol(self.symbol_var.get()),
row["option_expire_id"],
strike,
row["expire_date"],
put_call="CALL",
start_date=self.start_date,
end_date=self.end_date)
if success:
self.show_figure(canvas)
self.status_var.set("Done")
else:
self.status_var.set("No data available")
def show_figure(self, canvas):
canvas.draw()
canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1)
toolbar = NavigationToolbar2Tk(canvas, self.plot_frame)
toolbar.update()
canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1)
def clear_symbol_menu(self):
self.symbol_var.set('')
self.popup_symbol_menu['menu'].delete(0, 'end')
def update_symbols(self, choices):
for choice in choices:
self.popup_symbol_menu['menu'].add_command(label=choice,
command=lambda value=choice: self.symbol_var.set(value))
# noinspection PyUnusedLocal
def symbol_selection_event(self, *args):
print("symbol_selection_event", self.symbol_var.get())
self.update_chart_button_enable()
if not self.symbol_var.get():
pass
else:
self.clear_expiration_menu()
df_options_expirations = self.options_db.get_all_options_expirations(self.symbol_var.get())
expiration_set = []
self.shadow_expiration = dict()
for index, row in df_options_expirations.iterrows():
expiration_key = row["expire_date"].strftime('%Y-%m-%d')
expiration_set.append(expiration_key)
self.shadow_expiration[expiration_key] = row
self.update_expiration(expiration_set)
def clear_expiration_menu(self):
self.expiration_var.set(' ')
self.popup_expiration_menu['menu'].delete(0, 'end')
def update_expiration(self, choices):
for choice in choices:
self.popup_expiration_menu['menu'].add_command(label=choice,
command=lambda value=choice: self.expiration_var.set(value))
def clear_strike_menu(self):
self.strike_var.set(' ')
self.popup_strike_menu['menu'].delete(0, 'end')
def update_strike(self, choices):
for choice in choices:
self.popup_strike_menu['menu'].add_command(label=choice,
command=lambda value=choice: self.strike_var.set(value))
# noinspection PyUnusedLocal
def expiration_var_selection_event(self, *args):
self.update_chart_button_enable()
if not self.expiration_var.get() or self.expiration_var.get() == ' ':
pass
else:
self.clear_strike_menu()
row = self.shadow_expiration[self.expiration_var.get()]
df_strikes = self.options_db.get_unique_strikes_for_expiration(row["option_expire_id"], put_call="CALL")
strike_list = []
for index, row in df_strikes.iterrows():
strike_list.append(row["strike"])
self.update_strike(strike_list)
def strike_var_selection_event(self, *args):
self.update_chart_button_enable()
# noinspection PyUnusedLocal
def start_date_changed(self, args):
self.start_date = datetime.datetime.strptime(self.start_cal.get(), "%m/%d/%y")
print(self.start_cal.get())
# noinspection PyUnusedLocal
def end_date_changed(self, args):
self.end_date = datetime.datetime.strptime(self.end_cal.get(), "%m/%d/%y")
self.adjust_end_date()
print(self.end_cal.get())
def adjust_end_date(self):
if self.end_date is not None:
self.end_date += datetime.timedelta(days=1)
self.end_date -= datetime.timedelta(seconds=1)
def toggle_date_filter(self):
if self.is_date_filter_on.get():
self.start_cal.config(state='normal')
self.end_cal.config(state='normal')
self.end_date = datetime.datetime.strptime(self.end_cal.get(), "%m/%d/%y")
self.start_date = datetime.datetime.strptime(self.start_cal.get(), "%m/%d/%y")
self.adjust_end_date()
else:
self.start_cal.config(state='disabled')
self.end_cal.config(state='disabled')
self.end_date = None
self.start_date = None
def update_chart_button_enable(self):
if not self.symbol_var.get() or not self.expiration_var.get():
# self.surface_chart_button.config(state='disabled')
# self.line_chart_button.config(state='disabled')
# self.strike_chart_button.config(state='disabled')
self.positions_menu.entryconfig("Add", state="disabled")
self.chart_menu.entryconfig("Surface", state="disabled")
self.chart_menu.entryconfig("Line", state="disabled")
self.chart_menu.entryconfig("OTM Current bid/ask", state="disabled")
self.chart_menu.entryconfig("OTM Current delta/theta", state="disabled")
self.chart_menu.entryconfig("Strike/Profit", state="disabled")
self.chart_menu.entryconfig("Normalized Strike/Metrics", state="disabled")
self.chart_menu.entryconfig("Strike Bid/Ask/Last", state="disabled")
else:
# self.surface_chart_button.config(state='normal')
# self.line_chart_button.config(state='normal')
self.positions_menu.entryconfig("Add", state="normal")
self.chart_menu.entryconfig("Surface", state="normal")
self.chart_menu.entryconfig("Line", state="normal")
self.chart_menu.entryconfig("OTM Current bid/ask", state="normal")
self.chart_menu.entryconfig("OTM Current delta/theta", state="normal")
if not self.strike_var.get():
# self.strike_chart_button.config(state='disabled')
self.chart_menu.entryconfig("Strike/Profit", state="disabled")
self.chart_menu.entryconfig("Normalized Strike/Metrics", state="disabled")
self.chart_menu.entryconfig("Strike Bid/Ask/Last", state="disabled")
else:
# self.strike_chart_button.config(state='normal')
self.chart_menu.entryconfig("Strike/Profit", state="normal")
self.chart_menu.entryconfig("Normalized Strike/Metrics", state="normal")
self.chart_menu.entryconfig("Strike Bid/Ask/Last", state="normal")
if not self.symbol_var.get():
self.delete_option_button.config(state='disabled')
else:
self.delete_option_button.config(state='normal')
def init_ui(self):
self.master.title("Options")
self.init_menus()
# frame2 = Frame(self, relief=RAISED, borderwidth=1, style='My.TFrame')
tool_bar = tk.ttk.Frame(self, relief=tk.RAISED, borderwidth=1)
tool_bar.pack(fill=tk.X, side=tk.TOP, expand=False)
self.pack(fill=tk.BOTH, expand=True)
self.close_button = tk.ttk.Button(tool_bar, text="Close")
self.close_button.pack(side=tk.RIGHT, padx=5, pady=5)
self.close_button.bind('<Button-1>', self.quit_app)
self.delete_option_button = tk.ttk.Button(tool_bar, text="Delete option")
self.delete_option_button.pack(side=tk.LEFT, padx=5, pady=5)
self.delete_option_button.bind('<Button-1>', self.delete_option)
self.symbol_var.set('')
self.symbol_var.trace('w', self.symbol_selection_event)
self.expiration_var.set('')
self.expiration_var.trace('w', self.expiration_var_selection_event)
self.popup_symbol_menu = tk.OptionMenu(tool_bar, self.symbol_var,
*{''})
self.popup_symbol_menu.config(width=8)
self.popup_symbol_menu.pack(side=tk.LEFT, padx=5, pady=5)
self.popup_expiration_menu = tk.OptionMenu(tool_bar, self.expiration_var,
*{''})
self.popup_expiration_menu.config(width=16)
self.popup_expiration_menu.pack(side=tk.LEFT, padx=5, pady=5)
self.strike_var.set('')
self.strike_var.trace('w', self.strike_var_selection_event)
self.popup_strike_menu = tk.OptionMenu(tool_bar, self.strike_var,
*{''})
self.popup_strike_menu.config(width=7)
self.popup_strike_menu.pack(side=tk.LEFT, padx=5, pady=5)
tool_bar_style = Style()
tool_bar_style.theme_use("default")
tool_bar_style.configure('My.TFrame', background='lightsteelblue')
date_filter_container = tk.ttk.Frame(tool_bar, style='My.TFrame')
date_filter_container.pack(fill=tk.X, side=tk.LEFT, expand=False)
check_box = tk.Checkbutton(date_filter_container,
text="Date Filter",
variable=self.is_date_filter_on,
command=self.toggle_date_filter,
bg='lightsteelblue')
# style='My.TFrame')
check_box.pack(padx=10, side=tk.LEFT)
start_date_container = tk.ttk.Frame(date_filter_container, style='My.TFrame')
start_date_container.pack(fill=tk.X, side=tk.LEFT, expand=True)
start_date_label = tk.ttk.Label(start_date_container, text="Start Date", background="lightsteelblue")
start_date_label.pack(side=tk.TOP, padx=5, pady=2)
self.start_cal = cal.DateEntry(start_date_container, width=12, background='darkblue',
foreground='white', borderwidth=2)
self.start_cal.pack(side=tk.BOTTOM, padx=5, pady=5)
self.start_cal.bind('<<DateEntrySelected>>', self.start_date_changed)
end_date_container = tk.ttk.Frame(date_filter_container, style='My.TFrame')
end_date_container.pack(fill=tk.X, side=tk.LEFT, expand=True)
end_date_label = tk.ttk.Label(end_date_container, text="End Date", background="lightsteelblue")
end_date_label.pack(side=tk.TOP, padx=5, pady=2)
self.end_cal = cal.DateEntry(end_date_container, width=12, background='darkblue',
foreground='white', borderwidth=2)
self.end_cal.pack(side=tk.BOTTOM, padx=5, pady=5)
self.end_cal.bind('<<DateEntrySelected>>', self.end_date_changed)
bid_extrinsic_container = tk.ttk.Frame(tool_bar, style='My.TFrame')
bid_extrinsic_container.pack(fill=tk.BOTH, side=tk.LEFT, expand=False)
self.bid_extrinsic_value.set(1)
self.extrinsic_value_radio = tk.Radiobutton(bid_extrinsic_container,
text="Extrinsic value",
padx=20,
variable=self.bid_extrinsic_value,
value=1,
background="lightsteelblue")
self.extrinsic_value_radio.pack(anchor=tk.W)
self.bid_value_radio = tk.Radiobutton(bid_extrinsic_container,
text="Bid Value",
padx=20,
variable=self.bid_extrinsic_value,
value=2,
background="lightsteelblue")
self.bid_value_radio.pack(anchor=tk.W)
self.bid_extrinsic_value.set(1)
# import time
# time.sleep(1)
self.plot_frame = tk.ttk.Frame(self, relief=tk.RAISED, borderwidth=1)
self.plot_frame.pack(fill=tk.BOTH, side=tk.TOP, expand=True)
self.status_var.set("Status")
self.status_label = tk.ttk.Label(self, textvariable=self.status_var, background="lightsteelblue")
self.status_label.pack(side=tk.BOTTOM, fill=tk.X, expand=False, ipadx=10, ipady=5)
def show_positions(self):
df_positions = self.options_db.get_positions()
if len(df_positions.index) > 0:
web = Utilities.get_options_API()
expire_date_list = []
current_stock_price_list = []
current_option_price_list = []
for index, row in df_positions.iterrows():
expire_date = self.options_db.get_expire_date_from_id(row["option_expire_id"])
if expire_date is not None:
expire_date_str = expire_date.strftime('%Y-%m-%d')
else:
expire_date_str = "N/A"
expire_date_list.append(expire_date_str)
if row["status"] == "OPEN":
option = web.get_options_for_symbol_and_expiration(row["symbol"], expire_date_str)
else:
option = None
if bool(option) and pd.isnull(row["close_date"]):
# If the position is closed, we don't care what the current prices are
current_stock_price_list.append(option["current_value"])
current_option_price_list.append(self.__get_option_price_for_position(row, option))
else:
current_stock_price_list.append(None)
current_option_price_list.append(None)
df_positions.insert(len(df_positions.columns), "expire_date_str", expire_date_list)
df_positions.insert(len(df_positions.columns), "current_stock_price", current_stock_price_list)
df_positions.insert(len(df_positions.columns), "current_option_price", current_option_price_list)
# quote_dict = web.get_stock_price_for_symbol(row["symbol"])
# if bool(quote_dict):
# price = quote_dict["value"]
# else:
# price = None
position_info = {'positions': df_positions, 'delete': False}
dialog = listPos(position_info, self.options_db)
self.tk_root.wait_window(dialog.top)
if position_info["delete"]:
self.options_db.delete_position(position_info["position_id"])
else:
tk.messagebox.showinfo("No Positions", "There are no positions")
def add_position(self):
if self.expiration_var.get():
row = self.shadow_expiration[self.expiration_var.get()]
option_expire_id = row['option_expire_id']
position_info = {'symbol': self.symbol_var.get(),
'expiration_str': self.expiration_var.get(),
'option_expire_id': option_expire_id,
'added': False}
dialog = addPos(position_info)
self.tk_root.wait_window(dialog.top)
if position_info["added"]:
open_date = parser.parse(position_info["open_date"])
self.options_db.add_position(position_info["symbol"],
position_info["put_call"],
position_info["buy_sell"],
open_date,
position_info["option_price_open"],
position_info["strike_price"],
position_info["option_expire_id"])
@staticmethod
def __get_option_price_for_position(row, option):
option_price = None
if row["put_call"] == "call":
options = option['options_chain']['calls']
else:
options = option['options_chain']['puts']
if len(options) > 0:
for index, option_strike in options.iterrows():
if option_strike['strike'] == row['strike_price']:
# Use the mid price ???
option_price = (option_strike['ask'] + option_strike['bid']) / 2
# if row["buy_sell"] == "sell":
# option_price = option_strike['ask'] #To close, must buy back options at higher price
# else:
# option_price = option_strike['bid'] #To close, must sell back options at lower price
break
return option_price
# noinspection PyAttributeOutsideInit,PyAttributeOutsideInit,PyAttributeOutsideInit
def init_menus(self):
self.menu_bar = tk.Menu(self.tk_root)
self.positions_menu = tk.Menu(self.menu_bar, tearoff=0)
self.positions_menu.add_command(label="Show", command=self.show_positions)
self.positions_menu.add_command(label="Add", command=self.add_position)
self.menu_bar.add_cascade(label="Positions", menu=self.positions_menu)
self.chart_menu = tk.Menu(self.menu_bar, tearoff=0)
self.chart_menu.add_command(label="Surface", command=self.create_surface_chart)
self.chart_menu.add_command(label="Line", command=self.create_line_chart)
self.chart_menu.add_command(label="OTM Current bid/ask", command=self.create_current_bid_ask_chart)
self.chart_menu.add_command(label="OTM Current delta/theta", command=self.create_current_delta_theta_chart)
self.chart_menu.add_command(label="Strike/Profit", command=self.create_strike_profit_chart)
self.chart_menu.add_command(label="Normalized Strike/Metrics", command=self.create_strike_metrics_chart)
self.chart_menu.add_command(label="Strike Bid/Ask/Last", command=self.create_bid_ask_chart)
# self.chart_menu.add_command(label="Strike/Profit", command=self.add_position)
self.menu_bar.add_cascade(label="Charts", menu=self.chart_menu)
self.tk_root.config(menu=self.menu_bar)
def main():
root = tk.Tk()
root.geometry("1200x800+300+300")
GuiOptions(root)
while True:
try:
root.mainloop()
break
except UnicodeDecodeError:
pass
if __name__ == '__main__':
main()