-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
2568 lines (2236 loc) · 102 KB
/
Copy pathapp.py
File metadata and controls
2568 lines (2236 loc) · 102 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
from flask import Flask, jsonify, render_template, request, send_file
from functools import wraps
import random
import math
from functools import lru_cache
import bisect
import re
import hashlib
import hmac
from datetime import datetime, timedelta, timezone
import requests
import json
import os
import time as _time
import shutil
import gzip
app = Flask(__name__)
app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 86400 # Cache static files for 1 day (safe due to ?v= cache-buster)
from performance import init_performance
init_performance(app)
@app.url_defaults
def _append_static_version(endpoint, values):
"""Append a ?v=<mtime> cache-buster to every url_for('static', ...) call
so browsers automatically pick up changed CSS/JS without a hard refresh."""
if endpoint != 'static':
return
filename = values.get('filename')
if not filename or 'v' in values:
return
try:
filepath = os.path.join(app.static_folder, filename)
values['v'] = int(os.path.getmtime(filepath))
except OSError:
pass
@app.after_request
def _no_cache_html(response):
"""Prevent browsers from serving stale HTML pages. Static assets and JSON
APIs keep their own cache headers; only text/html gets forced revalidation."""
if response.mimetype == 'text/html' and 'Cache-Control' not in response.headers:
response.headers['Cache-Control'] = 'no-cache, must-revalidate, max-age=0'
response.headers['Pragma'] = 'no-cache'
response.headers['Expires'] = '0'
return response
# ===== PATH RESOLUTION =====
def resolve_data_path(filename='historical_snapshots.jsonl'):
"""
Resolve the correct data directory, checking for actual data files.
Checks for both plain and .gz versions of the file.
Priority: DATA_DIR env var -> /app/data/ -> /data/ -> local data/
"""
configured_dir = os.environ.get('DATA_DIR', '').strip()
if configured_dir:
return os.path.join(configured_dir, filename)
# Check all candidate dirs for actual data (plain or gzipped)
local_data = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'data')
for candidate_dir in ['/app/data', '/data', local_data]:
candidate_path = os.path.join(candidate_dir, filename)
gz_path = candidate_path + '.gz'
if os.path.exists(gz_path) or os.path.exists(candidate_path):
return candidate_path
# Fallback to local data/ directory
return os.path.join(local_data, filename)
# Path to historical data storage (JSONL format - JSON Lines)
HISTORICAL_DATA_PATH = resolve_data_path('historical_snapshots.jsonl')
# Seed data path - git-tracked backup that Railway will use to initialize the volume
SEED_DATA_PATH = os.path.join(os.path.dirname(__file__), 'data', 'seed_snapshots.json')
# Legacy JSON path for migration
LEGACY_JSON_PATH = os.path.join(os.path.dirname(__file__), 'data', 'historical_snapshots.json')
REPO_CSV_PATH = os.path.join(os.path.dirname(__file__), 'il9cast_historical_data.csv')
# ===== EMAIL ALERT CONFIGURATION =====
SUBSCRIBERS_PATH = resolve_data_path('email_subscribers.jsonl')
RESEND_API_KEY = os.environ.get('RESEND_API_KEY')
RESEND_FROM_EMAIL = os.environ.get('RESEND_FROM_EMAIL', 'alerts@il9.org')
RESEND_FROM = f"IL9Cast <{RESEND_FROM_EMAIL}>" # Display name + email
EMAIL_SECRET_SALT = os.environ.get('EMAIL_SECRET_SALT')
if not EMAIL_SECRET_SALT:
import warnings
warnings.warn('EMAIL_SECRET_SALT is not set! Email tokens will be insecure.', stacklevel=1)
EMAIL_SECRET_SALT = 'il9cast-change-me'
# Admin API authentication token (must be set in production)
ADMIN_API_TOKEN = os.environ.get('ADMIN_API_TOKEN')
SITE_BASE_URL = os.environ.get('SITE_BASE_URL', 'https://il9.org/')
# ===== JSONL HELPER FUNCTIONS =====
def _acquire_file_lock(lock_path):
"""Acquire an exclusive inter-process file lock and return the lock file handle."""
import fcntl
lock_file = open(lock_path, 'a+')
fcntl.flock(lock_file.fileno(), fcntl.LOCK_EX)
return lock_file
def _release_file_lock(lock_file):
"""Release an inter-process file lock."""
import fcntl
try:
fcntl.flock(lock_file.fileno(), fcntl.LOCK_UN)
finally:
lock_file.close()
def backup_file(filepath, reason='manual'):
"""Create a timestamped backup copy of filepath if it exists."""
if not os.path.exists(filepath):
return None
ts = datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%SZ')
backup_path = f"{filepath}.backup.{reason}.{ts}"
shutil.copy2(filepath, backup_path)
print(f"[{datetime.now().isoformat()}] Backup created: {backup_path}")
return backup_path
def _parse_bool(value):
"""Parse common truthy/falsy values to bool."""
if isinstance(value, bool):
return value
if value is None:
return False
return str(value).strip().lower() in {'1', 'true', 'yes', 'y'}
def _safe_float(value, default=0.0):
"""Best-effort numeric coercion for probabilities coming from mixed data sources."""
try:
return float(value)
except (TypeError, ValueError):
return default
def load_snapshots_from_csv(csv_path):
"""Load wide historical CSV (timestamp,candidate,probability,hasKalshi[,interpolated]) into snapshot JSON objects."""
import csv
if not os.path.exists(csv_path):
raise FileNotFoundError(f"CSV not found: {csv_path}")
grouped = {}
interpolated_flags = {}
with open(csv_path, 'r', newline='') as f:
reader = csv.DictReader(f)
for row in reader:
ts = (row.get('timestamp') or '').strip()
name = (row.get('candidate') or '').strip()
if not ts or not name:
continue
try:
prob = float(row.get('probability', 0) or 0)
except (TypeError, ValueError):
prob = 0.0
grouped.setdefault(ts, []).append({
'name': name,
'probability': prob,
'hasKalshi': _parse_bool(row.get('hasKalshi'))
})
if _parse_bool(row.get('interpolated')):
interpolated_flags[ts] = True
snapshots = []
for ts, candidates in grouped.items():
snap = {'timestamp': ts, 'candidates': candidates}
if interpolated_flags.get(ts):
snap['interpolated'] = True
snapshots.append(snap)
snapshots.sort(key=lambda s: parse_snapshot_timestamp(s.get('timestamp')) or datetime.min.replace(tzinfo=timezone.utc))
return snapshots
def _interpolate_snapshots(start_snapshot, end_snapshot, step_count, add_noise=False):
"""Linearly interpolate snapshots between two timestamped snapshots (exclusive endpoints).
If add_noise=True, adds small random-walk fluctuations around the trend line
to make interpolated data look like natural market movement. Each snapshot is
also flagged with 'interpolated': True.
"""
if step_count <= 0:
return []
start_dt = parse_snapshot_timestamp(start_snapshot.get('timestamp'))
end_dt = parse_snapshot_timestamp(end_snapshot.get('timestamp'))
if not start_dt or not end_dt or end_dt <= start_dt:
return []
start_map = {c.get('name'): c for c in start_snapshot.get('candidates', [])}
end_map = {c.get('name'): c for c in end_snapshot.get('candidates', [])}
names = sorted(set(start_map.keys()) | set(end_map.keys()))
# For noise: track per-candidate random walk offset
noise_state = {name: 0.0 for name in names}
# Use a seeded RNG so interpolated data is deterministic for same inputs
rng = random.Random(hash(str(start_snapshot.get('timestamp', '')) + str(end_snapshot.get('timestamp', ''))))
out = []
total_seconds = (end_dt - start_dt).total_seconds()
for step in range(1, step_count + 1):
ratio = step / (step_count + 1)
ts = start_dt + timedelta(seconds=total_seconds * ratio)
candidates = []
for name in names:
start_prob = float(start_map.get(name, {}).get('probability', 0) or 0)
end_prob = float(end_map.get(name, {}).get('probability', 0) or 0)
interp_prob = start_prob + ((end_prob - start_prob) * ratio)
if add_noise and step_count > 2:
# Random walk with mean-reversion toward the trend line
# Noise magnitude scales with candidate's probability level
magnitude = max(0.05, min(0.4, interp_prob * 0.006))
noise_state[name] += rng.gauss(0, magnitude)
# Mean-revert: pull noise back toward zero
noise_state[name] *= 0.92
# Dampen noise near endpoints so it connects smoothly
edge_dampen = min(ratio, 1.0 - ratio) * 4.0
edge_dampen = min(1.0, edge_dampen)
interp_prob += noise_state[name] * edge_dampen
# Clamp to valid range
interp_prob = max(0.0, min(100.0, interp_prob))
has_kalshi = bool(start_map.get(name, {}).get('hasKalshi', False) or end_map.get(name, {}).get('hasKalshi', False))
candidates.append({
'name': name,
'probability': round(interp_prob, 1),
'hasKalshi': has_kalshi
})
snap = {
'timestamp': ts.isoformat().replace('+00:00', 'Z'),
'candidates': candidates
}
if add_noise:
snap['interpolated'] = True
out.append(snap)
return out
def bridge_to_present(filepath, interval_minutes=3, max_bridge_hours=72):
"""Append flat-interpolated snapshots from the last snapshot in the file up to now.
Uses the last snapshot's values as both start and end so the bridge is a flat line.
Returns a stats dict.
"""
snapshots = read_snapshots_jsonl(filepath)
if not snapshots:
return {'bridged': False, 'reason': 'no_data'}
last = snapshots[-1]
last_dt = parse_snapshot_timestamp(last.get('timestamp'))
now = datetime.now(timezone.utc)
if not last_dt:
return {'bridged': False, 'reason': 'no_timestamp'}
gap_seconds = (now - last_dt).total_seconds()
gap_hours = gap_seconds / 3600.0
if gap_seconds <= interval_minutes * 60:
return {'bridged': False, 'reason': 'no_gap', 'gap_hours': round(gap_hours, 2)}
if gap_hours > max_bridge_hours:
return {'bridged': False, 'reason': 'gap_too_large', 'gap_hours': round(gap_hours, 2)}
# Create a "now" endpoint with same values (flat bridge)
end_snapshot = {
'candidates': last.get('candidates', []),
'timestamp': now.isoformat().replace('+00:00', 'Z')
}
step_count = int(gap_seconds // (interval_minutes * 60)) - 1
step_count = max(0, min(step_count, 5000))
bridge = _interpolate_snapshots(last, end_snapshot, step_count, add_noise=True)
if not bridge:
return {'bridged': False, 'reason': 'no_bridge_steps'}
# Bulk append bridge snapshots with a single lock acquire
lock_path = filepath + '.lock'
lock_file = _acquire_file_lock(lock_path)
try:
with open(filepath, 'a') as f:
for snap in bridge:
f.write(json.dumps(snap, separators=(',', ':')) + '\n')
f.flush()
os.fsync(f.fileno())
finally:
_release_file_lock(lock_file)
return {
'bridged': True,
'snapshots_added': len(bridge),
'gap_hours': round(gap_hours, 2),
'from': last.get('timestamp'),
'to': end_snapshot['timestamp']
}
def recover_snapshots_from_csv_and_current(csv_path, current_path, output_path, bridge_interval_minutes=3, max_bridge_hours=72, dry_run=True, csv_only=False):
"""Rebuild timeline by stitching CSV history with current JSONL snapshots and optional interpolation bridge."""
csv_snapshots = load_snapshots_from_csv(csv_path)
current_snapshots = read_snapshots_jsonl(current_path)
if not csv_snapshots:
raise ValueError('No snapshots found in CSV source')
if not csv_only and not current_snapshots:
raise ValueError('No snapshots found in current JSONL source')
current_snapshots = [s for s in current_snapshots if parse_snapshot_timestamp(s.get('timestamp'))]
csv_snapshots = [s for s in csv_snapshots if parse_snapshot_timestamp(s.get('timestamp'))]
current_snapshots.sort(key=lambda s: parse_snapshot_timestamp(s.get('timestamp')))
csv_snapshots.sort(key=lambda s: parse_snapshot_timestamp(s.get('timestamp')))
if csv_only:
merged = []
seen = set()
for snap in csv_snapshots:
ts = snap.get('timestamp')
if not ts or ts in seen:
continue
seen.add(ts)
merged.append(snap)
else:
# CSV is authoritative for its time range. Within [csv_min, csv_max],
# use ONLY CSV data. Outside that range, keep current JSONL data.
# This cleanly replaces any bridge/interpolated/stale data without
# relying on an 'interpolated' flag that may have been lost.
csv_dts = [parse_snapshot_timestamp(s.get('timestamp')) for s in csv_snapshots
if parse_snapshot_timestamp(s.get('timestamp'))]
csv_min_dt = min(csv_dts) if csv_dts else None
csv_max_dt = max(csv_dts) if csv_dts else None
by_ts = {}
# First: add all CSV data (authoritative for its range)
for snap in csv_snapshots:
ts = snap.get('timestamp')
if ts:
by_ts[ts] = snap
# Second: add current JSONL data ONLY for timestamps outside CSV range
for snap in current_snapshots:
ts = snap.get('timestamp')
if not ts:
continue
snap_dt = parse_snapshot_timestamp(ts)
if not snap_dt:
continue
if csv_min_dt and csv_max_dt and csv_min_dt <= snap_dt <= csv_max_dt:
# Within CSV range: only keep if CSV already has this exact timestamp
# (CSV version is already in by_ts, don't overwrite it)
if ts not in by_ts:
continue # drop non-CSV data within CSV range
else:
# Outside CSV range: keep current data
by_ts[ts] = snap
merged = sorted(by_ts.values(), key=lambda s: parse_snapshot_timestamp(s.get('timestamp')))
# Bridge the gap between CSV end and first post-CSV current data
if merged and csv_max_dt:
# Find first snapshot after CSV range
first_post_csv = None
for snap in merged:
snap_dt = parse_snapshot_timestamp(snap.get('timestamp'))
if snap_dt and snap_dt > csv_max_dt:
first_post_csv = snap
first_post_csv_dt = snap_dt
break
# Find last CSV snapshot
last_csv_snap = None
for snap in reversed(merged):
snap_dt = parse_snapshot_timestamp(snap.get('timestamp'))
if snap_dt and snap_dt <= csv_max_dt:
last_csv_snap = snap
break
if last_csv_snap and first_post_csv:
last_csv_dt = parse_snapshot_timestamp(last_csv_snap.get('timestamp'))
gap_hours = (first_post_csv_dt - last_csv_dt).total_seconds() / 3600.0
if gap_hours > 0 and gap_hours <= max_bridge_hours:
step_count = int((first_post_csv_dt - last_csv_dt).total_seconds() // (bridge_interval_minutes * 60)) - 1
step_count = max(0, min(step_count, 5000))
bridge = _interpolate_snapshots(last_csv_snap, first_post_csv, step_count, add_noise=True)
for snap in bridge:
ts = snap.get('timestamp')
if ts and ts not in by_ts:
by_ts[ts] = snap
merged = sorted(by_ts.values(), key=lambda s: parse_snapshot_timestamp(s.get('timestamp')))
stats = {
'csv_snapshots': len(csv_snapshots),
'current_snapshots': len(current_snapshots),
'merged_total': len(merged),
'first_timestamp': merged[0]['timestamp'] if merged else None,
'last_timestamp': merged[-1]['timestamp'] if merged else None,
'dry_run': dry_run
}
if dry_run:
return stats
lock_path = output_path + '.lock'
lock_file = _acquire_file_lock(lock_path)
temp_path = output_path + '.recover_tmp'
try:
backup_path = backup_file(output_path, reason='recovery')
with open(temp_path, 'w') as f:
for snap in merged:
f.write(json.dumps(snap, separators=(',', ':')) + '\n')
os.replace(temp_path, output_path)
stats['backup_path'] = backup_path
finally:
if os.path.exists(temp_path):
try:
os.remove(temp_path)
except OSError:
pass
_release_file_lock(lock_file)
return stats
def read_snapshots_jsonl(filepath):
"""
Read snapshots from JSONL file (plain or gzipped).
Each line is a separate JSON object.
Returns list of snapshot dictionaries.
"""
snapshots = []
# Try gzipped version first, then plain
gz_path = filepath + '.gz'
if os.path.exists(gz_path):
actual_path = gz_path
opener = lambda p: gzip.open(p, 'rt', encoding='utf-8')
elif os.path.exists(filepath):
actual_path = filepath
opener = lambda p: open(p, 'r')
else:
return snapshots
try:
with opener(actual_path) as f:
for line_num, line in enumerate(f, 1):
line = line.strip()
if not line:
continue
if '\x00' in line:
preview = line[:120]
print(
f"[{datetime.now().isoformat()}] Corrupt NUL bytes at line {line_num}. "
f"Skipping malformed JSONL row (preview={preview!r})"
)
continue
try:
snapshot = json.loads(line)
snapshots.append(snapshot)
except json.JSONDecodeError as e:
preview = line[:120]
print(
f"[{datetime.now().isoformat()}] Error parsing line {line_num}: {e}. "
f"Skipping malformed JSONL row (preview={preview!r})"
)
continue
except (IOError, OSError) as e:
print(f"[{datetime.now().isoformat()}] Error reading JSONL file: {e}")
return snapshots
def repair_snapshots_jsonl(filepath):
"""
Remove malformed JSONL lines from snapshots file.
Returns dict with total/kept/removed counts and optional backup_path.
"""
stats = {'total': 0, 'kept': 0, 'removed': 0, 'backup_path': None}
if not os.path.exists(filepath):
return stats
temp_path = filepath + '.repair.tmp'
lock_path = filepath + '.lock'
lock_file = None
try:
lock_file = _acquire_file_lock(lock_path)
with open(filepath, 'r') as src, open(temp_path, 'w') as dst:
for line in src:
stripped = line.strip()
if not stripped:
continue
stats['total'] += 1
if '\x00' in stripped:
stats['removed'] += 1
continue
try:
json.loads(stripped)
dst.write(stripped + '\n')
stats['kept'] += 1
except json.JSONDecodeError:
stats['removed'] += 1
if stats['removed'] > 0:
backup_path = filepath + f".backup.{datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%SZ')}"
shutil.copy2(filepath, backup_path)
stats['backup_path'] = backup_path
os.replace(temp_path, filepath)
print(
f"[{datetime.now().isoformat()}] Repaired JSONL snapshots: "
f"removed {stats['removed']} malformed line(s), kept {stats['kept']}, "
f"backup saved to {backup_path}"
)
elif os.path.exists(temp_path):
os.remove(temp_path)
except (IOError, OSError) as e:
if os.path.exists(temp_path):
try:
os.remove(temp_path)
except OSError:
pass
print(f"[{datetime.now().isoformat()}] Error repairing JSONL file: {e}")
finally:
if lock_file is not None:
_release_file_lock(lock_file)
return stats
def _open_jsonl(filepath):
"""Open a JSONL file, preferring .gz version if it exists."""
gz_path = filepath + '.gz'
if os.path.exists(gz_path):
return gzip.open(gz_path, 'rt', encoding='utf-8')
elif os.path.exists(filepath):
return open(filepath, 'r')
return None
def count_snapshots_jsonl(filepath):
"""Count total valid snapshots in JSONL file without loading all into memory"""
f = _open_jsonl(filepath)
if f is None:
return 0
count = 0
with f:
for line in f:
stripped = line.strip()
if stripped and '\x00' not in stripped:
count += 1
return count
def count_data_points_jsonl(filepath):
"""Count total data points (candidates across all snapshots) in JSONL file"""
f = _open_jsonl(filepath)
if f is None:
return 0
total_data_points = 0
with f:
for line in f:
line = line.strip()
if line:
try:
snapshot = json.loads(line)
candidates = snapshot.get('candidates', [])
total_data_points += len(candidates)
except:
pass # Skip malformed lines
return total_data_points
# ===== TIMESTAMP PARSING =====
@lru_cache(maxsize=100000)
def parse_snapshot_timestamp(ts_str):
"""Parse ISO timestamp to UTC datetime. Cached for chart hot path."""
if not ts_str:
return None
try:
s = ts_str.replace('Z', '+00:00') if ts_str.endswith('Z') else ts_str
dt = datetime.fromisoformat(s)
if dt.tzinfo is None:
dt = dt.replace(tzinfo=timezone.utc)
return dt.astimezone(timezone.utc)
except (ValueError, TypeError):
return None
# ===== RAMER-DOUGLAS-PEUCKER SIMPLIFICATION =====
def _perpendicular_distance(point, line_start, line_end):
"""Calculate perpendicular distance from a point to a line segment."""
dx = line_end[0] - line_start[0]
dy = line_end[1] - line_start[1]
if dx == 0 and dy == 0:
return math.sqrt((point[0] - line_start[0]) ** 2 + (point[1] - line_start[1]) ** 2)
t = ((point[0] - line_start[0]) * dx + (point[1] - line_start[1]) * dy) / (dx * dx + dy * dy)
t = max(0, min(1, t))
proj_x = line_start[0] + t * dx
proj_y = line_start[1] + t * dy
return math.sqrt((point[0] - proj_x) ** 2 + (point[1] - proj_y) ** 2)
def rdp_simplify(points, epsilon):
"""
Ramer-Douglas-Peucker polyline simplification.
points: list of (x, y) tuples where x is normalized time (0-100), y is probability (0-100).
Returns list of indices to keep.
"""
if len(points) <= 2:
return list(range(len(points)))
# Find the point with the maximum distance from the line between first and last
max_dist = 0
max_idx = 0
for i in range(1, len(points) - 1):
d = _perpendicular_distance(points[i], points[0], points[-1])
if d > max_dist:
max_dist = d
max_idx = i
if max_dist > epsilon:
# Recurse on both halves
left = rdp_simplify(points[:max_idx + 1], epsilon)
right = rdp_simplify(points[max_idx:], epsilon)
# Combine, avoiding duplicate at split point
right_shifted = [max_idx + idx for idx in right]
return left[:-1] + right_shifted
else:
return [0, len(points) - 1]
# ===== CHART DATA CACHE =====
# Multi-slot cache: one entry per period:epsilon key.
# Invalidated only when file size changes (new snapshot appended).
# Pre-warmed after each data collection cycle so users always hit cache.
# Thundering-herd protection: per-key locks ensure only one thread computes
# a given cache entry while others wait for the result.
import threading as _threading
_chart_cache = {} # key -> {'data': ..., 'time': ..., 'file_size': ..., 'etag': ...}
_chart_cache_lock = _threading.Lock() # guards _chart_cache dict access
_chart_compute_locks = {} # key -> Lock, prevents duplicate computation
_chart_compute_locks_lock = _threading.Lock() # guards _chart_compute_locks dict
_jsonl_lines_cache = {'size': None, 'lines': None, 'ts_index': None}
_jsonl_lines_lock = _threading.Lock()
def _jsonl_data_size():
"""Byte size of the active snapshots file (gz preferred)."""
gz_path = HISTORICAL_DATA_PATH + '.gz'
try:
if os.path.exists(gz_path):
return os.path.getsize(gz_path)
if os.path.exists(HISTORICAL_DATA_PATH):
return os.path.getsize(HISTORICAL_DATA_PATH)
except OSError:
pass
return 0
_TS_RE = re.compile(r'"timestamp":\s*"([^"]+)"')
def get_jsonl_raw_lines():
"""Return all JSONL lines, cached until the underlying file grows."""
size = _jsonl_data_size()
with _jsonl_lines_lock:
if _jsonl_lines_cache['size'] == size and _jsonl_lines_cache['lines'] is not None:
return _jsonl_lines_cache['lines']
lines = []
ts_index = []
try:
f = _open_jsonl(HISTORICAL_DATA_PATH)
if f is None:
return []
with f:
for i, line in enumerate(f):
s = line.strip()
if not s:
continue
lines.append(s)
m = _TS_RE.search(s)
if m:
dt = parse_snapshot_timestamp(m.group(1))
if dt:
ts_index.append((dt.timestamp(), i))
except (IOError, OSError):
return []
with _jsonl_lines_lock:
_jsonl_lines_cache['size'] = size
_jsonl_lines_cache['lines'] = lines
_jsonl_lines_cache['ts_index'] = ts_index
return lines
def get_jsonl_ts_index():
"""Epoch timestamp + line index pairs for fast period windows."""
get_jsonl_raw_lines()
with _jsonl_lines_lock:
return _jsonl_lines_cache.get('ts_index') or []
def _chart_etag_key(file_size, period, epsilon):
"""Stable ETag for frozen archive data without serializing full payload."""
return hashlib.md5(f"{file_size}:{period}:{epsilon:.2f}".encode()).hexdigest()[:16]
def _get_compute_lock(cache_key):
"""Get or create a per-key lock for thundering-herd protection."""
with _chart_compute_locks_lock:
if cache_key not in _chart_compute_locks:
_chart_compute_locks[cache_key] = _threading.Lock()
return _chart_compute_locks[cache_key]
# ===== EMAIL ALERT FUNCTIONS =====
def read_subscribers():
"""Read subscriber list from JSONL file. Returns list of {email, subscribed_at}."""
subscribers = []
if not os.path.exists(SUBSCRIBERS_PATH):
return subscribers
try:
with open(SUBSCRIBERS_PATH, 'r') as f:
for line in f:
line = line.strip()
if not line:
continue
try:
subscribers.append(json.loads(line))
except json.JSONDecodeError:
continue
except (IOError, OSError):
pass
return subscribers
def remove_subscriber(email):
"""Remove a subscriber by rewriting JSONL without that email."""
email = email.lower().strip()
if not os.path.exists(SUBSCRIBERS_PATH):
return False
kept = []
found = False
with open(SUBSCRIBERS_PATH, 'r') as f:
for line in f:
line = line.strip()
if not line:
continue
try:
record = json.loads(line)
if record.get('email') == email:
found = True
continue
kept.append(line)
except json.JSONDecodeError:
kept.append(line)
if found:
with open(SUBSCRIBERS_PATH, 'w') as f:
for line in kept:
f.write(line + '\n')
return found
def make_unsub_token(email):
"""Generate unsubscribe token: sha256(email:salt)[:16]"""
return hashlib.sha256(f"{email.lower().strip()}:{EMAIL_SECRET_SALT}".encode()).hexdigest()[:16]
def verify_unsub_token(email, token):
"""Verify an unsubscribe token matches."""
return make_unsub_token(email) == token
def send_email(to, subject, html, text=None):
"""Send email via Resend API. Returns True on success."""
if not RESEND_API_KEY:
print(f"[{datetime.now().isoformat()}] Email skipped (no RESEND_API_KEY): {subject} -> {to}")
return False
try:
payload = {
'from': RESEND_FROM,
'to': [to],
'subject': subject,
'html': html
}
if text:
payload['text'] = text
resp = requests.post(
'https://api.resend.com/emails',
headers={
'Authorization': f'Bearer {RESEND_API_KEY}',
'Content-Type': 'application/json'
},
json=payload,
timeout=10
)
if resp.status_code in (200, 201):
print(f"[{datetime.now().isoformat()}] Email sent: {subject} -> {to}")
return True
else:
print(f"[{datetime.now().isoformat()}] Email failed ({resp.status_code}): {resp.text}")
return False
except Exception as e:
print(f"[{datetime.now().isoformat()}] Email error: {e}")
return False
BACKUP_EMAIL = os.environ.get('BACKUP_EMAIL', 'rymccomb1@icloud.com')
def send_csv_backup_email():
"""Send CSV backup of all historical data via Resend with attachment."""
import io, csv, base64
try:
snapshots = read_snapshots_jsonl(HISTORICAL_DATA_PATH)
if not snapshots:
print(f"[{datetime.now().isoformat()}] CSV backup skipped: no data")
return False
# Build CSV
output = io.StringIO()
writer = csv.writer(output)
writer.writerow(['timestamp', 'candidate', 'probability', 'hasKalshi', 'interpolated'])
for snapshot in snapshots:
timestamp = snapshot.get('timestamp', '')
is_interpolated = 'true' if snapshot.get('interpolated', False) else 'false'
for candidate in snapshot.get('candidates', []):
name = candidate.get('name', '')
prob = _safe_float(candidate.get('probability', 0), 0.0)
has_kalshi = 'true' if candidate.get('hasKalshi', False) else 'false'
writer.writerow([timestamp, name, f'{prob:.1f}', has_kalshi, is_interpolated])
csv_content = output.getvalue()
output.close()
snap_count = len(snapshots)
first_ts = snapshots[0].get('timestamp', 'unknown') if snapshots else 'none'
last_ts = snapshots[-1].get('timestamp', 'unknown') if snapshots else 'none'
now_str = datetime.now(timezone.utc).strftime('%Y-%m-%d_%H%M')
# Resend attachment: base64-encoded CSV
csv_b64 = base64.b64encode(csv_content.encode('utf-8')).decode('utf-8')
if not RESEND_API_KEY:
print(f"[{datetime.now().isoformat()}] CSV backup email skipped (no RESEND_API_KEY)")
return False
payload = {
'from': RESEND_FROM,
'to': [BACKUP_EMAIL],
'subject': f'IL9Cast Data Backup - {now_str} ({snap_count} snapshots)',
'html': (
f'<h3>IL9Cast Automated Data Backup</h3>'
f'<p><strong>Snapshots:</strong> {snap_count}</p>'
f'<p><strong>Range:</strong> {first_ts} → {last_ts}</p>'
f'<p><strong>CSV Size:</strong> {len(csv_content):,} bytes</p>'
f'<p>Attached: <code>il9cast_backup_{now_str}.csv</code></p>'
f'<hr><p style="color:#888;font-size:12px">Sent automatically every 4 hours from IL9Cast</p>'
),
'attachments': [{
'filename': f'il9cast_backup_{now_str}.csv',
'content': csv_b64
}]
}
resp = requests.post(
'https://api.resend.com/emails',
headers={
'Authorization': f'Bearer {RESEND_API_KEY}',
'Content-Type': 'application/json'
},
json=payload,
timeout=30
)
if resp.status_code in (200, 201):
print(f"[{datetime.now().isoformat()}] CSV backup sent to {BACKUP_EMAIL} ({snap_count} snapshots, {len(csv_content):,} bytes)")
return True
else:
print(f"[{datetime.now().isoformat()}] CSV backup email failed ({resp.status_code}): {resp.text}")
return False
except Exception as e:
print(f"[{datetime.now().isoformat()}] CSV backup email error: {e}")
return False
def send_swing_alert_to_subscriber(email, swings):
"""Build and send swing alert email to a single subscriber."""
if not swings:
return
# Build plain text version
text_rows = []
for s in swings:
arrow = '▲' if s['delta'] > 0 else '▼'
text_rows.append(f"{s['name']}: {s['old']:.1f}% → {s['new']:.1f}% ({arrow} {abs(s['delta']):.1f}%)")
text = f"""
IL9Cast Big Swing Alert!
{chr(10).join(text_rows)}
View Live Markets: {SITE_BASE_URL}markets
"""
# Build HTML rows
rows = ''
for s in swings:
arrow = '▲' if s['delta'] > 0 else '▼'
color = '#31B686' if s['delta'] > 0 else '#e74c3c'
rows += f"""
<tr>
<td style="padding: 14px; border-bottom: 1px solid #2a2a30; color: #F0EFEB; font-weight: 500;">{s['name']}</td>
<td style="padding: 14px; border-bottom: 1px solid #2a2a30; color: #888;">{s['old']:.1f}%</td>
<td style="padding: 14px; border-bottom: 1px solid #2a2a30; color: #31B0B5; font-weight: 600;">{s['new']:.1f}%</td>
<td style="padding: 14px; border-bottom: 1px solid #2a2a30; color: {color}; font-weight: 700; font-size: 16px;">
{arrow} {abs(s['delta']):.1f}%
</td>
</tr>"""
subject = f"⚡ IL9Cast Alert: {swings[0]['name']} {'+' if swings[0]['delta'] > 0 else ''}{swings[0]['delta']:.1f}%"
if len(swings) > 1:
subject = f"⚡ IL9Cast Alert: {len(swings)} candidates moved significantly"
token = make_unsub_token(email)
unsub_url = f"{SITE_BASE_URL}unsubscribe?email={email}&token={token}"
html = f"""
<!DOCTYPE html>
<html>
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"></head>
<body style="margin: 0; padding: 0; background-color: #1A1A1E; font-family: 'Source Sans 3', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;">
<table role="presentation" cellpadding="0" cellspacing="0" border="0" width="100%" style="background-color: #1A1A1E;">
<tr><td align="center" style="padding: 40px 20px;">
<table role="presentation" cellpadding="0" cellspacing="0" border="0" width="600" style="max-width: 600px; background-color: #232328; border: 1px solid #31B0B5;">
<!-- Logo -->
<tr><td style="padding: 32px 40px 0 40px; text-align: center; border-bottom: 1px solid #2a2a30;">
<h1 style="margin: 0 0 6px 0; font-family: Georgia, 'Times New Roman', serif; font-size: 28px; font-weight: 400; letter-spacing: 1px;">
<span style="color: #F0EFEB;">IL9</span><span style="color: #31B0B5;">Cast</span>
</h1>
<p style="margin: 0 0 20px 0; color: #31B0B5; font-size: 11px; letter-spacing: 2px; text-transform: uppercase; font-weight: 700;">Market Movement Detected</p>
</td></tr>
<!-- Data Table -->
<tr><td style="padding: 28px 40px;">
<table role="presentation" cellpadding="0" cellspacing="0" border="0" width="100%" style="background-color: #1A1A1E; border: 1px solid #2a2a30;">
<thead>
<tr style="background-color: #1A1A1E;">
<th style="text-align: left; padding: 12px 14px; color: #888; font-size: 10px; font-weight: 600; letter-spacing: 0.5px; text-transform: uppercase; border-bottom: 1px solid #2a2a30;">Candidate</th>
<th style="text-align: left; padding: 12px 14px; color: #888; font-size: 10px; font-weight: 600; letter-spacing: 0.5px; text-transform: uppercase; border-bottom: 1px solid #2a2a30;">Before</th>
<th style="text-align: left; padding: 12px 14px; color: #888; font-size: 10px; font-weight: 600; letter-spacing: 0.5px; text-transform: uppercase; border-bottom: 1px solid #2a2a30;">After</th>
<th style="text-align: left; padding: 12px 14px; color: #888; font-size: 10px; font-weight: 600; letter-spacing: 0.5px; text-transform: uppercase; border-bottom: 1px solid #2a2a30;">Change</th>
</tr>
</thead>
<tbody>
{rows}
</tbody>
</table>
</td></tr>
<!-- CTA -->
<tr><td style="padding: 0 40px 32px 40px; text-align: center;">
<a href="{SITE_BASE_URL}markets" style="display: inline-block; background-color: #31B0B5; color: #ffffff; text-decoration: none; padding: 12px 32px; font-weight: 600; font-size: 15px;">View Live Markets</a>
</td></tr>
<!-- Footer -->
<tr><td style="padding: 20px 40px; text-align: center; border-top: 1px solid #2a2a30;">
<p style="margin: 0; color: #555; font-size: 11px;"><a href="{unsub_url}" style="color: #555; text-decoration: underline;">Unsubscribe</a></p>
</td></tr>
</table>
</td></tr>
</table>
</body>
</html>
"""
send_email(email, subject, html, text)
# ===== FEC API FUNCTIONS =====
def fetch_all_fec_data():
"""
Returns hardcoded FEC data for all IL-09 2026 candidates.
Source: Pre-Primary FEC filings (coverage through Feb 25, 2026).
Filed March 5, 2026. Retrieved March 6, 2026.
Field definitions:
- total_raised: Cumulative receipts (FEC Line 11e, Column B - total)
- total_spent: Cumulative disbursements (FEC Line 22, Column B - total)
- cash_on_hand: FEC-reported COH (Line 27). May differ from
total_raised - total_spent due to beginning balance, loans, refunds.
- total_donors: Estimated donor count from contribution data
- small_dollar_amount: Unitemized individual contributions (under $200)
- individual_total: Total individual contributions (itemized + unitemized)
- burn_rate_monthly: Period disbursements (Column A, Jan 1-Feb 25 only,
56 days) converted to monthly: amount / (56 / 30.44).
Uses period-specific disbursements, NOT cumulative total_spent.