-
Notifications
You must be signed in to change notification settings - Fork 37
Expand file tree
/
Copy pathtrading_bot.py
More file actions
1864 lines (1550 loc) · 89.5 KB
/
trading_bot.py
File metadata and controls
1864 lines (1550 loc) · 89.5 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
"""
Simple Kalshi trading bot with Octagon research and OpenAI decision making.
"""
import asyncio
import argparse
import json
import csv
import json
import csv
import datetime
import math
from pathlib import Path
import sys
from datetime import datetime
from pathlib import Path
from typing import Dict, Any, List, Optional
import time
from rich.console import Console
from rich.table import Table
from rich.progress import Progress, SpinnerColumn, TextColumn
from loguru import logger
import re
from kalshi_client import KalshiClient
from research_client import OctagonClient
from betting_models import BettingDecision, MarketAnalysis, ProbabilityExtraction
from config import load_config
import openai
class SimpleTradingBot:
"""Simple trading bot that follows a clear workflow."""
def __init__(self, live_trading: bool = False, max_close_ts: Optional[int] = None):
self.config = load_config()
# Override dry_run based on CLI parameter
self.config.dry_run = not live_trading
self.console = Console()
self.kalshi_client = None
self.research_client = None
self.openai_client = None
self.max_close_ts = max_close_ts
async def initialize(self):
"""Initialize all API clients."""
self.console.print("[bold blue]Initializing trading bot...[/bold blue]")
# Initialize clients
self.kalshi_client = KalshiClient(
self.config.kalshi,
self.config.minimum_time_remaining_hours,
self.config.max_markets_per_event,
max_close_ts=self.max_close_ts,
)
self.research_client = OctagonClient(self.config.octagon)
self.openai_client = openai.AsyncOpenAI(api_key=self.config.openai.api_key)
# Test connections
await self.kalshi_client.login()
self.console.print("[green]✓ Kalshi API connected[/green]")
self.console.print("[green]✓ Octagon API ready[/green]")
self.console.print("[green]✓ OpenAI API ready[/green]")
# Show environment info
env_color = "green" if self.config.kalshi.use_demo else "yellow"
env_name = "DEMO" if self.config.kalshi.use_demo else "PRODUCTION"
mode = "DRY RUN" if self.config.dry_run else "LIVE TRADING"
self.console.print(f"\n[{env_color}]Environment: {env_name}[/{env_color}]")
self.console.print(f"[blue]Mode: {mode}[/blue]")
self.console.print(f"[blue]Max events to analyze: {self.config.max_events_to_analyze}[/blue]")
self.console.print(f"[blue]Research batch size: {self.config.research_batch_size}[/blue]")
self.console.print(f"[blue]Skip existing positions: {self.config.skip_existing_positions}[/blue]")
self.console.print(f"[blue]Minimum time to event strike: {self.config.minimum_time_remaining_hours} hours (for events with strike_date)[/blue]")
self.console.print(f"[blue]Max markets per event: {self.config.max_markets_per_event}[/blue]")
self.console.print(f"[blue]Max bet amount: ${self.config.max_bet_amount}[/blue]")
hedging_status = "Enabled" if self.config.enable_hedging else "Disabled"
self.console.print(f"[blue]Risk hedging: {hedging_status} (ratio: {self.config.hedge_ratio}, min confidence: {self.config.min_confidence_for_hedging})[/blue]")
# Show risk-adjusted trading settings
self.console.print(f"[blue]R-score filtering: Enabled (z-threshold: {self.config.z_threshold})[/blue]")
if self.config.enable_kelly_sizing:
self.console.print(f"[blue]Kelly sizing: Enabled (fraction: {self.config.kelly_fraction}, bankroll: ${self.config.bankroll})[/blue]")
self.console.print(f"[blue]Portfolio selection: {self.config.portfolio_selection_method} (max positions: {self.config.max_portfolio_positions})[/blue]\n")
if self.max_close_ts is not None:
hours_from_now = (self.max_close_ts - int(time.time())) / 3600
# Show one decimal hour precision
self.console.print(f"[blue]Market expiration filter: close before ~{hours_from_now:.1f} hours from now[/blue]")
def calculate_risk_adjusted_metrics(self, research_prob: float, market_price: float, action: str) -> dict:
"""
Calculate hedge-fund style risk-adjusted metrics.
Args:
research_prob: Research probability (0-1)
market_price: Market price (0-1)
action: "buy_yes" or "buy_no"
Returns:
dict with expected_return, r_score, kelly_fraction
"""
try:
# Adjust probabilities based on action
if action == "buy_yes":
p = research_prob # Our probability of YES
y = market_price # Market price of YES
elif action == "buy_no":
p = 1 - research_prob # Our probability of NO (1 - research_prob_of_yes)
y = market_price # Market price of NO
else:
return {"expected_return": 0.0, "r_score": 0.0, "kelly_fraction": 0.0}
# Prevent division by zero and invalid probabilities
if y <= 0 or y >= 1 or p <= 0 or p >= 1:
return {"expected_return": 0.0, "r_score": 0.0, "kelly_fraction": 0.0}
# Expected return on capital: E[R] = (p-y)/y
expected_return = (p - y) / y
# Risk-Adjusted Edge (R-score): (p-y)/sqrt(p*(1-p))
# This is the z-score - how many standard deviations away from fair value
variance = p * (1 - p)
if variance <= 0:
return {"expected_return": expected_return, "r_score": 0.0, "kelly_fraction": 0.0}
r_score = (p - y) / math.sqrt(variance)
# Kelly fraction: f_kelly = (p-y)/(1-y)
# This gives the optimal fraction of bankroll to bet
if y >= 1:
kelly_fraction = 0.0
else:
kelly_fraction = (p - y) / (1 - y)
# Ensure Kelly fraction is reasonable (between 0 and 1)
kelly_fraction = max(0.0, min(1.0, kelly_fraction))
return {
"expected_return": expected_return,
"r_score": r_score,
"kelly_fraction": kelly_fraction
}
except Exception as e:
logger.warning(f"Error calculating risk metrics: {e}")
return {"expected_return": 0.0, "r_score": 0.0, "kelly_fraction": 0.0}
def calculate_kelly_position_size(self, kelly_fraction: float) -> float:
"""
Calculate position size using fractional Kelly criterion.
Args:
kelly_fraction: Optimal Kelly fraction (0-1)
Returns:
Position size in dollars
"""
if not self.config.enable_kelly_sizing or kelly_fraction <= 0:
return self.config.max_bet_amount
# Apply fractional Kelly (e.g., half-Kelly)
adjusted_kelly = kelly_fraction * self.config.kelly_fraction
# Calculate position size as fraction of bankroll
kelly_bet_size = self.config.bankroll * adjusted_kelly
# Apply maximum bet fraction constraint
max_allowed = self.config.bankroll * self.config.max_kelly_bet_fraction
kelly_bet_size = min(kelly_bet_size, max_allowed)
# Apply absolute maximum bet limit
kelly_bet_size = min(kelly_bet_size, self.config.max_bet_amount)
# Ensure minimum bet size
kelly_bet_size = max(kelly_bet_size, 1.0)
return kelly_bet_size
def apply_portfolio_selection(self, analysis: MarketAnalysis, event_ticker: str) -> MarketAnalysis:
"""
Apply portfolio selection to hold only the N highest R-scores.
Step 4: Portfolio view - hold the N highest R-scores subject to limits.
"""
if self.config.portfolio_selection_method == "legacy":
# Skip portfolio optimization, use existing logic
return analysis
# Filter out skip decisions for ranking
actionable_decisions = [d for d in analysis.decisions if d.action != "skip"]
skip_decisions = [d for d in analysis.decisions if d.action == "skip"]
if not actionable_decisions:
return analysis
if self.config.portfolio_selection_method == "top_r_scores":
# Sort by R-score (highest first)
actionable_decisions.sort(key=lambda d: d.r_score or -999, reverse=True)
# Select top N positions
max_positions = self.config.max_portfolio_positions
selected_decisions = actionable_decisions[:max_positions]
# Convert remaining to skip decisions
rejected_decisions = []
for decision in actionable_decisions[max_positions:]:
skip_decision = BettingDecision(
ticker=decision.ticker,
action="skip",
confidence=decision.confidence,
amount=0.0,
reasoning=f"Portfolio limit: R-score {decision.r_score:.2f} ranked #{len(selected_decisions)+1}",
event_name=decision.event_name,
market_name=decision.market_name,
expected_return=decision.expected_return,
r_score=decision.r_score,
kelly_fraction=decision.kelly_fraction,
market_price=decision.market_price,
research_probability=decision.research_probability
)
rejected_decisions.append(skip_decision)
if rejected_decisions:
logger.info(f"Portfolio selection: kept top {len(selected_decisions)} positions, "
f"rejected {len(rejected_decisions)} lower R-score positions")
# Combine selected decisions with all skip decisions
analysis.decisions = selected_decisions + skip_decisions + rejected_decisions
elif self.config.portfolio_selection_method == "diversified":
# Future enhancement: could implement diversification by event category, etc.
# For now, fall back to top R-scores
return self.apply_portfolio_selection(analysis, event_ticker)
return analysis
async def get_top_events(self) -> List[Dict[str, Any]]:
"""Get top events sorted by 24-hour volume."""
self.console.print("[bold]Step 1: Fetching top events...[/bold]")
with Progress(
SpinnerColumn(),
TextColumn("[progress.description]{task.description}"),
console=self.console,
transient=True,
) as progress:
task = progress.add_task("Fetching events...", total=None)
try:
# Get a larger pool of events to ensure we have enough after filtering positions
# Use 3x the target amount to account for events with existing positions
fetch_limit = self.config.max_events_to_analyze * 3
events = await self.kalshi_client.get_events(limit=fetch_limit)
self.console.print(f"[blue]• Fetched {len(events)} events (will filter to top {self.config.max_events_to_analyze} after position filtering)[/blue]")
self.console.print(f"[green]✓ Found {len(events)} events[/green]")
# Show top 10 events
table = Table(title="Top 10 Events by 24h Volume")
table.add_column("Event Ticker", style="cyan")
table.add_column("Title", style="yellow")
table.add_column("24h Volume", style="magenta", justify="right")
table.add_column("Time Remaining", style="blue", justify="right")
table.add_column("Category", style="green")
table.add_column("Mutually Exclusive", style="red", justify="center")
for event in events[:10]:
time_remaining = event.get('time_remaining_hours')
if time_remaining is None:
time_str = "No date set"
elif time_remaining > 24:
time_str = f"{time_remaining/24:.1f} days"
else:
time_str = f"{time_remaining:.1f} hours"
table.add_row(
event.get('event_ticker', 'N/A'),
event.get('title', 'N/A')[:35] + ("..." if len(event.get('title', '')) > 35 else ""),
f"{event.get('volume_24h', 0):,}",
time_str,
event.get('category', 'N/A'),
"YES" if event.get('mutually_exclusive', False) else "NO"
)
self.console.print(table)
return events
except Exception as e:
self.console.print(f"[red]Error fetching events: {e}[/red]")
return []
async def get_markets_for_events(self, events: List[Dict[str, Any]]) -> Dict[str, List[Dict[str, Any]]]:
"""Get markets for each event (uses pre-loaded markets from events)."""
self.console.print(f"\n[bold]Step 2: Processing markets for {len(events)} events...[/bold]")
event_markets = {}
for event in events:
event_ticker = event.get('event_ticker', '')
if not event_ticker:
continue
# Use pre-loaded markets from the event data
markets = event.get('markets', [])
total_markets = event.get('total_markets', len(markets))
if markets:
# Convert to the format expected by the rest of the system
simple_markets = []
for market in markets:
simple_markets.append({
"ticker": market.get("ticker", ""),
"title": market.get("title", ""),
"subtitle": market.get("subtitle", ""),
"volume": market.get("volume", 0),
"open_time": market.get("open_time", ""),
"close_time": market.get("close_time", ""),
})
event_markets[event_ticker] = {
'event': event,
'markets': simple_markets
}
if total_markets > len(markets):
self.console.print(f"[green]✓ Using top {len(markets)} markets for {event_ticker} (from {total_markets} total)[/green]")
else:
self.console.print(f"[green]✓ Using {len(markets)} markets for {event_ticker}[/green]")
else:
self.console.print(f"[yellow]⚠ No markets found for {event_ticker}[/yellow]")
total_markets = sum(len(data['markets']) for data in event_markets.values())
self.console.print(f"[green]✓ Processing {total_markets} total markets across {len(event_markets)} events[/green]")
return event_markets
async def filter_markets_by_positions(self, event_markets: Dict[str, Dict[str, Any]]) -> Dict[str, Dict[str, Any]]:
"""Filter out markets where we already have positions to save research time."""
if self.config.dry_run or not self.config.skip_existing_positions:
# Skip position filtering in dry run mode or if disabled
return event_markets
self.console.print(f"\n[bold]Step 2.5: Filtering markets by existing positions...[/bold]")
filtered_event_markets = {}
total_markets_before = 0
total_markets_after = 0
skipped_markets = 0
with Progress(
SpinnerColumn(),
TextColumn("[progress.description]{task.description}"),
console=self.console,
) as progress:
# Count total markets for progress
total_markets = sum(len(data['markets']) for data in event_markets.values())
task = progress.add_task("Checking existing positions...", total=total_markets)
for event_ticker, data in event_markets.items():
event = data['event']
markets = data['markets']
total_markets_before += len(markets)
# Check if we have positions in ANY market of this event
event_has_positions = False
markets_checked = 0
for market in markets:
ticker = market.get('ticker', '')
if not ticker:
progress.update(task, advance=1)
markets_checked += 1
continue
try:
# Check if we already have a position in this market
has_position = await self.kalshi_client.has_position_in_market(ticker)
if has_position:
self.console.print(f"[yellow]⚠ Found position in {ticker}[/yellow]")
event_has_positions = True
# Update progress for remaining unchecked markets in this event
remaining_markets = len(markets) - markets_checked - 1
progress.update(task, advance=remaining_markets + 1)
break # No need to check other markets in this event
except Exception as e:
logger.warning(f"Could not check position for {ticker}: {e}")
# If we can't check, assume no position and continue checking other markets
progress.update(task, advance=1)
markets_checked += 1
if event_has_positions:
skipped_markets += len(markets) # Count all markets in event as skipped
self.console.print(f"[yellow]⚠ Skipping entire event {event_ticker}: Has existing positions[/yellow]")
else:
# No positions found, keep the entire event
filtered_event_markets[event_ticker] = {
'event': event,
'markets': markets
}
total_markets_after += len(markets)
self.console.print(f"[green]✓ Keeping entire event {event_ticker}: No existing positions[/green]")
# Show filtering summary
events_skipped = len(event_markets) - len(filtered_event_markets)
self.console.print(f"\n[blue]Position filtering summary:[/blue]")
self.console.print(f"[blue]• Events before filtering: {len(event_markets)}[/blue]")
self.console.print(f"[blue]• Events after filtering: {len(filtered_event_markets)}[/blue]")
self.console.print(f"[blue]• Events skipped (existing positions): {events_skipped}[/blue]")
self.console.print(f"[blue]• Markets in skipped events: {skipped_markets}[/blue]")
self.console.print(f"[blue]• Markets remaining for research: {total_markets_after}[/blue]")
if len(filtered_event_markets) == 0:
self.console.print("[yellow]⚠ No events remaining after position filtering[/yellow]")
elif events_skipped > 0:
time_saved_estimate = events_skipped * 3 # Rough estimate: 3 minutes per event research
self.console.print(f"[green]✓ Estimated time saved by skipping research: ~{time_saved_estimate} minutes[/green]")
return filtered_event_markets
def _parse_probabilities_from_research(self, research_text: str, markets: List[Dict[str, Any]]) -> Dict[str, float]:
"""Parse probability predictions from Octagon research text."""
probabilities = {}
# Look for patterns with both ticker names and market titles
for market in markets:
ticker = market.get('ticker', '')
title = market.get('title', '')
if not ticker:
continue
# Try different patterns to find probability for this market
# Look for both ticker and title patterns
search_terms = [ticker]
if title:
# Add key words from the title for better matching
search_terms.append(title)
# Extract key identifying words (avoid common words)
title_words = [w for w in title.split() if len(w) > 3 and w.lower() not in ['will', 'the', 'win', 'be', 'a', 'be', 'of', 'and', 'or', 'for', 'to', 'in', 'on', 'at', 'with', 'from', 'by', 'about', 'into', 'through', 'during', 'before', 'after', 'above', 'below', 'up', 'down', 'out', 'off', 'over', 'under', 'again', 'further', 'then', 'once']]
search_terms.extend(title_words)
found_probability = None
for term in search_terms:
if not term:
continue
# Try different patterns to find probability for this term
patterns = [
rf"{re.escape(term)}[:\s]*(\d+\.?\d*)%",
rf"{re.escape(term)}[:\s]*(\d+)%",
rf"(\d+\.?\d*)%[:\s]*{re.escape(term)}",
rf"(\d+)%[:\s]*{re.escape(term)}",
rf"probability.*{re.escape(term)}[:\s]*(\d+\.?\d*)%",
rf"{re.escape(term)}.*probability.*?(\d+\.?\d*)%",
rf"{re.escape(term)}.*(\d+\.?\d*)%.*probability",
rf"probability.*(\d+\.?\d*)%.*{re.escape(term)}",
# More flexible patterns for natural language
rf"{re.escape(term)}.*?(\d+\.?\d*)%",
rf"(\d+\.?\d*)%.*?{re.escape(term)}",
]
for pattern in patterns:
matches = re.findall(pattern, research_text, re.IGNORECASE | re.DOTALL)
if matches:
try:
prob = float(matches[0])
if 0 <= prob <= 100:
found_probability = prob
break
except ValueError:
continue
if found_probability is not None:
break
if found_probability is not None:
probabilities[ticker] = found_probability
logger.info(f"Found probability for {ticker}: {found_probability}%")
else:
logger.warning(f"No probability found for {ticker} (title: {title})")
# Show first 200 chars of research text for debugging
sample_text = research_text[:200].replace('\n', ' ')
logger.debug(f"Research sample: {sample_text}...")
return probabilities
async def research_events(self, event_markets: Dict[str, Dict[str, Any]]) -> Dict[str, str]:
"""Research each event and its markets using Octagon Deep Research."""
self.console.print(f"\n[bold]Step 3: Researching {len(event_markets)} events...[/bold]")
research_results = {}
with Progress(
SpinnerColumn(),
TextColumn("[progress.description]{task.description}"),
console=self.console,
) as progress:
task = progress.add_task("Researching events...", total=len(event_markets))
# Research events in batches to avoid rate limits
batch_size = self.config.research_batch_size
event_items = list(event_markets.items())
for i in range(0, len(event_items), batch_size):
batch = event_items[i:i + batch_size]
self.console.print(f"[blue]Processing research batch {i//batch_size + 1} with {len(batch)} events[/blue]")
# Research batch in parallel with per-event timeout
tasks = []
for event_ticker, data in batch:
event = data['event']
markets = data['markets']
if event and markets:
coro = self.research_client.research_event(event, markets)
# Apply per-event timeout to avoid hanging the whole batch
tasks.append(asyncio.wait_for(coro, timeout=self.config.research_timeout_seconds))
else:
tasks.append(asyncio.sleep(0, result=None))
try:
results = await asyncio.gather(*tasks, return_exceptions=True)
for (event_ticker, data), result in zip(batch, results):
if not isinstance(result, Exception) and result:
research_results[event_ticker] = result
progress.update(task, advance=1)
self.console.print(f"[green]✓ Researched {event_ticker}[/green]")
else:
err = result
if isinstance(result, asyncio.TimeoutError):
err = f"Timeout after {self.config.research_timeout_seconds}s"
self.console.print(f"[red]✗ Failed to research {event_ticker}: {err}[/red]")
progress.update(task, advance=1)
except Exception as e:
self.console.print(f"[red]Batch research error: {e}[/red]")
# Ensure progress advances for this entire batch even on error
progress.update(task, advance=len(batch))
# Brief pause between batches
await asyncio.sleep(1)
self.console.print(f"[green]✓ Completed research on {len(research_results)} events[/green]")
return research_results
async def _extract_probabilities_for_event(self, event_ticker: str, research_text: str,
event_markets: Dict[str, Dict[str, Any]]) -> tuple[str, Optional[ProbabilityExtraction]]:
"""Extract probabilities for a single event."""
try:
# Get market information for this event
event_data = event_markets.get(event_ticker, {})
markets = event_data.get('markets', [])
event_info = event_data.get('event', {})
# Prepare market information for the prompt
market_info = []
for market in markets:
market_info.append({
'ticker': market.get('ticker', ''),
'title': market.get('title', ''),
'yes_mid_price': market.get('yes_mid_price', 0),
'no_mid_price': market.get('no_mid_price', 0)
})
# Create prompt for probability extraction
prompt = f"""
Based on the following deep research, extract the probability estimates for each market.
Event: {event_info.get('title', event_ticker)}
Markets:
{json.dumps(market_info, indent=2)}
Research Results:
{research_text}
For each market, provide:
1. The research-based probability estimate (0-100%)
2. Clear reasoning for that probability
3. Confidence level in the estimate (0-1)
Focus on extracting concrete probability estimates from the research, not market prices.
If the research doesn't provide a clear probability for a market, make your best estimate based on the available information.
"""
# Use Responses API structured outputs
from openai_utils import responses_parse_pydantic
extraction = await responses_parse_pydantic(
self.openai_client,
model=self.config.openai.model if self.config.openai.model else "gpt-5",
messages=[
{"role": "system", "content": "You are a professional prediction market analyst. Extract probability estimates from research with structured output."},
{"role": "user", "content": prompt}
],
response_format=ProbabilityExtraction,
reasoning_effort="low",
text_verbosity="medium",
)
return event_ticker, extraction
except Exception as e:
logger.error(f"Error extracting probabilities for {event_ticker}: {e}")
return event_ticker, None
async def extract_probabilities(self, research_results: Dict[str, str],
event_markets: Dict[str, Dict[str, Any]]) -> Dict[str, ProbabilityExtraction]:
"""Extract structured probabilities from research results using GPT-5 in parallel."""
self.console.print(f"\n[bold]Step 3.5: Extracting probabilities from research...[/bold]")
probability_extractions = {}
with Progress(
SpinnerColumn(),
TextColumn("[progress.description]{task.description}"),
console=self.console,
) as progress:
task = progress.add_task("Extracting probabilities...", total=len(research_results))
# Create tasks for all events to run in parallel
tasks = []
for event_ticker, research_text in research_results.items():
task_coroutine = self._extract_probabilities_for_event(event_ticker, research_text, event_markets)
tasks.append(task_coroutine)
# Run all probability extractions in parallel
results = await asyncio.gather(*tasks, return_exceptions=True)
# Process results
for result in results:
if isinstance(result, Exception):
logger.error(f"Exception in probability extraction: {result}")
progress.update(task, advance=1)
continue
event_ticker, extraction = result
if extraction is not None:
probability_extractions[event_ticker] = extraction
self.console.print(f"[green]✓ Extracted probabilities for {event_ticker}[/green]")
# Display extracted probabilities
self.console.print(f"[blue]Extracted probabilities for {event_ticker}:[/blue]")
for market_prob in extraction.markets:
self.console.print(f" {market_prob.ticker}: {market_prob.research_probability:.1f}%")
else:
self.console.print(f"[red]✗ Failed to extract probabilities for {event_ticker}[/red]")
progress.update(task, advance=1)
self.console.print(f"[green]✓ Extracted probabilities for {len(probability_extractions)} events[/green]")
return probability_extractions
async def get_market_odds(self, event_markets: Dict[str, Dict[str, Any]]) -> Dict[str, Dict[str, Any]]:
"""Fetch current market odds for all markets."""
self.console.print(f"\n[bold]Step 4: Fetching current market odds...[/bold]")
market_odds = {}
all_tickers = []
# Collect all market tickers
for event_ticker, data in event_markets.items():
markets = data['markets']
for market in markets:
ticker = market.get('ticker', '')
if ticker:
all_tickers.append(ticker)
with Progress(
SpinnerColumn(),
TextColumn("[progress.description]{task.description}"),
console=self.console,
) as progress:
task = progress.add_task("Fetching market odds...", total=len(all_tickers))
# Fetch odds in batches to avoid overwhelming the API
batch_size = 20
for i in range(0, len(all_tickers), batch_size):
batch = all_tickers[i:i + batch_size]
# Fetch batch in parallel
tasks = []
for ticker in batch:
tasks.append(self.kalshi_client.get_market_with_odds(ticker))
try:
results = await asyncio.gather(*tasks, return_exceptions=True)
for ticker, result in zip(batch, results):
if not isinstance(result, Exception) and result:
market_odds[ticker] = result
progress.update(task, advance=1)
else:
self.console.print(f"[red]✗ Failed to get odds for {ticker}[/red]")
progress.update(task, advance=1)
except Exception as e:
self.console.print(f"[red]Batch odds fetch error: {e}[/red]")
progress.update(task, advance=len(batch))
# Brief pause between batches
await asyncio.sleep(0.2)
self.console.print(f"[green]✓ Fetched odds for {len(market_odds)} markets[/green]")
return market_odds
async def _get_betting_decisions_for_event(self, event_ticker: str, data: Dict[str, Any],
probability_extraction: ProbabilityExtraction,
market_odds: Dict[str, Dict[str, Any]]) -> tuple[str, Optional[MarketAnalysis]]:
"""Get betting decisions for a single event with error handling."""
try:
# Get event-specific decisions
event_analysis = await self._get_event_betting_decisions(
event_ticker, data, probability_extraction, market_odds
)
return event_ticker, event_analysis
except Exception as e:
logger.error(f"Error generating decisions for {event_ticker}: {e}")
return event_ticker, None
async def get_betting_decisions(self, event_markets: Dict[str, Dict[str, Any]],
probability_extractions: Dict[str, ProbabilityExtraction],
market_odds: Dict[str, Dict[str, Any]]) -> MarketAnalysis:
"""Use OpenAI to make structured betting decisions per event in parallel."""
self.console.print(f"\n[bold]Step 5: Generating betting decisions...[/bold]")
# Process events in parallel for better performance
all_decisions = []
total_recommended_bet = 0.0
high_confidence_bets = 0
event_summaries = []
# Filter to events that have both research results and markets
processable_events = [
(event_ticker, data) for event_ticker, data in event_markets.items()
if event_ticker in probability_extractions and data['markets']
]
with Progress(
SpinnerColumn(),
TextColumn("[progress.description]{task.description}"),
console=self.console,
) as progress:
task = progress.add_task("Generating betting decisions...", total=len(processable_events))
# Create tasks for all events to run in parallel
tasks = []
for event_ticker, data in processable_events:
task_coroutine = self._get_betting_decisions_for_event(
event_ticker, data, probability_extractions[event_ticker], market_odds
)
tasks.append(task_coroutine)
# Run all betting decision generations in parallel
results = await asyncio.gather(*tasks, return_exceptions=True)
# Process results
for result in results:
if isinstance(result, Exception):
logger.error(f"Exception in betting decisions generation: {result}")
progress.update(task, advance=1)
continue
event_ticker, event_analysis = result
if event_analysis is not None:
# Display decisions for this event
self._display_event_decisions(event_ticker, event_analysis)
# Aggregate results
all_decisions.extend(event_analysis.decisions)
total_recommended_bet += event_analysis.total_recommended_bet
high_confidence_bets += event_analysis.high_confidence_bets
event_summaries.append(f"{event_ticker}: {event_analysis.summary}")
self.console.print(f"[green]✓ Generated {len(event_analysis.decisions)} decisions for {event_ticker}[/green]")
else:
self.console.print(f"[red]✗ Failed to generate decisions for {event_ticker}[/red]")
progress.update(task, advance=1)
# Generate hedge decisions for risk management
hedge_decisions = self._generate_hedge_decisions(all_decisions)
if hedge_decisions:
all_decisions.extend(hedge_decisions)
# Update totals to include hedge amounts
hedge_bet_total = sum(d.amount for d in hedge_decisions)
total_recommended_bet += hedge_bet_total
self.console.print(f"[blue]💡 Generated {len(hedge_decisions)} hedge bets (${hedge_bet_total:.2f}) for risk management[/blue]")
# Create combined analysis
analysis = MarketAnalysis(
decisions=all_decisions,
total_recommended_bet=total_recommended_bet,
high_confidence_bets=high_confidence_bets,
summary=f"Analyzed {len(processable_events)} events. " + " | ".join(event_summaries[:3]) +
(f" and {len(event_summaries) - 3} more..." if len(event_summaries) > 3 else "")
)
# Show overall decision summary
actionable_decisions = [d for d in analysis.decisions if d.action != "skip"]
self.console.print(f"\n[green]✓ Generated {len(analysis.decisions)} total decisions ({len(actionable_decisions)} actionable)[/green]")
# Display consolidated summary table
if actionable_decisions:
table = Table(title="📊 All Betting Decisions Summary", show_lines=True)
table.add_column("Type", style="bright_blue", justify="center", width=8)
table.add_column("Event", style="bright_blue", width=22)
table.add_column("Market", style="cyan", width=32)
table.add_column("Action", style="yellow", justify="center", width=10)
table.add_column("Confidence", style="magenta", justify="right", width=10)
table.add_column("Amount", style="green", justify="right", width=10)
table.add_column("Reasoning", style="blue", width=65)
for decision in actionable_decisions:
# Use human-readable names if available
event_name = decision.event_name if decision.event_name else "Unknown Event"
market_name = decision.market_name if decision.market_name else decision.ticker
# Determine bet type
bet_type = "🛡️ Hedge" if decision.is_hedge else "💰 Main"
table.add_row(
bet_type,
event_name,
market_name,
decision.action.upper().replace('_', ' '),
f"{decision.confidence:.2f}",
f"${decision.amount:.2f}",
decision.reasoning
)
self.console.print(table)
else:
self.console.print("[yellow]No actionable betting decisions generated[/yellow]")
# Show summary
self.console.print(f"\n[blue]Total recommended bet: ${analysis.total_recommended_bet:.2f}[/blue]")
self.console.print(f"[blue]High confidence bets: {analysis.high_confidence_bets}[/blue]")
self.console.print(f"[blue]Strategy: {analysis.summary}[/blue]")
return analysis
def _generate_hedge_decisions(self, main_decisions: List[BettingDecision]) -> List[BettingDecision]:
"""Generate hedge decisions to minimize risk for main betting decisions."""
if not self.config.enable_hedging:
return []
hedge_decisions = []
for main_decision in main_decisions:
# Skip if this is already a hedge or a skip
if main_decision.is_hedge or main_decision.action == "skip":
continue
# Only hedge if confidence is below threshold (higher risk bets)
if main_decision.confidence >= self.config.min_confidence_for_hedging:
continue
# Calculate hedge amount
hedge_amount = min(
main_decision.amount * self.config.hedge_ratio,
self.config.max_hedge_amount
)
# Only create hedge if amount is meaningful (at least $1)
if hedge_amount < 1.0:
continue
# Create opposite hedge position
hedge_action = "buy_no" if main_decision.action == "buy_yes" else "buy_yes"
hedge_decision = BettingDecision(
ticker=main_decision.ticker,
action=hedge_action,
confidence=0.8, # Hedge has high confidence (it's risk management)
amount=hedge_amount,
reasoning=f"Risk hedge: {self.config.hedge_ratio*100:.0f}% hedge for {main_decision.action} (confidence {main_decision.confidence:.2f} < {self.config.min_confidence_for_hedging:.2f})",
event_name=main_decision.event_name,
market_name=main_decision.market_name,
is_hedge=True,
hedge_for=main_decision.ticker,
hedge_ratio=self.config.hedge_ratio
)
hedge_decisions.append(hedge_decision)
return hedge_decisions
def _display_event_decisions(self, event_ticker: str, event_analysis: MarketAnalysis):
"""Display the betting decisions for a single event."""
# Filter to actionable decisions (not skip)
actionable_decisions = [
decision for decision in event_analysis.decisions
if decision.action != "skip"
]
# Check if any decisions were adjusted due to mutually exclusive constraint
mutually_exclusive_adjustments = [
decision for decision in event_analysis.decisions
if decision.action != "skip" and "Mutually exclusive hedge" in decision.reasoning
]
# Check if strategic filtering was applied
strategic_filtering_skips = [
decision for decision in event_analysis.decisions
if decision.action == "skip" and "Strategic filter" in decision.reasoning
]
if not actionable_decisions:
self.console.print(f"[yellow]No actionable decisions for {event_ticker}[/yellow]")
return
# Create event-specific table
event_name = actionable_decisions[0].event_name if actionable_decisions else "Unknown Event"
table = Table(title=f"Betting Decisions for {event_name}", show_lines=True)
table.add_column("Type", style="bright_blue", justify="center", width=8)
table.add_column("Market", style="cyan", width=40)
table.add_column("Action", style="yellow", justify="center", width=10)
table.add_column("Confidence", style="magenta", justify="right", width=10)
table.add_column("Amount", style="green", justify="right", width=10)
table.add_column("Reasoning", style="blue", width=70)
for decision in actionable_decisions:
# Use human-readable market name if available, otherwise generate from ticker
market_display = decision.market_name if decision.market_name else self._generate_readable_market_name(decision.ticker)
# Determine bet type
bet_type = "🛡️ Hedge" if decision.is_hedge else "💰 Main"
table.add_row(
bet_type,
market_display,
decision.action.upper().replace('_', ' '),
f"{decision.confidence:.2f}",
f"${decision.amount:.2f}",
decision.reasoning
)
self.console.print(table)
# Show mutually exclusive strategy info if applicable
if mutually_exclusive_adjustments:
self.console.print(f"[blue]ℹ Strategic hedge betting: {len(mutually_exclusive_adjustments)} positions sized for mutually exclusive event[/blue]")
# Show strategic filtering info if applicable
if strategic_filtering_skips:
self.console.print(f"[yellow]⚡ Strategic filtering: {len(strategic_filtering_skips)} lower-value opportunities skipped, focused on best positions[/yellow]")
# Show event summary
if event_analysis.total_recommended_bet > 0:
self.console.print(f"[blue]Event total: ${event_analysis.total_recommended_bet:.2f} | High confidence: {event_analysis.high_confidence_bets}[/blue]")
async def _get_event_betting_decisions(self, event_ticker: str, event_data: Dict[str, Any],
probability_extraction: ProbabilityExtraction, market_odds: Dict[str, Dict[str, Any]]) -> MarketAnalysis:
"""Get betting decisions for a single event."""
event_info = event_data['event']
markets = event_data['markets']
# Include market odds in the data
markets_with_odds = []
for market in markets:
ticker = market.get('ticker', '')
market_data = {
'ticker': ticker,
'title': market.get('title', ''),
'volume': market.get('volume', 0)
}
# Add current market odds if available
if ticker in market_odds:
odds = market_odds[ticker]
yes_bid = odds.get('yes_bid', 0)
no_bid = odds.get('no_bid', 0)
yes_ask = odds.get('yes_ask', 0)
no_ask = odds.get('no_ask', 0)
# Calculate mid-prices with validation
# Only calculate mid-price if both bid and ask are > 0
yes_mid_price = None
no_mid_price = None
if yes_bid > 0 and yes_ask > 0:
yes_mid_price = (yes_bid + yes_ask) / 2
elif yes_ask > 0:
# If only ask is available, use ask price as approximation
yes_mid_price = yes_ask
elif yes_bid > 0:
# If only bid is available, use bid price as approximation
yes_mid_price = yes_bid
if no_bid > 0 and no_ask > 0:
no_mid_price = (no_bid + no_ask) / 2
elif no_ask > 0:
# If only ask is available, use ask price as approximation
no_mid_price = no_ask
elif no_bid > 0:
# If only bid is available, use bid price as approximation
no_mid_price = no_bid