|
| 1 | +"""``iaf index`` CLI \u2014 build a SQLite Tier-1 index over a folder of |
| 2 | +``.iafbt`` bundles (epic #540 phase 2). |
| 3 | +
|
| 4 | +Walks the directory, opens each bundle with ``summary_only=True`` (no |
| 5 | +Parquet metric-blob decode), derives a :class:`BacktestIndexRow` via |
| 6 | +:meth:`Backtest.index_row`, and upserts into a |
| 7 | +:class:`SqliteBacktestIndex`. |
| 8 | +""" |
| 9 | + |
| 10 | +from __future__ import annotations |
| 11 | + |
| 12 | +import logging |
| 13 | +from pathlib import Path |
| 14 | +from typing import Iterable, List, Optional |
| 15 | + |
| 16 | +from investing_algorithm_framework.domain import ( |
| 17 | + Backtest, |
| 18 | + BUNDLE_EXT, |
| 19 | +) |
| 20 | +from investing_algorithm_framework.services.backtest_index import ( |
| 21 | + SqliteBacktestIndex, |
| 22 | +) |
| 23 | + |
| 24 | +logger = logging.getLogger(__name__) |
| 25 | + |
| 26 | + |
| 27 | +DEFAULT_INDEX_NAME = "index.sqlite" |
| 28 | + |
| 29 | + |
| 30 | +def _iter_bundle_paths(directory: Path) -> Iterable[Path]: |
| 31 | + """Yield every ``*.iafbt`` file under *directory* (sorted).""" |
| 32 | + return sorted(directory.rglob(f"*{BUNDLE_EXT}")) |
| 33 | + |
| 34 | + |
| 35 | +def build_index( |
| 36 | + directory: str, |
| 37 | + output: Optional[str] = None, |
| 38 | + relative_paths: bool = True, |
| 39 | + show_progress: bool = False, |
| 40 | +) -> str: |
| 41 | + """Build (or refresh) a SQLite Tier-1 index over *directory*. |
| 42 | +
|
| 43 | + Args: |
| 44 | + directory: Folder to scan for ``.iafbt`` bundles. |
| 45 | + output: Path to the SQLite file. Defaults to |
| 46 | + ``<directory>/index.sqlite``. |
| 47 | + relative_paths: if True, store ``bundle_path`` relative to |
| 48 | + *directory* so the index file stays portable when the |
| 49 | + folder is moved/renamed. |
| 50 | + show_progress: emit a tqdm progress bar. |
| 51 | +
|
| 52 | + Returns: |
| 53 | + Absolute path of the SQLite file that was written. |
| 54 | + """ |
| 55 | + src = Path(directory).resolve() |
| 56 | + if not src.is_dir(): |
| 57 | + raise NotADirectoryError(f"Not a directory: {src}") |
| 58 | + |
| 59 | + out = Path(output).resolve() if output else src / DEFAULT_INDEX_NAME |
| 60 | + paths: List[Path] = list(_iter_bundle_paths(src)) |
| 61 | + |
| 62 | + pbar = None |
| 63 | + if show_progress: |
| 64 | + try: |
| 65 | + from tqdm import tqdm |
| 66 | + pbar = tqdm(total=len(paths), desc="Indexing bundles") |
| 67 | + except ImportError: # pragma: no cover - tqdm is a dep |
| 68 | + pbar = None |
| 69 | + |
| 70 | + index = SqliteBacktestIndex.create(out) |
| 71 | + n_ok = 0 |
| 72 | + n_err = 0 |
| 73 | + try: |
| 74 | + for path in paths: |
| 75 | + try: |
| 76 | + bt = Backtest.open(str(path), summary_only=True) |
| 77 | + bundle_path = ( |
| 78 | + str(path.relative_to(src)) if relative_paths |
| 79 | + else str(path) |
| 80 | + ) |
| 81 | + row = bt.index_row(bundle_path=bundle_path) |
| 82 | + index.upsert(row) |
| 83 | + n_ok += 1 |
| 84 | + except Exception as exc: # noqa: BLE001 \u2014 best-effort scan |
| 85 | + logger.warning("failed to index %s: %s", path, exc) |
| 86 | + n_err += 1 |
| 87 | + finally: |
| 88 | + if pbar is not None: |
| 89 | + pbar.update(1) |
| 90 | + finally: |
| 91 | + if pbar is not None: |
| 92 | + pbar.close() |
| 93 | + index.close() |
| 94 | + |
| 95 | + logger.info( |
| 96 | + "Indexed %d bundle(s) into %s (%d failed)", n_ok, out, n_err, |
| 97 | + ) |
| 98 | + return str(out) |
0 commit comments