Coverage for data_pipeline/public_candles.py: 100%
120 statements
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-22 12:55 +0000
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-22 12:55 +0000
1"""Daily bars from Coinbase's public candles, with no key, no account and no extra package (V6.6.5, #343).
3The endpoint returns at most 300 rows per call, newest first, each `[time, low, high, open, close, volume]`. A coin is fetched
4one window at a time and one coin at a time; a coin whose fetch fails is named and left out, so one delisted product never
5voids the rest. Only closed bars are kept: a bar dated today (UTC) is still forming. Results are cached as CSV so a second
6run is offline. The parsing and windowing are pure; the network is an injected `get_json`.
7"""
9from __future__ import annotations
11import csv
12import json
13import time
14import urllib.error
15import urllib.request
16from collections.abc import Callable, Sequence
17from datetime import date, datetime, timedelta, timezone
18from pathlib import Path
20import numpy as np
21import pandas as pd
23COINBASE_CANDLES_URL = "https://api.exchange.coinbase.com/products/{product}/candles?granularity=86400&start={start}&end={end}"
24USER_AGENT = "AetherQuantResearch/6.6 (github.com/leon1706-lol/Aether-quant)"
25MAX_ROWS = 300
26COLUMNS = ("date", "open", "high", "low", "close", "volume")
27DEFAULT_CACHE_DIR = Path.home() / ".cache" / "aether-quant" / "candles"
29GetJson = Callable[[str], object]
32def coinbase_product(ticker: str) -> str:
33 """`BTCUSD` -> `BTC-USD`; a ticker that already has a dash is returned as it is."""
34 text = str(ticker).upper()
35 return text if "-" in text else f"{text[:-3]}-{text[-3:]}"
38def candle_windows(start: date, end: date, max_rows: int = MAX_ROWS) -> list[tuple[date, date]]:
39 """Inclusive [start, end] cut into windows of at most `max_rows - 1` days, oldest first (one spare row of headroom)."""
40 if end < start:
41 return []
42 span = max(int(max_rows) - 1, 1)
43 windows: list[tuple[date, date]] = []
44 cursor = start
45 while cursor <= end:
46 stop = min(cursor + timedelta(days=span - 1), end)
47 windows.append((cursor, stop))
48 cursor = stop + timedelta(days=1)
49 return windows
52def candles_url(product: str, start: date, end: date) -> str:
53 """The Coinbase public candles URL for one product and an inclusive day window, daily granularity."""
54 return COINBASE_CANDLES_URL.format(product=product, start=f"{start.isoformat()}T00:00:00Z", end=f"{end.isoformat()}T23:59:59Z")
57def parse_candles(rows: object) -> pd.DataFrame:
58 """Rows to a frame with columns `date, open, high, low, close, volume`, ascending by date. Drops malformed, non-finite,
59 non-positive-price and duplicate rows (the first of a duplicated date is kept)."""
60 records: list[dict[str, object]] = []
61 if isinstance(rows, list):
62 for row in rows:
63 if not isinstance(row, (list, tuple)) or len(row) < 6:
64 continue
65 try:
66 stamp = int(float(row[0]))
67 low, high, open_, close, volume = (float(value) for value in row[1:6])
68 except (TypeError, ValueError, OverflowError):
69 continue
70 prices = (open_, high, low, close)
71 if not all(np.isfinite(value) and value > 0.0 for value in prices) or not np.isfinite(volume):
72 continue
73 day = datetime.fromtimestamp(stamp, timezone.utc).strftime("%Y-%m-%d")
74 records.append({"date": day, "open": open_, "high": high, "low": low, "close": close, "volume": volume})
75 frame = pd.DataFrame(records, columns=list(COLUMNS))
76 if frame.empty:
77 return frame
78 return frame.drop_duplicates("date", keep="first").sort_values("date").reset_index(drop=True)
81def default_get_json(url: str, *, timeout: float = 20.0, retries: int = 3, backoff: float = 1.5) -> object:
82 """GET a JSON document with the standard library. Retries a transient failure with exponential backoff."""
83 request = urllib.request.Request(url, headers={"User-Agent": USER_AGENT, "Accept": "application/json"})
84 error: Exception | None = None
85 for attempt in range(max(int(retries), 1)):
86 try:
87 with urllib.request.urlopen(request, timeout=timeout) as response:
88 return json.loads(response.read().decode("utf-8"))
89 except (urllib.error.URLError, TimeoutError, json.JSONDecodeError, OSError) as exc:
90 error = exc
91 if attempt + 1 < retries:
92 time.sleep(backoff ** attempt)
93 raise ConnectionError(f"public candles fetch failed: {error}")
96def _read_cache(cache_dir: Path, ticker: str) -> tuple[pd.DataFrame, dict[str, str]] | None:
97 data, meta = cache_dir / f"{ticker}.csv", cache_dir / f"{ticker}.json"
98 if not data.is_file() or not meta.is_file():
99 return None
100 try:
101 frame = pd.read_csv(data, dtype={"date": str})
102 info = json.loads(meta.read_text(encoding="utf-8"))
103 except (OSError, ValueError):
104 return None
105 if list(frame.columns) != list(COLUMNS) or not isinstance(info, dict):
106 return None
107 return frame, {str(key): str(value) for key, value in info.items()}
110def _write_cache(cache_dir: Path, ticker: str, frame: pd.DataFrame, start: date, end: date) -> None:
111 try:
112 cache_dir.mkdir(parents=True, exist_ok=True)
113 frame.to_csv(cache_dir / f"{ticker}.csv", index=False, quoting=csv.QUOTE_MINIMAL)
114 (cache_dir / f"{ticker}.json").write_text(json.dumps({"start": start.isoformat(), "end": end.isoformat()}), encoding="utf-8")
115 except OSError:
116 pass # a read-only home only costs the next run a download
119def fetch_daily_bars(
120 tickers: Sequence[str], start: date, end: date, *, get_json: GetJson = default_get_json, cache_dir: Path | None = DEFAULT_CACHE_DIR,
121 today: date | None = None,
122) -> tuple[dict[str, pd.DataFrame], list[str]]:
123 """({ticker: bars}, failed tickers). Bars cover [start, min(end, yesterday)] and never include today's forming bar.
124 A cache written for an earlier-or-equal start and a later-or-equal end is reused without a call."""
125 today = today or datetime.now(timezone.utc).date()
126 last_closed = min(end, today - timedelta(days=1))
127 bars: dict[str, pd.DataFrame] = {}
128 failed: list[str] = []
129 for ticker in tickers:
130 if cache_dir is not None:
131 cached = _read_cache(Path(cache_dir), ticker)
132 if cached is not None:
133 frame, info = cached
134 if info.get("start", "9999") <= start.isoformat() and info.get("end", "") >= last_closed.isoformat():
135 bars[ticker] = frame[(frame["date"] >= start.isoformat()) & (frame["date"] <= last_closed.isoformat())].reset_index(drop=True)
136 continue
137 try:
138 parts = [parse_candles(get_json(candles_url(coinbase_product(ticker), lo, hi))) for lo, hi in candle_windows(start, last_closed)]
139 except Exception:
140 failed.append(ticker)
141 continue
142 frame = pd.concat([part for part in parts if not part.empty], ignore_index=True) if any(not part.empty for part in parts) else parse_candles([])
143 if not frame.empty:
144 frame = frame.drop_duplicates("date", keep="first").sort_values("date")
145 frame = frame[(frame["date"] >= start.isoformat()) & (frame["date"] <= last_closed.isoformat())].reset_index(drop=True)
146 if frame.empty:
147 failed.append(ticker)
148 continue
149 bars[ticker] = frame
150 if cache_dir is not None:
151 _write_cache(Path(cache_dir), ticker, frame, start, last_closed)
152 return bars, failed
155def bars_to_panel(bars: dict[str, pd.DataFrame], field: str = "close") -> pd.DataFrame:
156 """{ticker: bars} to a dates x tickers frame of one field, indexed by `YYYY-MM-DD` strings, NaN where a coin has no bar."""
157 if field not in COLUMNS[1:]:
158 raise ValueError(f"field must be one of {COLUMNS[1:]}")
159 columns = {ticker: frame.set_index("date")[field].astype(float) for ticker, frame in bars.items() if not frame.empty}
160 if not columns:
161 return pd.DataFrame()
162 return pd.DataFrame(columns).sort_index()