-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgui.py
More file actions
executable file
·1817 lines (1514 loc) · 73.2 KB
/
gui.py
File metadata and controls
executable file
·1817 lines (1514 loc) · 73.2 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
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
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
GUI Application for Prediction Analyzer
Provides an intuitive graphical interface for analyzing prediction market trades
"""
import tkinter as tk
from tkinter import ttk, filedialog, messagebox, scrolledtext
from pathlib import Path
import sys
from typing import List, Optional
from datetime import datetime
import threading
# Add the package directory to Python path
package_dir = Path(__file__).parent
sys.path.insert(0, str(package_dir))
from prediction_analyzer.trade_loader import load_trades, Trade
from prediction_analyzer.trade_filter import (
filter_trades_by_market_slug,
get_unique_markets,
group_trades_by_market,
)
from prediction_analyzer.filters import (
filter_by_date,
filter_by_trade_type,
filter_by_pnl,
filter_by_side,
)
from prediction_analyzer.pnl import calculate_global_pnl_summary, calculate_market_pnl_summary
from prediction_analyzer.charts.simple import generate_simple_chart
from prediction_analyzer.charts.pro import generate_pro_chart
from prediction_analyzer.charts.enhanced import generate_enhanced_chart
from prediction_analyzer.charts.global_chart import generate_global_dashboard
from prediction_analyzer.reporting.report_data import export_to_csv, export_to_excel, export_to_json
from prediction_analyzer.utils.auth import get_api_key
from prediction_analyzer.metrics import calculate_advanced_metrics
from prediction_analyzer.positions import calculate_open_positions, calculate_concentration_risk
from prediction_analyzer.drawdown import analyze_drawdowns
from prediction_analyzer.tax import calculate_capital_gains
from prediction_analyzer.comparison import compare_periods
class PredictionAnalyzerGUI:
"""Main GUI application for Prediction Analyzer"""
def __init__(self, root):
self.root = root
self.root.title("Prediction Market Trade Analyzer")
self.root.geometry("1200x800")
# Data storage
self.all_trades: List[Trade] = []
self.filtered_trades: List[Trade] = []
self.current_file_path: Optional[str] = None
self.market_slugs: List[str] = [] # Initialize to prevent AttributeError
self._fetch_lock = threading.Lock()
self._fetch_in_progress = False
# Configure style
self.setup_style()
# Create main layout
self.create_menu_bar()
self.create_main_interface()
def setup_style(self):
"""Configure ttk styles for better appearance"""
style = ttk.Style()
style.theme_use("clam")
# Use cross-platform font family (works on Windows, macOS, Linux)
# 'TkDefaultFont' is always available, fallback chain for explicit fonts
self.default_font = ("DejaVu Sans", "Helvetica", "Arial", "TkDefaultFont")
self.mono_font = ("DejaVu Sans Mono", "Consolas", "Courier", "TkFixedFont")
# Configure colors with cross-platform fonts
style.configure("Title.TLabel", font=(self.default_font[0], 16, "bold"))
style.configure("Subtitle.TLabel", font=(self.default_font[0], 12, "bold"))
style.configure("Info.TLabel", font=(self.default_font[0], 10))
style.configure(
"Success.TLabel", foreground="green", font=(self.default_font[0], 10, "bold")
)
style.configure("Error.TLabel", foreground="red", font=(self.default_font[0], 10, "bold"))
def create_menu_bar(self):
"""Create application menu bar"""
menubar = tk.Menu(self.root)
self.root.config(menu=menubar)
# File menu
file_menu = tk.Menu(menubar, tearoff=0)
menubar.add_cascade(label="File", menu=file_menu)
file_menu.add_command(
label="Load Trades from File...", command=self.load_file, accelerator="Ctrl+O"
)
file_menu.add_command(label="Load Trades from API...", command=self.load_from_api)
file_menu.add_separator()
file_menu.add_command(
label="Export to CSV...", command=lambda: self.export_data("csv"), accelerator="Ctrl+E"
)
file_menu.add_command(label="Export to Excel...", command=lambda: self.export_data("excel"))
file_menu.add_command(label="Export to JSON...", command=lambda: self.export_data("json"))
file_menu.add_separator()
file_menu.add_command(label="Exit", command=self.root.quit, accelerator="Ctrl+Q")
# Analysis menu
analysis_menu = tk.Menu(menubar, tearoff=0)
menubar.add_cascade(label="Analysis", menu=analysis_menu)
analysis_menu.add_command(
label="Global PnL Summary", command=self.show_global_summary, accelerator="Ctrl+G"
)
analysis_menu.add_command(
label="Generate Dashboard", command=self.generate_dashboard, accelerator="Ctrl+D"
)
analysis_menu.add_separator()
analysis_menu.add_command(
label="Compare Periods...", command=self.show_compare_periods_dialog
)
# Help menu
help_menu = tk.Menu(menubar, tearoff=0)
menubar.add_cascade(label="Help", menu=help_menu)
help_menu.add_command(label="About", command=self.show_about)
def create_main_interface(self):
"""Create the main interface layout"""
# Main container with padding
main_container = ttk.Frame(self.root, padding="10")
main_container.grid(row=0, column=0, sticky=(tk.W, tk.E, tk.N, tk.S))
# Configure grid weights
self.root.columnconfigure(0, weight=1)
self.root.rowconfigure(0, weight=1)
main_container.columnconfigure(0, weight=1)
main_container.rowconfigure(2, weight=1)
# Header section
self.create_header(main_container)
# Control panel
self.create_control_panel(main_container)
# Notebook for tabbed interface
self.notebook = ttk.Notebook(main_container)
self.notebook.grid(row=2, column=0, sticky=(tk.W, tk.E, tk.N, tk.S), pady=10)
# Create tabs
self.create_summary_tab()
self.create_markets_tab()
self.create_trades_tab()
self.create_filters_tab()
self.create_portfolio_tab()
self.create_tax_tab()
self.create_charts_tab()
# Keyboard shortcuts
self.root.bind("<Control-o>", lambda e: self.load_file())
self.root.bind("<Control-e>", lambda e: self.export_data("csv"))
self.root.bind("<Control-d>", lambda e: self.generate_dashboard())
self.root.bind("<Control-g>", lambda e: self.show_global_summary())
self.root.bind("<Control-q>", lambda e: self.root.quit())
def create_header(self, parent):
"""Create header section"""
header_frame = ttk.Frame(parent)
header_frame.grid(row=0, column=0, sticky=(tk.W, tk.E), pady=(0, 10))
title_label = ttk.Label(
header_frame, text="Prediction Market Trade Analyzer", style="Title.TLabel"
)
title_label.grid(row=0, column=0, sticky=tk.W)
self.status_label = ttk.Label(header_frame, text="No file loaded", style="Info.TLabel")
self.status_label.grid(row=1, column=0, sticky=tk.W)
def create_control_panel(self, parent):
"""Create control panel with main action buttons"""
control_frame = ttk.LabelFrame(parent, text="Quick Actions", padding="10")
control_frame.grid(row=1, column=0, sticky=(tk.W, tk.E), pady=(0, 10))
# Provider selector
ttk.Label(control_frame, text="Provider:").grid(
row=0, column=0, sticky=tk.W, padx=5, pady=2
)
self.provider_var = tk.StringVar(value="auto")
provider_combo = ttk.Combobox(
control_frame,
textvariable=self.provider_var,
values=["auto", "limitless", "polymarket", "kalshi", "manifold"],
state="readonly",
width=12,
)
provider_combo.grid(row=0, column=1, sticky=tk.W, padx=5, pady=2)
# API key input section
ttk.Label(control_frame, text="API Key / Wallet:").grid(
row=0, column=2, sticky=tk.W, padx=5, pady=2
)
self.api_key_entry = ttk.Entry(control_frame, width=35, show="*")
self.api_key_entry.grid(row=0, column=3, sticky=(tk.W, tk.E), padx=5, pady=2)
ttk.Button(control_frame, text="Load from API", command=self.load_from_api).grid(
row=0, column=4, padx=5, pady=2
)
# Action buttons row
ttk.Button(control_frame, text="Load Trades File", command=self.load_file).grid(
row=1, column=0, padx=5, pady=2
)
ttk.Button(control_frame, text="Global Summary", command=self.show_global_summary).grid(
row=1, column=1, padx=5, pady=2
)
ttk.Button(control_frame, text="Generate Dashboard", command=self.generate_dashboard).grid(
row=1, column=2, padx=5, pady=2
)
ttk.Button(control_frame, text="Export CSV", command=lambda: self.export_data("csv")).grid(
row=1, column=3, padx=5, pady=2
)
ttk.Button(
control_frame, text="Export Excel", command=lambda: self.export_data("excel")
).grid(row=1, column=4, padx=5, pady=2)
def create_summary_tab(self):
"""Create global summary tab"""
summary_frame = ttk.Frame(self.notebook, padding="10")
self.notebook.add(summary_frame, text="Global Summary")
summary_frame.columnconfigure(0, weight=1)
summary_frame.rowconfigure(1, weight=1)
# Summary info
info_frame = ttk.Frame(summary_frame)
info_frame.grid(row=0, column=0, sticky=(tk.W, tk.E), pady=(0, 10))
ttk.Label(info_frame, text="Trade Statistics", style="Subtitle.TLabel").grid(
row=0, column=0, sticky=tk.W, pady=(0, 5)
)
self.summary_text = scrolledtext.ScrolledText(
summary_frame, width=80, height=20, font=(self.mono_font[0], 10)
)
self.summary_text.grid(row=1, column=0, sticky=(tk.W, tk.E, tk.N, tk.S))
def create_markets_tab(self):
"""Create market analysis tab"""
markets_frame = ttk.Frame(self.notebook, padding="10")
self.notebook.add(markets_frame, text="Market Analysis")
markets_frame.columnconfigure(1, weight=1)
markets_frame.rowconfigure(1, weight=1)
# Market selection header and search
header_frame = ttk.Frame(markets_frame)
header_frame.grid(row=0, column=0, columnspan=2, sticky=(tk.W, tk.E), pady=(0, 5))
ttk.Label(header_frame, text="Select Market:", style="Subtitle.TLabel").grid(
row=0, column=0, sticky=tk.W
)
ttk.Label(header_frame, text="Search:").grid(row=0, column=1, sticky=tk.W, padx=(20, 5))
self.market_search_var = tk.StringVar()
self.market_search_var.trace_add("write", lambda *args: self._filter_market_listbox())
market_search_entry = ttk.Entry(header_frame, textvariable=self.market_search_var, width=25)
market_search_entry.grid(row=0, column=2, sticky=tk.W, padx=5)
# Market listbox with scrollbar
listbox_frame = ttk.Frame(markets_frame)
listbox_frame.grid(
row=1, column=0, columnspan=2, sticky=(tk.W, tk.E, tk.N, tk.S), pady=(0, 10)
)
scrollbar = ttk.Scrollbar(listbox_frame)
scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
self.market_listbox = tk.Listbox(
listbox_frame, yscrollcommand=scrollbar.set, height=15, font=(self.default_font[0], 10)
)
self.market_listbox.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
scrollbar.config(command=self.market_listbox.yview)
# Market action buttons
button_frame = ttk.Frame(markets_frame)
button_frame.grid(row=2, column=0, columnspan=2, sticky=tk.W, pady=5)
ttk.Button(button_frame, text="Show Market Summary", command=self.show_market_summary).grid(
row=0, column=0, padx=5
)
ttk.Button(
button_frame, text="Simple Chart", command=lambda: self.generate_market_chart("simple")
).grid(row=0, column=1, padx=5)
ttk.Button(
button_frame, text="Pro Chart", command=lambda: self.generate_market_chart("pro")
).grid(row=0, column=2, padx=5)
ttk.Button(
button_frame,
text="Enhanced Chart",
command=lambda: self.generate_market_chart("enhanced"),
).grid(row=0, column=3, padx=5)
# Market summary display
ttk.Label(markets_frame, text="Market Details:", style="Subtitle.TLabel").grid(
row=3, column=0, columnspan=2, sticky=tk.W, pady=(10, 5)
)
self.market_details_text = scrolledtext.ScrolledText(
markets_frame, width=80, height=10, font=(self.mono_font[0], 10)
)
self.market_details_text.grid(
row=4, column=0, columnspan=2, sticky=(tk.W, tk.E, tk.N, tk.S)
)
def create_trades_tab(self):
"""Create trade browser tab for viewing individual trades"""
trades_frame = ttk.Frame(self.notebook, padding="10")
self.notebook.add(trades_frame, text="Trade Browser")
trades_frame.columnconfigure(0, weight=1)
trades_frame.rowconfigure(1, weight=1)
# Controls row
controls_frame = ttk.Frame(trades_frame)
controls_frame.grid(row=0, column=0, sticky=(tk.W, tk.E), pady=(0, 5))
ttk.Label(controls_frame, text="Trade Browser", style="Subtitle.TLabel").grid(
row=0, column=0, sticky=tk.W
)
self.trades_count_label = ttk.Label(controls_frame, text="", style="Info.TLabel")
self.trades_count_label.grid(row=0, column=1, sticky=tk.W, padx=20)
# Sort controls
ttk.Label(controls_frame, text="Sort by:").grid(row=0, column=2, sticky=tk.W, padx=(20, 5))
self.sort_var = tk.StringVar(value="timestamp")
sort_combo = ttk.Combobox(
controls_frame,
textvariable=self.sort_var,
values=["timestamp", "pnl", "cost", "market"],
state="readonly",
width=12,
)
sort_combo.grid(row=0, column=3, padx=5)
self.sort_desc_var = tk.BooleanVar(value=True)
ttk.Checkbutton(controls_frame, text="Descending", variable=self.sort_desc_var).grid(
row=0, column=4, padx=5
)
ttk.Button(controls_frame, text="Refresh", command=self.refresh_trades_browser).grid(
row=0, column=5, padx=5
)
# Treeview for trade data
tree_frame = ttk.Frame(trades_frame)
tree_frame.grid(row=1, column=0, sticky=(tk.W, tk.E, tk.N, tk.S))
tree_frame.columnconfigure(0, weight=1)
tree_frame.rowconfigure(0, weight=1)
columns = (
"timestamp",
"market",
"type",
"side",
"price",
"shares",
"cost",
"pnl",
"source",
"currency",
)
self.trades_tree = ttk.Treeview(tree_frame, columns=columns, show="headings", height=20)
# Column headings and widths
col_config = {
"timestamp": ("Timestamp", 140),
"market": ("Market", 200),
"type": ("Type", 80),
"side": ("Side", 50),
"price": ("Price", 70),
"shares": ("Shares", 70),
"cost": ("Cost", 80),
"pnl": ("PnL", 80),
"source": ("Source", 80),
"currency": ("Currency", 60),
}
for col, (heading, width) in col_config.items():
self.trades_tree.heading(col, text=heading)
self.trades_tree.column(col, width=width, minwidth=40)
# Scrollbars
tree_yscroll = ttk.Scrollbar(tree_frame, orient=tk.VERTICAL, command=self.trades_tree.yview)
tree_xscroll = ttk.Scrollbar(
tree_frame, orient=tk.HORIZONTAL, command=self.trades_tree.xview
)
self.trades_tree.configure(yscrollcommand=tree_yscroll.set, xscrollcommand=tree_xscroll.set)
self.trades_tree.grid(row=0, column=0, sticky=(tk.W, tk.E, tk.N, tk.S))
tree_yscroll.grid(row=0, column=1, sticky=(tk.N, tk.S))
tree_xscroll.grid(row=1, column=0, sticky=(tk.W, tk.E))
def create_filters_tab(self):
"""Create filters tab"""
filters_frame = ttk.Frame(self.notebook, padding="10")
self.notebook.add(filters_frame, text="Filters")
# Use a canvas with scrollbar for the filters content
filters_canvas = tk.Canvas(filters_frame)
filters_scrollbar = ttk.Scrollbar(
filters_frame, orient=tk.VERTICAL, command=filters_canvas.yview
)
filters_content = ttk.Frame(filters_canvas)
filters_content.bind(
"<Configure>",
lambda e: filters_canvas.configure(scrollregion=filters_canvas.bbox("all")),
)
filters_canvas.create_window((0, 0), window=filters_content, anchor="nw")
filters_canvas.configure(yscrollcommand=filters_scrollbar.set)
filters_frame.columnconfigure(0, weight=1)
filters_frame.rowconfigure(0, weight=1)
filters_canvas.grid(row=0, column=0, sticky=(tk.W, tk.E, tk.N, tk.S))
filters_scrollbar.grid(row=0, column=1, sticky=(tk.N, tk.S))
# Date filters
date_frame = ttk.LabelFrame(filters_content, text="Date Range", padding="10")
date_frame.grid(row=0, column=0, sticky=(tk.W, tk.E), pady=(0, 10))
ttk.Label(date_frame, text="Start Date (YYYY-MM-DD):").grid(row=0, column=0, sticky=tk.W)
self.start_date_entry = ttk.Entry(date_frame, width=20)
self.start_date_entry.grid(row=0, column=1, padx=5, pady=2)
# Bind Enter key to apply filters
self.start_date_entry.bind("<Return>", lambda e: self.apply_filters())
ttk.Label(date_frame, text="End Date (YYYY-MM-DD):").grid(row=1, column=0, sticky=tk.W)
self.end_date_entry = ttk.Entry(date_frame, width=20)
self.end_date_entry.grid(row=1, column=1, padx=5, pady=2)
self.end_date_entry.bind("<Return>", lambda e: self.apply_filters())
# Format hint label
ttk.Label(date_frame, text="(e.g., 2024-01-15)", style="Info.TLabel").grid(
row=0, column=2, sticky=tk.W, padx=5
)
# Trade type filters
type_frame = ttk.LabelFrame(filters_content, text="Trade Type", padding="10")
type_frame.grid(row=1, column=0, sticky=(tk.W, tk.E), pady=(0, 10))
self.buy_var = tk.BooleanVar(value=True)
self.sell_var = tk.BooleanVar(value=True)
ttk.Checkbutton(type_frame, text="Buy", variable=self.buy_var).grid(
row=0, column=0, sticky=tk.W, padx=(0, 15)
)
ttk.Checkbutton(type_frame, text="Sell", variable=self.sell_var).grid(
row=0, column=1, sticky=tk.W
)
# Side filters
side_frame = ttk.LabelFrame(filters_content, text="Side", padding="10")
side_frame.grid(row=2, column=0, sticky=(tk.W, tk.E), pady=(0, 10))
self.yes_var = tk.BooleanVar(value=True)
self.no_var = tk.BooleanVar(value=True)
ttk.Checkbutton(side_frame, text="YES", variable=self.yes_var).grid(
row=0, column=0, sticky=tk.W, padx=(0, 15)
)
ttk.Checkbutton(side_frame, text="NO", variable=self.no_var).grid(
row=0, column=1, sticky=tk.W
)
# PnL filters
pnl_frame = ttk.LabelFrame(filters_content, text="PnL Range", padding="10")
pnl_frame.grid(row=3, column=0, sticky=(tk.W, tk.E), pady=(0, 10))
ttk.Label(pnl_frame, text="Minimum PnL:").grid(row=0, column=0, sticky=tk.W)
self.min_pnl_entry = ttk.Entry(pnl_frame, width=20)
self.min_pnl_entry.grid(row=0, column=1, padx=5, pady=2)
self.min_pnl_entry.bind("<Return>", lambda e: self.apply_filters())
ttk.Label(pnl_frame, text="Maximum PnL:").grid(row=1, column=0, sticky=tk.W)
self.max_pnl_entry = ttk.Entry(pnl_frame, width=20)
self.max_pnl_entry.grid(row=1, column=1, padx=5, pady=2)
self.max_pnl_entry.bind("<Return>", lambda e: self.apply_filters())
# Format hint label
ttk.Label(pnl_frame, text="(e.g., -100.50, 500)", style="Info.TLabel").grid(
row=0, column=2, sticky=tk.W, padx=5
)
# Filter buttons
button_frame = ttk.Frame(filters_content)
button_frame.grid(row=4, column=0, sticky=tk.W, pady=10)
ttk.Button(button_frame, text="Apply Filters", command=self.apply_filters).grid(
row=0, column=0, padx=5
)
ttk.Button(button_frame, text="Clear Filters", command=self.clear_filters).grid(
row=0, column=1, padx=5
)
# Filter status
self.filter_status_label = ttk.Label(
filters_content, text="No filters applied", style="Info.TLabel"
)
self.filter_status_label.grid(row=5, column=0, sticky=tk.W)
def create_portfolio_tab(self):
"""Create portfolio analysis tab with positions, concentration, and drawdown"""
portfolio_frame = ttk.Frame(self.notebook, padding="10")
self.notebook.add(portfolio_frame, text="Portfolio")
portfolio_frame.columnconfigure(0, weight=1)
portfolio_frame.rowconfigure(1, weight=1)
# Buttons row
buttons_frame = ttk.Frame(portfolio_frame)
buttons_frame.grid(row=0, column=0, sticky=(tk.W, tk.E), pady=(0, 10))
ttk.Button(buttons_frame, text="Open Positions", command=self.show_open_positions).grid(
row=0, column=0, padx=5
)
ttk.Button(
buttons_frame, text="Concentration Risk", command=self.show_concentration_risk
).grid(row=0, column=1, padx=5)
ttk.Button(
buttons_frame, text="Drawdown Analysis", command=self.show_drawdown_analysis
).grid(row=0, column=2, padx=5)
# Display area
self.portfolio_text = scrolledtext.ScrolledText(
portfolio_frame, width=80, height=25, font=(self.mono_font[0], 10)
)
self.portfolio_text.grid(row=1, column=0, sticky=(tk.W, tk.E, tk.N, tk.S))
def create_tax_tab(self):
"""Create tax reporting tab"""
tax_frame = ttk.Frame(self.notebook, padding="10")
self.notebook.add(tax_frame, text="Tax Report")
tax_frame.columnconfigure(0, weight=1)
tax_frame.rowconfigure(2, weight=1)
# Controls
controls_frame = ttk.LabelFrame(tax_frame, text="Tax Report Settings", padding="10")
controls_frame.grid(row=0, column=0, sticky=(tk.W, tk.E), pady=(0, 10))
ttk.Label(controls_frame, text="Tax Year:").grid(row=0, column=0, sticky=tk.W, padx=5)
self.tax_year_var = tk.StringVar(value=str(datetime.now().year - 1))
tax_year_entry = ttk.Entry(controls_frame, textvariable=self.tax_year_var, width=8)
tax_year_entry.grid(row=0, column=1, padx=5)
ttk.Label(controls_frame, text="Cost Basis Method:").grid(
row=0, column=2, sticky=tk.W, padx=(20, 5)
)
self.cost_basis_var = tk.StringVar(value="fifo")
cost_basis_combo = ttk.Combobox(
controls_frame,
textvariable=self.cost_basis_var,
values=["fifo", "lifo", "average"],
state="readonly",
width=10,
)
cost_basis_combo.grid(row=0, column=3, padx=5)
ttk.Button(
controls_frame, text="Generate Tax Report", command=self.generate_tax_report
).grid(row=0, column=4, padx=15)
# Method descriptions
method_text = (
"FIFO: First-In, First-Out (most common) | "
"LIFO: Last-In, First-Out | "
"Average: Average cost basis"
)
ttk.Label(controls_frame, text=method_text, style="Info.TLabel").grid(
row=1, column=0, columnspan=5, sticky=tk.W, pady=(5, 0)
)
# Results display
self.tax_text = scrolledtext.ScrolledText(
tax_frame, width=80, height=25, font=(self.mono_font[0], 10)
)
self.tax_text.grid(row=2, column=0, sticky=(tk.W, tk.E, tk.N, tk.S))
def create_charts_tab(self):
"""Create charts tab"""
charts_frame = ttk.Frame(self.notebook, padding="10")
self.notebook.add(charts_frame, text="Charts")
charts_frame.columnconfigure(0, weight=1)
charts_frame.columnconfigure(1, weight=1)
ttk.Label(charts_frame, text="Chart Generation", style="Subtitle.TLabel").grid(
row=0, column=0, columnspan=2, sticky=tk.W, pady=(0, 10)
)
# Global charts section
global_frame = ttk.LabelFrame(charts_frame, text="Global Charts", padding="10")
global_frame.grid(row=1, column=0, sticky=(tk.W, tk.E, tk.N), padx=(0, 5), pady=(0, 10))
ttk.Label(
global_frame,
text="Multi-market overview dashboard\nshowing cumulative PnL across\nall loaded markets.",
justify=tk.LEFT,
).grid(row=0, column=0, sticky=tk.W, pady=(0, 10))
ttk.Button(global_frame, text="Generate Dashboard", command=self.generate_dashboard).grid(
row=1, column=0, sticky=tk.W, pady=5
)
# Per-market charts section
market_frame = ttk.LabelFrame(charts_frame, text="Market-Specific Charts", padding="10")
market_frame.grid(row=1, column=1, sticky=(tk.W, tk.E, tk.N), padx=(5, 0), pady=(0, 10))
chart_descriptions = (
"Simple Chart\n"
" Basic matplotlib PNG with price history\n"
" and net cash invested over time.\n\n"
"Pro Chart\n"
" Interactive Plotly HTML dashboard\n"
" with advanced multi-metric display.\n\n"
"Enhanced Chart\n"
" Battlefield-style Plotly visualization\n"
" with P&L tracking and risk panels."
)
ttk.Label(market_frame, text=chart_descriptions, justify=tk.LEFT).grid(
row=0, column=0, sticky=tk.W, pady=(0, 10)
)
ttk.Label(
market_frame,
text="Select a market in the Market Analysis\ntab, then use the chart buttons there.",
style="Info.TLabel",
justify=tk.LEFT,
).grid(row=1, column=0, sticky=tk.W, pady=5)
def load_file(self):
"""Load trades from a file"""
file_path = filedialog.askopenfilename(
title="Select Trades File",
filetypes=[
("All Supported", "*.json *.csv *.xlsx"),
("JSON files", "*.json"),
("CSV files", "*.csv"),
("Excel files", "*.xlsx"),
("All files", "*.*"),
],
)
if not file_path:
return
try:
self.all_trades = load_trades(file_path)
self.filtered_trades = self.all_trades.copy()
self.current_file_path = file_path
# Update status
filename = Path(file_path).name
self.status_label.config(text=f"Loaded: {filename} ({len(self.all_trades)} trades)")
# Update displays
self.update_markets_list()
self.update_summary_display()
self.refresh_trades_browser()
messagebox.showinfo(
"Success", f"Successfully loaded {len(self.all_trades)} trades from {filename}"
)
except Exception as e:
messagebox.showerror("Error", f"Failed to load file:\n{str(e)}")
def load_from_api(self):
"""Load trades from API using API key (runs in background thread)"""
# Atomic check-and-set to prevent concurrent fetches
with self._fetch_lock:
if self._fetch_in_progress:
messagebox.showinfo("Busy", "A fetch is already in progress. Please wait.")
return
self._fetch_in_progress = True
try:
self._start_api_fetch()
except Exception as e:
self._fetch_in_progress = False
self._set_api_controls_enabled(True)
messagebox.showerror("Error", f"Failed to start API fetch:\n{str(e)}")
def _start_api_fetch(self):
"""Prepare and launch the background API fetch thread."""
from prediction_analyzer.utils.auth import detect_provider_from_key
api_key_raw = self.api_key_entry.get().strip()
provider_name = self.provider_var.get()
api_key = get_api_key(
api_key_raw, provider=provider_name if provider_name != "auto" else "limitless"
)
if not api_key:
self._fetch_in_progress = False
messagebox.showwarning(
"Missing API Key",
"Please enter your API key or wallet address.\n\n"
"Supported formats:\n"
" Limitless: lmts_...\n"
" Polymarket: 0x... (wallet address)\n"
" Kalshi: kalshi_<KEY_ID>:<PEM_PATH>\n"
" Manifold: manifold_...\n\n"
"Or set the appropriate environment variable.",
)
return
# Auto-detect provider if needed
if provider_name == "auto":
provider_name = detect_provider_from_key(api_key)
# Disable buttons while fetching (flag already set inside _fetch_lock above)
self.status_label.config(text=f"Fetching trades from {provider_name}...")
self._set_api_controls_enabled(False)
def _fetch_worker():
"""Background thread for API fetch"""
try:
from prediction_analyzer.providers import ProviderRegistry
provider = ProviderRegistry.get(provider_name)
trades = provider.fetch_trades(api_key)
if provider_name in ("kalshi", "manifold", "polymarket"):
from prediction_analyzer.providers.pnl_calculator import compute_realized_pnl
trades = compute_realized_pnl(trades)
self.root.after(
0, lambda: self._on_provider_fetch_complete(trades, provider_name)
)
except Exception as exc:
try:
self.root.after(0, lambda err=str(exc): self._on_api_fetch_error(err))
except Exception:
# root may be destroyed (user closed GUI during fetch);
# ensure the lock flag is cleared so it doesn't stick
self._fetch_in_progress = False
thread = threading.Thread(target=_fetch_worker, daemon=True)
thread.start()
def _set_api_controls_enabled(self, enabled: bool):
"""Enable or disable API-related controls during fetch"""
state = "normal" if enabled else "disabled"
self.api_key_entry.config(state=state)
def _on_api_fetch_complete(self, raw_trades):
"""Handle successful API fetch (called on main thread)"""
self._fetch_in_progress = False
self._set_api_controls_enabled(True)
if not raw_trades:
messagebox.showinfo("No Trades", "No trades found for this account.")
self.status_label.config(text="No trades found")
return
try:
from prediction_analyzer.trade_loader import load_trades
import json
import tempfile
with tempfile.NamedTemporaryFile(mode="w", suffix=".json", delete=False) as tmp:
tmp_path = tmp.name
json.dump(raw_trades, tmp)
try:
self.all_trades = load_trades(tmp_path)
self.filtered_trades = self.all_trades.copy()
self.current_file_path = None
self.status_label.config(text=f"Loaded from API ({len(self.all_trades)} trades)")
self.update_markets_list()
self.update_summary_display()
self.refresh_trades_browser()
messagebox.showinfo(
"Success", f"Successfully loaded {len(self.all_trades)} trades from API"
)
finally:
import os
try:
os.unlink(tmp_path)
except OSError:
pass
except Exception as e:
messagebox.showerror("Error", f"Failed to process trades:\n{str(e)}")
self.status_label.config(text="Failed to process API data")
def _on_provider_fetch_complete(self, trades, provider_name: str):
"""Handle successful provider fetch (called on main thread)"""
self._fetch_in_progress = False
self._set_api_controls_enabled(True)
if not trades:
messagebox.showinfo("No Trades", f"No trades found from {provider_name}.")
self.status_label.config(text="No trades found")
return
self.all_trades = trades
self.filtered_trades = self.all_trades.copy()
self.current_file_path = None
self.status_label.config(
text=f"Loaded from {provider_name} ({len(self.all_trades)} trades)"
)
self.update_markets_list()
self.update_summary_display()
self.refresh_trades_browser()
messagebox.showinfo(
"Success", f"Successfully loaded {len(self.all_trades)} trades from {provider_name}"
)
def _on_api_fetch_error(self, error_msg: str):
"""Handle API fetch error (called on main thread)"""
self._fetch_in_progress = False
self._set_api_controls_enabled(True)
messagebox.showerror("Error", f"Failed to load trades from API:\n{error_msg}")
self.status_label.config(text="Failed to load from API")
def update_markets_list(self):
"""Update the markets listbox while preserving selection if possible"""
# Remember current selection before clearing
current_selection = self.market_listbox.curselection()
selected_slug = None
if current_selection and self.market_slugs:
idx = current_selection[0]
if idx < len(self.market_slugs):
selected_slug = self.market_slugs[idx]
self.market_listbox.delete(0, tk.END)
if not self.filtered_trades:
self.market_slugs = []
return
markets = get_unique_markets(self.filtered_trades)
# Count trades per market for display
trades_by_market = group_trades_by_market(self.filtered_trades)
self.market_slugs = sorted(markets.keys())
new_selection_idx = None
for i, slug in enumerate(self.market_slugs):
title = markets[slug]
trade_count = len(trades_by_market.get(slug, []))
# Show trade count next to market name
count_suffix = f" ({trade_count} trades)"
max_title_len = 60 - len(count_suffix)
if len(title) > max_title_len:
display_text = f"{title[:max_title_len]}...{count_suffix}"
else:
display_text = f"{title}{count_suffix}"
self.market_listbox.insert(tk.END, display_text)
# Check if this was the previously selected market
if slug == selected_slug:
new_selection_idx = i
# Restore selection if the market still exists in filtered list
if new_selection_idx is not None:
self.market_listbox.selection_set(new_selection_idx)
self.market_listbox.see(new_selection_idx)
def _filter_market_listbox(self):
"""Filter market listbox based on search text"""
search_text = self.market_search_var.get().strip().lower()
if not self.filtered_trades:
return
self.market_listbox.delete(0, tk.END)
self.market_listbox.selection_clear(0, tk.END)
markets = get_unique_markets(self.filtered_trades)
trades_by_market = group_trades_by_market(self.filtered_trades)
# Filter and rebuild the visible slugs list
self.market_slugs = []
for slug in sorted(markets.keys()):
title = markets[slug]
if search_text and search_text not in title.lower() and search_text not in slug.lower():
continue
self.market_slugs.append(slug)
trade_count = len(trades_by_market.get(slug, []))
count_suffix = f" ({trade_count} trades)"
max_title_len = 60 - len(count_suffix)
if len(title) > max_title_len:
display_text = f"{title[:max_title_len]}...{count_suffix}"
else:
display_text = f"{title}{count_suffix}"
self.market_listbox.insert(tk.END, display_text)
def update_summary_display(self):
"""Update the global summary display"""
self.summary_text.delete(1.0, tk.END)
if not self.filtered_trades:
self.summary_text.insert(tk.END, "No trades loaded.\n")
return
try:
summary = calculate_global_pnl_summary(self.filtered_trades)
output = []
output.append("=" * 60)
output.append("GLOBAL PnL SUMMARY")
output.append("=" * 60)
currency = summary.get("currency", "USD")
cur_sym = "$" if currency in ("USD", "USDC") else f"{currency} "
output.append(f"\nTotal Trades: {summary['total_trades']}")
output.append(f"Total PnL: {cur_sym}{summary['total_pnl']:.2f}")
output.append(f"Average PnL per Trade: {cur_sym}{summary['avg_pnl']:.2f}")
output.append(f"\nWinning Trades: {summary['winning_trades']}")
output.append(f"Losing Trades: {summary['losing_trades']}")
output.append(f"Breakeven Trades: {summary.get('breakeven_trades', 0)}")
output.append(f"Win Rate: {summary['win_rate']:.1f}%")
output.append(f"\nTotal Invested: {cur_sym}{summary['total_invested']:.2f}")
output.append(f"Total Returned: {cur_sym}{summary['total_returned']:.2f}")
output.append(f"ROI: {summary['roi']:.2f}%")
# Currency breakdown if multiple currencies present
if summary.get("by_currency"):
output.append("\n" + "-" * 60)
output.append("CURRENCY BREAKDOWN")
output.append("-" * 60)
for currency, data in summary["by_currency"].items():
output.append(f"\n {currency}:")
output.append(f" Trades: {data.get('total_trades', 'N/A')}")
if isinstance(data.get("total_pnl"), (int, float)):
output.append(f" PnL: {data['total_pnl']:.2f} {currency}")
if isinstance(data.get("win_rate"), (int, float)):
output.append(f" Win Rate: {data['win_rate']:.1f}%")
# Provider/source breakdown (use pre-computed by_source from summary)
if summary.get("by_source"):
output.append("\n" + "-" * 60)
output.append("PROVIDER BREAKDOWN")
output.append("-" * 60)
for source, data in sorted(summary["by_source"].items()):
output.append(f"\n {source.capitalize()}:")
output.append(f" Trades: {data.get('total_trades', 0)}")
pnl_val = data.get("total_pnl", 0)
cur = data.get("currency", "USD")
output.append(f" PnL: {pnl_val:.2f} {cur}")
# Advanced metrics
metrics = calculate_advanced_metrics(self.filtered_trades)
output.append("\n" + "=" * 60)
output.append("ADVANCED METRICS")
output.append("=" * 60)
output.append(f"\nSharpe Ratio: {metrics['sharpe_ratio']:.4f}")
output.append(f"Sortino Ratio: {metrics['sortino_ratio']:.4f}")
output.append(f"Profit Factor: {metrics['profit_factor']:.2f}")
output.append(f"Expectancy: {cur_sym}{metrics['expectancy']:.4f}")
output.append(
f"\nMax Drawdown: {cur_sym}{metrics['max_drawdown']:.2f} ({metrics['max_drawdown_pct']:.1f}%)"
)
output.append(f"Max DD Duration: {metrics['max_drawdown_duration_trades']} trades")
output.append(
f"\nAvg Win: {cur_sym}{metrics['avg_win']:.2f} | Avg Loss: {cur_sym}{metrics['avg_loss']:.2f}"
)
output.append(
f"Largest Win: {cur_sym}{metrics['largest_win']:.2f} | Largest Loss: {cur_sym}{metrics['largest_loss']:.2f}"
)
output.append(
f"Max Win Streak: {metrics['max_win_streak']} | Max Loss Streak: {metrics['max_loss_streak']}"
)
output.append("\n" + "=" * 60)
self.summary_text.insert(tk.END, "\n".join(output))
except Exception as e:
self.summary_text.insert(tk.END, f"Error calculating summary:\n{str(e)}")
def refresh_trades_browser(self):
"""Populate the trade browser treeview with current filtered trades"""