-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbtc_overnight_message.py
More file actions
executable file
·69 lines (56 loc) · 1.93 KB
/
btc_overnight_message.py
File metadata and controls
executable file
·69 lines (56 loc) · 1.93 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
#!/usr/bin/env python3
import json
import sys
from datetime import datetime, timedelta
from zoneinfo import ZoneInfo
# Reads jsonl from stdin or a file path arg; prints a short message
# comparing the most recent sample to the most recent 5pm sample.
tz = ZoneInfo('America/Edmonton')
path = sys.argv[1] if len(sys.argv) > 1 else None
fh = open(path, 'r', encoding='utf-8') if path else sys.stdin
recs = []
for line in fh:
line = line.strip()
if not line:
continue
recs.append(json.loads(line))
if path:
fh.close()
if not recs:
print('No BTC samples yet.')
sys.exit(0)
recs.sort(key=lambda r: int(r['ts']))
latest = recs[-1]
latest_dt = datetime.fromtimestamp(int(latest['ts']), tz)
# Find latest 5pm (hour==17) sample strictly before latest, else any 5pm sample.
prev_5pm = None
for r in reversed(recs[:-1]):
dt = datetime.fromtimestamp(int(r['ts']), tz)
if dt.hour == 17:
prev_5pm = r
break
# If latest itself is a 5pm sample, compare to previous day's 5pm.
if latest_dt.hour == 17:
prev_5pm = None
for r in reversed(recs[:-1]):
dt = datetime.fromtimestamp(int(r['ts']), tz)
if dt.hour == 17 and dt.date() < latest_dt.date():
prev_5pm = r
break
btc_usd = float(latest['btc_usd'])
btc_cad = float(latest['btc_cad'])
usd_cad = float(latest['usd_cad'])
lines = []
lines.append(f"BTC snapshot ({latest_dt:%Y-%m-%d %H:%M} MST)")
lines.append(f"- BTC/USD: ${btc_usd:,.0f}")
lines.append(f"- BTC/CAD: C${btc_cad:,.0f}")
lines.append(f"- USD/CAD: {usd_cad:.4f}")
if prev_5pm:
pdt = datetime.fromtimestamp(int(prev_5pm['ts']), tz)
p_usd = float(prev_5pm['btc_usd'])
p_cad = float(prev_5pm['btc_cad'])
d_usd = btc_usd - p_usd
d_cad = btc_cad - p_cad
pct = (d_usd / p_usd) * 100 if p_usd else 0.0
lines.append(f"Overnight vs last 5pm ({pdt:%Y-%m-%d %H:%M}): {d_usd:+,.0f} USD ({pct:+.2f}%) / {d_cad:+,.0f} CAD")
print("\n".join(lines))