Coverage for scripts/build_hello_sample.py: 100%

50 statements  

« prev     ^ index     » next       coverage.py v7.17.3, created at 2026-11-22 12:55 +0000

1"""Build the sample `aq hello --offline` and the notebooks read (V6.6.5, #343): the shipped book's 11 coins, daily open and 

2close from Coinbase's public candles, 2021-06-01 to 2026-10-31, gzip with a zero mtime so a rebuild is byte-identical. 

3 

4 python scripts/build_hello_sample.py # fetch and write aether_quant/_sample/ 

5 python scripts/build_hello_sample.py --check # verify the tracked file against its README sha256 

6""" 

7 

8from __future__ import annotations 

9 

10import argparse 

11import gzip 

12import hashlib 

13import io 

14import sys 

15from datetime import date 

16from pathlib import Path 

17 

18ROOT = Path(__file__).resolve().parents[1] 

19sys.path.insert(0, str(ROOT)) 

20 

21from data_pipeline.public_candles import fetch_daily_bars # noqa: E402 

22 

23SAMPLE_DIR = ROOT / "aether_quant" / "_sample" 

24SAMPLE = SAMPLE_DIR / "coinbase_daily.csv.gz" 

25README = SAMPLE_DIR / "README.md" 

26TICKERS = ("ADAUSD", "BCHUSD", "BTCUSD", "DOGEUSD", "ETCUSD", "ETHUSD", "LINKUSD", "LTCUSD", "XLMUSD", "XRPUSD", "ZECUSD") 

27START, END = date(2021, 6, 1), date(2026, 10, 31) 

28 

29 

30def _fmt(value: float) -> str: 

31 return f"{float(value):.8g}" 

32 

33 

34def sample_bytes(bars: dict) -> bytes: 

35 lines = ["date,ticker,open,close"] 

36 rows = sorted((row.date, ticker, row.open, row.close) for ticker, frame in bars.items() for row in frame.itertuples(index=False)) 

37 lines += [f"{day},{ticker},{_fmt(open_)},{_fmt(close)}" for day, ticker, open_, close in rows] 

38 buffer = io.BytesIO() 

39 with gzip.GzipFile(filename="", mode="wb", fileobj=buffer, mtime=0, compresslevel=9) as handle: 

40 handle.write(("\n".join(lines) + "\n").encode("utf-8")) 

41 return buffer.getvalue() 

42 

43 

44def readme_text(digest: str, rows: int) -> str: 

45 return ( 

46 "# Sample data for `aq hello` and the notebooks\n\n" 

47 f"- **File:** `coinbase_daily.csv.gz`, {rows} rows, columns `date,ticker,open,close` (8 significant figures).\n" 

48 f"- **Coins:** {', '.join(TICKERS)}: the shipped book's universe.\n" 

49 f"- **Window:** <!--fact:sample.first-->{START.isoformat()}<!--/fact--> to <!--fact:sample.last-->{END.isoformat()}<!--/fact-->, daily bars in UTC. XRP-USD trades on Coinbase only from 2023-07-13.\n" 

50 "- **Source:** Coinbase Exchange public candles (`api.exchange.coinbase.com/products/<id>/candles`), no key. Prices are factual market data, " 

51 "kept here only so the demo runs offline.\n" 

52 "- **Rebuild:** `python scripts/build_hello_sample.py` (byte-identical for the same data); `--check` verifies the digest.\n" 

53 f"- **sha256:** `{digest}`\n" 

54 ) 

55 

56 

57def main(argv: list[str] | None = None) -> int: 

58 parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) 

59 parser.add_argument("--check", action="store_true") 

60 args = parser.parse_args(argv) 

61 if args.check: 

62 digest = hashlib.sha256(SAMPLE.read_bytes()).hexdigest() 

63 ok = f"`{digest}`" in README.read_text(encoding="utf-8") 

64 print(f"sample sha256 {digest}: {'matches' if ok else 'DIFFERS from'} README") 

65 return 0 if ok else 1 

66 bars, failed = fetch_daily_bars(TICKERS, START, END, cache_dir=None, today=date(2026, 11, 8)) 

67 if failed: 

68 print(f"failed coins: {failed}", file=sys.stderr) 

69 return 1 

70 payload = sample_bytes(bars) 

71 SAMPLE_DIR.mkdir(parents=True, exist_ok=True) 

72 SAMPLE.write_bytes(payload) 

73 rows = sum(len(frame) for frame in bars.values()) 

74 README.write_text(readme_text(hashlib.sha256(payload).hexdigest(), rows), encoding="utf-8", newline="\n") 

75 print(f"wrote {SAMPLE.relative_to(ROOT)}: {rows} rows, {len(payload) / 1024:.0f} KB") 

76 return 0 

77 

78 

79if __name__ == "__main__": 

80 raise SystemExit(main())