Coverage for scripts/refresh_universe_availability.py: 100%
82 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"""Set each universe asset's `available_from` / `available_to` in config.json to the first / last bar of its zip.
3The fields are metadata (nothing in the trading or training path reads them); after the V5.8.0 data rewrite they still
4said 2021-03-31. Dry run by default; `--apply` rewrites only those two values in place (the rest of the file's text is
5left byte-identical).
7 python scripts/refresh_universe_availability.py [--config config.json] [--apply]
8"""
10from __future__ import annotations
12import argparse
13import json
14import re
15import sys
16import zipfile
17from pathlib import Path
19ROOT_DIR = Path(__file__).resolve().parents[1]
22def zip_date_range(zip_path: Path) -> tuple[str, str] | None:
23 """First and last bar date (YYYY-MM-DD) of a daily Lean zip, or None when it is missing or empty."""
24 if not zip_path.is_file():
25 return None
26 with zipfile.ZipFile(zip_path) as archive:
27 members = [name for name in archive.namelist() if name.endswith(".csv")]
28 if not members:
29 return None
30 lines = [line for line in archive.read(members[0]).decode("utf-8").splitlines() if line.strip()]
31 if not lines:
32 return None
34 def _date(line: str) -> str:
35 stamp = line.split(",", 1)[0].strip()[:8]
36 return f"{stamp[:4]}-{stamp[4:6]}-{stamp[6:8]}"
38 return _date(lines[0]), _date(lines[-1])
41def planned_updates(config: dict, root: Path) -> list[dict]:
42 updates = []
43 for asset in config["phase1"]["universe"]["assets"]:
44 found = zip_date_range(root / asset["data_path"])
45 if found is None:
46 continue
47 first, last = found
48 if asset.get("available_from") != first or asset.get("available_to") != last:
49 updates.append({"ticker": asset["ticker"], "from": (asset.get("available_from"), first), "to": (asset.get("available_to"), last)})
50 return updates
53def _enclosing_object(text: str, position: int) -> tuple[int, int]:
54 """Span of the JSON object that contains `position` (assets hold nested objects, so braces are counted)."""
55 depth, start = 0, position
56 while start > 0:
57 start -= 1
58 if text[start] == "}":
59 depth += 1
60 elif text[start] == "{":
61 if depth == 0:
62 break
63 depth -= 1
64 depth, end = 0, start
65 for end in range(start, len(text)):
66 if text[end] == "{":
67 depth += 1
68 elif text[end] == "}":
69 depth -= 1
70 if depth == 0:
71 break
72 return start, end + 1
75def apply_updates(text: str, updates: list[dict]) -> str:
76 """Rewrite the two top-level date values of each updated asset's object, found by its unique `"ticker": "<T>"`."""
77 for update in updates:
78 anchor = re.search(r'"ticker":\s*"' + re.escape(update["ticker"]) + r'"', text)
79 if anchor is None:
80 raise ValueError(f"ticker {update['ticker']} not found")
81 start, end = _enclosing_object(text, anchor.start())
82 block = text[start:end]
83 for key, (_, new) in (("available_from", update["from"]), ("available_to", update["to"])):
84 block = re.sub(r'("' + key + r'":\s*")[^"]*(")', lambda m, new=new: m.group(1) + new + m.group(2), block, count=1)
85 text = text[:start] + block + text[end:]
86 return text
89def main(argv: list[str] | None = None) -> int:
90 parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
91 parser.add_argument("--config", default=str(ROOT_DIR / "config.json"))
92 parser.add_argument("--root", default=str(ROOT_DIR))
93 parser.add_argument("--apply", action="store_true")
94 args = parser.parse_args(argv)
95 path = Path(args.config)
96 text = path.read_text(encoding="utf-8")
97 updates = planned_updates(json.loads(text), Path(args.root))
98 for update in updates:
99 print(f"{update['ticker']:<8} from {update['from'][0]} -> {update['from'][1]} to {update['to'][0]} -> {update['to'][1]}")
100 print(f"{len(updates)} asset(s) to update")
101 if args.apply and updates:
102 new_text = apply_updates(text, updates)
103 json.loads(new_text)
104 path.write_text(new_text, encoding="utf-8")
105 print(f"wrote {path}")
106 return 0
109if __name__ == "__main__":
110 sys.exit(main())