-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrefresh_weather.py
More file actions
2063 lines (1730 loc) · 79.3 KB
/
Copy pathrefresh_weather.py
File metadata and controls
2063 lines (1730 loc) · 79.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
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
"""
Weather Edge — Multi-model ensemble weather prediction pipeline.
Fetches forecasts from 3 weather models (HRRR, NBM, ECMWF) via OpenMeteo,
compares against Kalshi weather market pricing to find edges.
"""
import json, os, sys, time, math, requests, uuid
from datetime import datetime, timezone, timedelta
from pathlib import Path
from zoneinfo import ZoneInfo
# ============================================================
# CONSTANTS
# ============================================================
OPENMETEO_URL = "https://api.open-meteo.com/v1/forecast"
WEATHER_MODELS = [
"ncep_hrrr_conus", # HRRR (3km, hourly, CONUS, ~48h) — best short-range
"ncep_nbm_conus", # NBM (2.5km, CONUS) — already blends 31 models w/ bias correction
"ecmwf_ifs025", # ECMWF IFS (14km, global) — best global model, adds value day 2+
# Dropped: GFS (redundant, NBM already includes it bias-corrected),
# ICON (Europe-optimized), GEM (Canada-optimized), JMA (55km, noise)
]
KALSHI_BASE = "https://api.elections.kalshi.com/trade-api/v2"
# 10 high-volume Kalshi weather cities
# Format: (display_name, lat, lon, kalshi_high_ticker, kalshi_low_ticker, timezone)
CITIES = {
"NYC": {"name": "New York", "lat": 40.7128, "lon": -74.0060, "high": "KXHIGHNY", "low": "KXLOWTNYC", "tz": "America/New_York"},
"LAX": {"name": "Los Angeles", "lat": 33.9425, "lon": -118.408, "high": "KXHIGHLAX", "low": "KXLOWTLAX", "tz": "America/Los_Angeles"},
"CHI": {"name": "Chicago", "lat": 41.8781, "lon": -87.6298, "high": "KXHIGHCHI", "low": "KXLOWTCHI", "tz": "America/Chicago"},
"MIA": {"name": "Miami", "lat": 25.7617, "lon": -80.1918, "high": "KXHIGHMIA", "low": "KXLOWTMIA", "tz": "America/New_York"},
"DAL": {"name": "Dallas", "lat": 32.8998, "lon": -97.0403, "high": "KXHIGHTDAL", "low": "KXLOWTDAL", "tz": "America/Chicago"},
"DEN": {"name": "Denver", "lat": 39.8561, "lon": -104.674, "high": "KXHIGHDEN", "low": "KXLOWTDEN", "tz": "America/Denver"},
"PHI": {"name": "Philadelphia", "lat": 39.8744, "lon": -75.2424, "high": "KXHIGHPHIL", "low": "KXLOWTPHIL", "tz": "America/New_York"},
"ATL": {"name": "Atlanta", "lat": 33.6407, "lon": -84.4277, "high": "KXHIGHTATL", "low": "KXLOWTATL", "tz": "America/New_York"},
"HOU": {"name": "Houston", "lat": 29.9844, "lon": -95.3414, "high": "KXHIGHTHOU", "low": "KXLOWTHOU", "tz": "America/Chicago"},
"PHX": {"name": "Phoenix", "lat": 33.4373, "lon": -112.008, "high": "KXHIGHTPHX", "low": "KXLOWTPHX", "tz": "America/Phoenix"},
}
# Sigma: city-specific from calibration data, with global fallback
# calibrate.py generates data/city_sigma.json with per-city/type/month sigma + bias
SIGMA_FLOOR = 3.0 # Global fallback when no calibration data (conservative default)
SIGMA_INFLATION = 1.3 # Inflate calibrated sigma to account for operational vs ideal conditions
SIGMA_MIN = 1.5 # Absolute minimum sigma (even PHX can surprise)
# Model weights by forecast horizon. Bucket 2 also serves as the 2+ fallback.
HORIZON_WEIGHTS = {
0: {"ncep_hrrr_conus": 2.0, "ncep_nbm_conus": 1.0, "ecmwf_ifs025": 0.5},
1: {"ncep_hrrr_conus": 1.0, "ncep_nbm_conus": 1.2, "ecmwf_ifs025": 0.8},
2: {"ncep_nbm_conus": 1.2, "ecmwf_ifs025": 1.0},
}
def _load_calibration():
"""Load city-specific sigma + bias from calibration data."""
cal_file = Path(__file__).parent / "data" / "city_sigma.json"
if cal_file.exists():
return json.loads(cal_file.read_text(encoding="utf-8"))
return None
CITY_SIGMA = _load_calibration()
# Edge threshold for signals
EDGE_THRESHOLD = 0.12 # Floor for lows
HIGH_EDGE_THRESHOLD = 0.18 # Higher floor for highs — backtest 2026-04-18: |edge| 0.12-0.18 lost -$3.21 across highs
MAX_DISAGREEMENT = 0.20 # Kill switch: if |model - market| > 20%, it's a model failure, not alpha
# Blocklist — (city, type) combos where calibration bias points the wrong way or
# under-corrects by >2F against current weather patterns (April 2026 backtest).
# Suppressing here until calibration is rebuilt with an operational-data blend.
SIGNAL_BLOCKLIST = frozenset([
("CHI", "high"), # historical bias -2.4F captures only 35% of true -6.9F bias
("DEN", "high"), # cal says cold-biased (-0.8F), reality is warm-biased (+1.8F)
("DEN", "low"), # cal says warm-biased (+0.8F), reality is warmer still (+3.3F)
])
# Suppress HIGH YES signals entirely — backtest: 2/39 = 5% WR, -$3.65 P&L.
# Symptom of residual cold-bias: if our model STILL predicts a high-temp edge
# after bias correction, the correction is insufficient and we're wrong.
SUPPRESS_HIGH_YES = True
# Pause all high-temperature signals until the high model is rebuilt.
# Audit 2026-04-24: high less/greater Brier was 66.7% worse than market mid,
# and recorded high picks were 24.7% winners.
SUPPRESS_HIGH_SIGNALS = True
# ============================================================
# HELPERS
# ============================================================
def horizon_bucket(horizon):
"""Collapse raw day offsets into the buckets used by the live model."""
try:
return min(max(int(horizon), 0), 2)
except (TypeError, ValueError):
return 1
def get_horizon_weights(horizon):
"""Return ensemble weights for the requested forecast horizon bucket."""
return HORIZON_WEIGHTS.get(horizon_bucket(horizon), HORIZON_WEIGHTS[2])
def horizon_weighted_mean(model_temps, horizon):
"""Compute a horizon-weighted mean from {model_key: temperature}."""
weights = get_horizon_weights(horizon)
total_w, total_v = 0.0, 0.0
for model, temp in model_temps.items():
if temp is None:
continue
w = weights.get(model, 0.5)
if w <= 0:
continue
total_v += temp * w
total_w += w
return round(total_v / total_w, 1) if total_w > 0 else None
def get_calibration(city_code, mtype, date_str, horizon=1):
"""Look up city/type/month-specific sigma and bias from calibration data.
Returns (sigma, bias). Falls back to SIGMA_FLOOR if no data."""
if CITY_SIGMA is None:
return SIGMA_FLOOR, 0.0
city_cal = CITY_SIGMA.get(city_code, {}).get(mtype, {})
try:
month = str(int(date_str.split("-")[1]))
except (IndexError, ValueError):
return SIGMA_FLOOR, 0.0
# Backward compatibility: older calibration files were keyed directly by month.
if month in city_cal:
month_cal = city_cal.get(month, {})
else:
hkey = str(horizon_bucket(horizon))
month_cal = (
city_cal.get(hkey, {}).get(month)
or city_cal.get("default", {}).get(month)
or {}
)
if not month_cal:
return SIGMA_FLOOR, 0.0
raw_sigma = month_cal.get("sigma", SIGMA_FLOOR)
bias = month_cal.get("bias", 0.0)
sigma = max(raw_sigma * SIGMA_INFLATION, SIGMA_MIN)
return sigma, bias
def norm_cdf(x):
"""Standard normal CDF approximation."""
return 0.5 * (1 + math.erf(x / math.sqrt(2)))
# KDE bandwidth for "between" contract probability — represents typical per-model forecast error
KDE_BANDWIDTH = 2.0 # degrees F
def model_kde_prob(model_temps, floor, cap, bandwidth=KDE_BANDWIDTH):
"""
Probability of temp falling in [floor, cap) using Kernel Density Estimation.
Places a gaussian kernel (bandwidth wide) around each model's prediction and
integrates over the bucket. This respects model clustering — if 5/7 models
predict 57-58F, the bucket gets ~70% probability instead of the ~11% that
the ensemble gaussian gives.
"""
if not model_temps:
return 0.5
total = 0
for t in model_temps:
total += norm_cdf((cap - t) / bandwidth) - norm_cdf((floor - t) / bandwidth)
return total / len(model_temps)
def load_env():
"""Load API keys from ~/AI Stuff/keys.env if not in environment."""
env_path = Path.home() / "AI Stuff" / "keys.env"
if env_path.exists():
for line in env_path.read_text().splitlines():
line = line.strip()
if "=" in line and not line.startswith("#"):
key, val = line.split("=", 1)
key = key.strip()
val = val.strip().strip('"').strip("'")
# Map keys.env names to expected env var names
mapping = {
"Openrouter": "OPENROUTER_API_KEY",
"KenPom": "KENPOM_API_KEY",
"OpenMeteo": "OPENMETEO_API_KEY",
}
env_name = mapping.get(key, key)
if env_name not in os.environ:
os.environ[env_name] = val
# ============================================================
# OPENMETEO — MULTI-MODEL FORECASTS
# ============================================================
def fetch_forecasts(cities=CITIES, models=WEATHER_MODELS, forecast_days=3):
"""
Fetch multi-model temperature forecasts for all cities.
Returns: {city_code: {date: {model: {high, low, hourly: [(hour, temp)]}}}}
"""
print("\n=== FETCHING OPENMETEO MULTI-MODEL FORECASTS ===\n")
all_forecasts = {}
city_codes = list(cities.keys())
# Batch all cities in one request (OpenMeteo supports multi-location)
lats = ",".join(str(cities[c]["lat"]) for c in city_codes)
lons = ",".join(str(cities[c]["lon"]) for c in city_codes)
model_str = ",".join(models)
params = {
"latitude": lats,
"longitude": lons,
"daily": "temperature_2m_max,temperature_2m_min",
"hourly": "temperature_2m",
"models": model_str,
"temperature_unit": "fahrenheit",
"timezone": "auto",
"forecast_days": forecast_days,
}
# Add paid API key if available
api_key = os.environ.get("OPENMETEO_API_KEY", "")
if api_key:
params["apikey"] = api_key
try:
resp = requests.get(OPENMETEO_URL, params=params, timeout=30)
resp.raise_for_status()
data = resp.json()
except Exception as e:
print(f" ERROR fetching OpenMeteo: {e}")
return {}
# Multi-location returns array
if not isinstance(data, list):
data = [data]
for i, city_code in enumerate(city_codes):
city_data = data[i] if i < len(data) else None
if not city_data:
print(f" {city_code}: no data")
continue
city_forecasts = {}
daily = city_data.get("daily", {})
hourly = city_data.get("hourly", {})
dates = daily.get("time", [])
for di, date_str in enumerate(dates):
day_models = {}
for model in models:
suffix = f"_{model}"
high_key = f"temperature_2m_max{suffix}"
low_key = f"temperature_2m_min{suffix}"
high_val = daily.get(high_key, [None] * len(dates))[di]
low_val = daily.get(low_key, [None] * len(dates))[di]
# Hourly temps for this model on this date
hourly_key = f"temperature_2m{suffix}"
hourly_temps = hourly.get(hourly_key, [])
hourly_times = hourly.get("time", [])
day_hourly = []
for hi, ht in enumerate(hourly_times):
if ht.startswith(date_str) and hi < len(hourly_temps):
temp = hourly_temps[hi]
if temp is not None:
day_hourly.append((ht, temp))
if high_val is not None:
day_models[model] = {
"high": round(high_val, 1),
"low": round(low_val, 1) if low_val else None,
"hourly": day_hourly,
}
if day_models:
city_forecasts[date_str] = day_models
all_forecasts[city_code] = city_forecasts
model_count = max(len(v) for v in city_forecasts.values()) if city_forecasts else 0
print(f" {city_code} ({cities[city_code]['name']}): {len(city_forecasts)} days, {model_count} models")
print(f"\n Total: {len(all_forecasts)} cities fetched")
return all_forecasts
# ============================================================
# ENSEMBLE — PROBABILITY DISTRIBUTION
# ============================================================
def build_ensemble(forecasts):
"""
Build ensemble statistics from multi-model forecasts.
Returns: {city: {date: {high_mean, high_std, high_models: [...], low_mean, low_std, ...}}}
"""
print("\n=== BUILDING ENSEMBLE DISTRIBUTIONS ===\n")
ensembles = {}
for city_code, city_data in forecasts.items():
city_ensemble = {}
for date_str, models in city_data.items():
highs = [m["high"] for m in models.values() if m.get("high") is not None]
lows = [m["low"] for m in models.values() if m.get("low") is not None]
if len(highs) < 2:
continue
high_mean = sum(highs) / len(highs)
high_std = max((sum((h - high_mean)**2 for h in highs) / (len(highs) - 1)) ** 0.5, SIGMA_FLOOR) if len(highs) > 1 else SIGMA_FLOOR
low_mean = sum(lows) / len(lows) if lows else None
low_std = max((sum((l - low_mean)**2 for l in lows) / (len(lows) - 1)) ** 0.5, SIGMA_FLOOR) if lows and len(lows) > 1 else SIGMA_FLOOR
# Per-model breakdown for UI
model_highs = {m: d["high"] for m, d in models.items() if d.get("high") is not None}
model_lows = {m: d["low"] for m, d in models.items() if d.get("low") is not None}
city_ensemble[date_str] = {
"high_mean": round(high_mean, 1),
"high_std": round(high_std, 2),
"high_min": round(min(highs), 1),
"high_max": round(max(highs), 1),
"high_models": model_highs,
"low_mean": round(low_mean, 1) if low_mean else None,
"low_std": round(low_std, 2) if low_std else None,
"low_models": model_lows,
"model_count": len(highs),
}
ensembles[city_code] = city_ensemble
if city_ensemble:
sample = list(city_ensemble.values())[0]
print(f" {city_code}: {sample['model_count']} models, "
f"high {sample['high_mean']}F +/- {sample['high_std']}F, "
f"spread {sample['high_min']}-{sample['high_max']}F")
return ensembles
# ============================================================
# KALSHI — WEATHER MARKETS
# ============================================================
def fetch_kalshi_markets(cities=CITIES):
"""
Fetch active Kalshi weather markets for all cities.
Returns: {city_code: {date: {type: 'high'|'low', contracts: [...]}}}
"""
print("\n=== FETCHING KALSHI WEATHER MARKETS ===\n")
all_markets = {}
series_tickers = []
# Build list of series tickers to fetch
for city_code, city in cities.items():
series_tickers.append((city_code, "high", city["high"]))
series_tickers.append((city_code, "low", city["low"]))
for city_code, market_type, series_ticker in series_tickers:
if city_code not in all_markets:
all_markets[city_code] = {}
try:
events = _kalshi_paginate_events(series_ticker)
except Exception as e:
print(f" {series_ticker}: ERROR {e}")
continue
for event in events:
# Parse date from event ticker (e.g. KXHIGHLAX-26APR08)
event_ticker = event.get("event_ticker", "")
date_str = _parse_kalshi_date(event_ticker)
if not date_str:
continue
contracts = []
for market in event.get("markets", []):
if market.get("status") != "active":
continue
yes_bid = _parse_price(market.get("yes_bid_dollars") or market.get("yes_bid"))
yes_ask = _parse_price(market.get("yes_ask_dollars") or market.get("yes_ask"))
no_bid = _parse_price(market.get("no_bid_dollars") or market.get("no_bid"))
no_ask = _parse_price(market.get("no_ask_dollars") or market.get("no_ask"))
mid = (yes_bid + yes_ask) / 2 if yes_bid is not None and yes_ask is not None else None
contracts.append({
"ticker": market.get("ticker", ""),
"title": market.get("title", ""),
"strike_type": market.get("strike_type", ""),
"floor_strike": market.get("floor_strike"),
"cap_strike": market.get("cap_strike"),
"yes_bid": yes_bid,
"yes_ask": yes_ask,
"no_bid": no_bid,
"no_ask": no_ask,
"mid": round(mid, 3) if mid else None,
"volume": _parse_price(market.get("volume_fp") or market.get("volume")),
"open_interest": _parse_price(market.get("open_interest_fp") or market.get("open_interest")),
"close_time": market.get("close_time"),
})
if contracts:
key = f"{date_str}_{market_type}"
all_markets[city_code][key] = {
"date": date_str,
"type": market_type,
"event_ticker": event_ticker,
"contracts": sorted(contracts, key=lambda c: c.get("floor_strike") or c.get("cap_strike") or 0),
}
time.sleep(0.5) # Rate limit buffer
# Summary
total_contracts = sum(
len(m["contracts"])
for city in all_markets.values()
for m in city.values()
)
total_events = sum(len(city) for city in all_markets.values())
print(f"\n Total: {total_events} events, {total_contracts} contracts across {len(all_markets)} cities")
return all_markets
def _kalshi_paginate_events(series_ticker, limit=200):
"""Paginate through Kalshi events for a series ticker."""
events = []
cursor = None
while True:
params = {
"series_ticker": series_ticker,
"status": "open",
"with_nested_markets": "true",
"limit": limit,
}
if cursor:
params["cursor"] = cursor
resp = requests.get(f"{KALSHI_BASE}/events", params=params, timeout=15)
if resp.status_code == 404:
return events
resp.raise_for_status()
data = resp.json()
events.extend(data.get("events", []))
cursor = data.get("cursor")
if not cursor or not data.get("events"):
break
time.sleep(0.3)
return events
def _parse_kalshi_date(event_ticker):
"""Parse date from event ticker like KXHIGHLAX-26APR08 -> 2026-04-08."""
parts = event_ticker.split("-")
if len(parts) < 2:
return None
date_part = parts[1] # e.g. 26APR08
try:
dt = datetime.strptime(date_part, "%y%b%d")
return dt.strftime("%Y-%m-%d")
except ValueError:
return None
def _parse_price(val):
"""Parse Kalshi price field (string or number) to float."""
if val is None:
return None
try:
return float(val)
except (ValueError, TypeError):
return None
# ============================================================
# EDGE CALCULATION
# ============================================================
def calculate_edges(ensembles, markets, pace_data=None):
"""
Compare ensemble probabilities against Kalshi market prices.
Uses horizon-based model weighting (HRRR dominant day 0, NBM/ECMWF for day 2+).
Pace data is computed upstream and surfaced in the UI, but NOT fed into edge math —
backtest showed it was 3.3x less accurate than the ensemble on day 0 highs.
Returns: [{city, date, type, contract_ticker, threshold, our_prob, market_prob, edge, signal}]
"""
print("\n=== CALCULATING EDGES ===\n")
pace_data = pace_data or {}
# Determine today's local date per city
now_utc = datetime.now(timezone.utc)
city_today = {}
for city_code, city in CITIES.items():
local_now = now_utc.astimezone(ZoneInfo(city["tz"]))
city_today[city_code] = local_now.strftime("%Y-%m-%d")
edges = []
for city_code, city_markets in markets.items():
city_ensemble = ensembles.get(city_code, {})
today = city_today.get(city_code, "")
pace = pace_data.get(city_code, {})
for key, market_data in city_markets.items():
date_str = market_data["date"]
mtype = market_data["type"] # "high" or "low"
ensemble = city_ensemble.get(date_str)
if not ensemble:
continue
# Determine forecast horizon (days ahead)
try:
from datetime import date as _date
horizon = (_date.fromisoformat(date_str) - _date.fromisoformat(today)).days
except Exception:
horizon = 1
horizon = max(0, horizon)
horizon_key = horizon_bucket(horizon)
# Get per-model temps and raw ensemble stats
model_temps = ensemble.get(f"{mtype}_models", {})
raw_std = ensemble["high_std"] if mtype == "high" else ensemble.get("low_std")
# Horizon-weighted ensemble mean.
# Pace adjustment was removed: backtest (2026-04-18) showed pace-adjusted
# mean had 3.3x worse MAE than raw ensemble (2.17F vs 0.66F) on day 0 highs,
# and went 0/7 on signals because it flipped the mean across thresholds.
# Pace is still computed and surfaced in the UI as an intraday indicator.
if model_temps:
mean = horizon_weighted_mean(model_temps, horizon)
else:
mean = ensemble["high_mean"] if mtype == "high" else ensemble.get("low_mean")
if mean is None or raw_std is None:
continue
# Apply calibration: city-specific sigma + bias correction
cal_sigma, cal_bias = get_calibration(city_code, mtype, date_str, horizon=horizon_key)
mean = mean - cal_bias # Correct systematic forecast bias
std = cal_sigma # Use calibrated sigma instead of raw model spread
for contract in market_data["contracts"]:
mid = contract.get("mid")
if mid is None:
continue
# Skip dead/settled contracts
yes_bid = contract.get("yes_bid") or 0
yes_ask = contract.get("yes_ask") or 0
spread = yes_ask - yes_bid
if spread >= 0.50: # No real market
continue
if mid <= 0.08 or mid >= 0.92: # Near-settled — market has intraday info our model lacks
continue
# Skip expired contracts
close_time_str = contract.get("close_time", "")
if close_time_str:
try:
ct = datetime.fromisoformat(close_time_str.replace("Z", "+00:00"))
if ct < datetime.now(timezone.utc):
continue
except ValueError:
pass
strike_type = contract["strike_type"]
floor = contract.get("floor_strike")
cap = contract.get("cap_strike")
# Calculate our probability for this contract
if strike_type == "less" and cap is not None:
# P(temp < cap) — gaussian CDF works well for cumulative
our_prob = norm_cdf((cap - mean) / std)
elif strike_type == "greater" and floor is not None:
# P(temp > floor) — gaussian CDF works well for cumulative
our_prob = 1 - norm_cdf((floor - mean) / std)
elif strike_type == "between" and floor is not None and cap is not None:
# P(floor <= temp < cap) — use KDE from individual models
# Gaussian mean/std is too blunt for narrow 2-degree buckets:
# with sigma=3.5, ANY bucket maxes at ~23% probability.
# KDE respects model clustering (5/7 models at 57F → high bucket prob).
models_key = f"{mtype}_models"
model_temps = list(ensemble.get(models_key, {}).values())
if model_temps:
our_prob = model_kde_prob(model_temps, floor, cap)
else:
our_prob = norm_cdf((cap - mean) / std) - norm_cdf((floor - mean) / std)
else:
continue
our_prob = round(our_prob, 4)
edge = round(our_prob - mid, 4)
# Signal: only on "less"/"greater" contracts where cumulative gaussian works.
# "Between" contracts are narrow 2-degree buckets — our model structurally
# can't price them (max ~20% for any bucket, even when models cluster there).
# Still calculate edge for display, but don't generate actionable signals.
min_edge = HIGH_EDGE_THRESHOLD if mtype == "high" else EDGE_THRESHOLD
if SUPPRESS_HIGH_SIGNALS and mtype == "high":
signal = None
elif (city_code, mtype) in SIGNAL_BLOCKLIST:
signal = None
elif strike_type != "between" and abs(edge) >= min_edge:
# Kill switch: huge disagreements with market are model failures
if abs(edge) > MAX_DISAGREEMENT:
signal = None
else:
signal = "YES" if edge > 0 else "NO"
# HIGH YES is a confirmed money-loser (5% WR historical) — suppress
if SUPPRESS_HIGH_YES and mtype == "high" and signal == "YES":
signal = None
else:
signal = None
# EV calculation (capped — if you're seeing 300%+ EV against a liquid market,
# the model is probably wrong, not the market)
if signal == "YES" and mid > 0.01:
ev = min(edge / mid, 3.0)
elif signal == "NO" and mid < 0.99:
ev = min(-edge / (1 - mid), 3.0)
else:
ev = 0
edges.append({
"city": city_code,
"city_name": CITIES[city_code]["name"],
"date": date_str,
"type": mtype,
"horizon": horizon,
"horizon_bucket": horizon_key,
"ticker": contract["ticker"],
"strike_type": strike_type,
"floor": floor,
"cap": cap,
"threshold": cap if strike_type == "less" else floor if strike_type == "greater" else f"{floor}-{cap}",
"our_prob": our_prob,
"market_mid": mid,
"yes_bid": contract["yes_bid"],
"yes_ask": contract["yes_ask"],
"spread": round(spread, 4),
"edge": edge,
"ev": round(ev, 4),
"signal": signal,
"volume": contract["volume"],
"close_time": contract["close_time"],
"calibration_sigma": round(std, 4),
"calibration_bias": round(cal_bias, 4),
"pace_used": False,
})
# Sort by absolute edge descending
edges.sort(key=lambda e: abs(e["edge"]), reverse=True)
# Summary
signals = [e for e in edges if e["signal"]]
print(f" Total contracts analyzed: {len(edges)}")
killed = len([e for e in edges
if e["strike_type"] != "between"
and (HIGH_EDGE_THRESHOLD if e["type"] == "high" else EDGE_THRESHOLD) <= abs(e["edge"])
and abs(e["edge"]) > MAX_DISAGREEMENT])
blocked = len([e for e in edges if (e["city"], e["type"]) in SIGNAL_BLOCKLIST])
suppressed_highs = len([e for e in edges
if SUPPRESS_HIGH_SIGNALS
and e["type"] == "high"
and e["signal"] is None
and abs(e["edge"]) >= HIGH_EDGE_THRESHOLD
and abs(e["edge"]) <= MAX_DISAGREEMENT
and e["strike_type"] != "between"])
suppressed_high_yes = len([e for e in edges
if SUPPRESS_HIGH_YES
and e["type"] == "high"
and e["signal"] is None
and e["edge"] > 0
and abs(e["edge"]) >= HIGH_EDGE_THRESHOLD
and abs(e["edge"]) <= MAX_DISAGREEMENT
and e["strike_type"] != "between"
and (e["city"], e["type"]) not in SIGNAL_BLOCKLIST])
print(f" Signals: {len(signals)} "
f"(low floor {EDGE_THRESHOLD*100:.0f}%, high floor {HIGH_EDGE_THRESHOLD*100:.0f}%, kill {MAX_DISAGREEMENT*100:.0f}%)")
print(f" killed {killed} over-disagreement, blocked {blocked} city/type, "
f"suppressed {suppressed_highs} highs, {suppressed_high_yes} high-YES")
if signals:
top = signals[0]
print(f" Best edge: {top['city_name']} {top['type']} {top['threshold']}F "
f"-> {top['signal']} ({top['edge']:+.1%} edge, {top['ev']:+.1%} EV)")
return edges
# ============================================================
# NWS OBSERVATIONS — CURRENT TEMPS (for pace tracking)
# ============================================================
def fetch_observations(cities=CITIES):
"""
Fetch current temperature observations from NWS for pace tracking.
Returns: {city_code: {temp_f, observed_at, station}}
"""
print("\n=== FETCHING NWS OBSERVATIONS ===\n")
# NWS station IDs for our cities (airport weather stations)
NWS_STATIONS = {
"NYC": "KNYC", "LAX": "KLAX", "CHI": "KMDW",
"MIA": "KMIA", "DAL": "KDFW", "DEN": "KDEN",
"PHI": "KPHL", "ATL": "KATL", "HOU": "KIAH",
"PHX": "KPHX",
}
observations = {}
for city_code, station_id in NWS_STATIONS.items():
try:
url = f"https://api.weather.gov/stations/{station_id}/observations/latest"
resp = requests.get(url, headers={"User-Agent": "WeatherEdge/1.0"}, timeout=10)
if resp.status_code != 200:
print(f" {city_code} ({station_id}): HTTP {resp.status_code}")
continue
data = resp.json()
props = data.get("properties", {})
temp_c = props.get("temperature", {}).get("value")
if temp_c is not None:
temp_f = round(temp_c * 9/5 + 32, 1)
observed_at = props.get("timestamp", "")
# Track observation age so frontend can flag stale readings
obs_age_min = None
if observed_at:
try:
obs_time = datetime.fromisoformat(observed_at.replace("Z", "+00:00"))
obs_age_min = round((datetime.now(timezone.utc) - obs_time).total_seconds() / 60)
except ValueError:
pass
observations[city_code] = {
"temp_f": temp_f,
"observed_at": observed_at,
"station": station_id,
"obs_age_min": obs_age_min,
}
age_str = f", {obs_age_min}min ago" if obs_age_min else ""
print(f" {city_code}: {temp_f}F ({station_id}{age_str})")
else:
print(f" {city_code}: null temperature")
except Exception as e:
print(f" {city_code}: ERROR {e}")
time.sleep(0.2)
print(f"\n Got observations for {len(observations)}/{len(NWS_STATIONS)} cities")
return observations
# ============================================================
# PACE TRACKING — INTRADAY TEMPERATURE ADJUSTMENT
# ============================================================
def calculate_pace(forecasts, observations):
"""
Compare current observed temps against HRRR hourly curve to detect
whether reality is running ahead/behind forecast.
Returns: {city_code: {pace_delta, expected_now, observed, adjusted_high}}
"""
print("\n=== CALCULATING TEMPERATURE PACE ===\n")
now_utc = datetime.now(timezone.utc)
pace_data = {}
for city_code, obs in observations.items():
city_tz = CITIES.get(city_code, {}).get("tz", "America/New_York")
local_now = now_utc.astimezone(ZoneInfo(city_tz))
today_str = local_now.strftime("%Y-%m-%d")
city_forecasts = forecasts.get(city_code, {}).get(today_str, {})
hrrr = city_forecasts.get("ncep_hrrr_conus")
if not hrrr or not hrrr.get("hourly"):
continue
# Match against HRRR hourly using LOCAL time (OpenMeteo returns local times)
local_hour = local_now.strftime("%Y-%m-%dT%H")
expected_now = None
for ht, temp in hrrr["hourly"]:
if ht.startswith(local_hour):
expected_now = temp
break
if expected_now is None:
continue
pace_delta = round(obs["temp_f"] - expected_now, 1)
adjusted_high = round(hrrr["high"] + pace_delta, 1)
pace_data[city_code] = {
"pace_delta": pace_delta,
"expected_now": round(expected_now, 1),
"observed": obs["temp_f"],
"hrrr_high": hrrr["high"],
"adjusted_high": adjusted_high,
}
direction = "AHEAD" if pace_delta > 0 else "BEHIND" if pace_delta < 0 else "ON PACE"
print(f" {city_code}: {obs['temp_f']}F observed vs {expected_now:.1f}F expected "
f"-> {pace_delta:+.1f}F {direction} (adj high: {adjusted_high}F)")
return pace_data
# ============================================================
# AI ANALYSIS (Claude + GPT via OpenRouter)
# ============================================================
def ai_analysis(edges, ensembles, pace_data, observations):
"""
Get Claude and GPT to independently analyze the top edges.
Returns: {model_name: {summary, picks: [...]}}
"""
api_key = os.environ.get("OPENROUTER_API_KEY", "")
if not api_key:
print("\n [--] OPENROUTER_API_KEY not set — skipping AI analysis")
return {}
print("\n=== AI WEATHER ANALYSIS ===\n")
# Build context for AI
top_edges = [e for e in edges if e["signal"]][:15]
if not top_edges:
print(" No signals to analyze")
return {}
# Format the data concisely
edge_lines = []
for e in top_edges:
pace = pace_data.get(e["city"], {})
pace_str = f" (pace: {pace['pace_delta']:+.1f}F)" if pace else ""
edge_lines.append(
f" {e['city_name']} {e['type']} {e['threshold']}F: "
f"our={e['our_prob']:.0%} vs market={e['market_mid']:.0%} "
f"-> {e['signal']} ({e['edge']:+.1%} edge, {e['ev']:+.1%} EV){pace_str}"
)
ensemble_lines = []
for city_code, city_data in ensembles.items():
for date, ens in city_data.items():
obs = observations.get(city_code, {})
obs_str = f", current: {obs['temp_f']}F" if obs else ""
ensemble_lines.append(
f" {CITIES[city_code]['name']} {date}: "
f"high {ens['high_mean']}F +/-{ens['high_std']}F "
f"(range: {ens['high_min']}-{ens['high_max']}F, {ens['model_count']} models{obs_str})"
)
prompt = f"""You are a weather market analyst. You have ensemble weather forecasts from 7 models
and Kalshi market prices. Analyze the top edges and give your independent assessment.
ENSEMBLE FORECASTS:
{chr(10).join(ensemble_lines)}
TOP EDGES DETECTED:
{chr(10).join(edge_lines)}
For each edge, assess:
1. Is the ensemble signal trustworthy here? (model agreement, forecast horizon, city-specific factors)
2. Any weather patterns that could shift the outcome? (fronts, urban heat islands, coastal effects)
3. Your confidence: STRONG / LEAN / SKIP
Respond in JSON format:
{{
"summary": "1-2 sentence overall market take",
"picks": [
{{
"city": "NYC",
"type": "high",
"threshold": "72",
"signal": "YES",
"confidence": "STRONG",
"reasoning": "brief reason"
}}
]
}}"""
models = [
("claude", "anthropic/claude-sonnet-4-6"),
("gpt", "openai/gpt-4.1-mini"),
]
results = {}
for model_name, model_id in models:
try:
resp = requests.post(
"https://openrouter.ai/api/v1/chat/completions",
headers={
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json",
},
json={
"model": model_id,
"messages": [{"role": "user", "content": prompt}],
"temperature": 0.3,
"max_tokens": 1500,
"response_format": {"type": "json_object"},
},
timeout=60,
)
resp.raise_for_status()
content = resp.json()["choices"][0]["message"]["content"]
# Multi-stage JSON parsing
content = content.strip()
if content.startswith("```"):
content = content.split("\n", 1)[1].rsplit("```", 1)[0].strip()
parsed = None
# Stage 1: direct parse
try:
parsed = json.loads(content)
except json.JSONDecodeError:
pass
# Stage 2: find first { to last }
if not parsed:
try:
start = content.index("{")
end = content.rindex("}") + 1
parsed = json.loads(content[start:end])
except (ValueError, json.JSONDecodeError):
pass
if parsed:
results[model_name] = parsed
pick_count = len(parsed.get("picks", []))
print(f" {model_name}: {pick_count} picks — {parsed.get('summary', '')[:80]}")
else:
print(f" {model_name}: got response but failed to parse JSON")
results[model_name] = {"summary": content[:300], "picks": []}
except Exception as e:
print(f" {model_name}: ERROR {e}")
return results
# ============================================================
# HISTORICAL DATA — SIGNAL RECORDING & RESOLUTION
# ============================================================
DATA_DIR = Path(__file__).parent / "data"
def load_jsonl(path):
"""Load JSONL rows, skipping malformed lines."""
if not path.exists():
return []
rows = []
for line in path.read_text(encoding="utf-8").splitlines():
if not line.strip():
continue
try:
rows.append(json.loads(line))
except json.JSONDecodeError:
continue
return rows
def record_contract_snapshots(edges, ensembles, pace_data):
"""
Append every evaluated contract to data/contract_snapshots.jsonl.
Deduplicates by ticker within the last hour to keep the file informative
without exploding on every refresh.
"""
print("\n=== RECORDING CONTRACT SNAPSHOTS ===\n")
DATA_DIR.mkdir(exist_ok=True)
snapshots_file = DATA_DIR / "contract_snapshots.jsonl"
timestamp = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
if not edges:
print(" No contracts to record")
return
recent_tickers = set()
if snapshots_file.exists():
cutoff = datetime.now(timezone.utc) - timedelta(hours=1)
for line in snapshots_file.read_text(encoding="utf-8").splitlines():
try:
rec = json.loads(line)