SPB Git

spb/findata

Public
6.7 KB · 148 lines python
1"""`findata` operator CLI."""2from __future__ import annotations34import json5from pathlib import Path67import typer89app = typer.Typer(no_args_is_help=True, help="FinData OS operator CLI")101112@app.callback()13def _main() -> None:14    import atexit1516    from findata_core.db import close_pool17    atexit.register(close_pool)18ingest_app = typer.Typer(no_args_is_help=True)19app.add_typer(ingest_app, name="ingest")202122@app.command()23def migrate() -> None:24    """Apply database migrations."""25    from findata_core.db import migrate as _m26    applied = _m()27    typer.echo(f"applied: {applied or 'nothing'}")282930@app.command()31def discover(source: str = "all") -> None:32    """Sanitized live probe of vendor capabilities (no bulk download)."""33    out = {}34    if source in ("all", "firstrate"):35        from findata_market_firstrate import FirstRateMarketConnector36        out["firstrate"] = FirstRateMarketConnector().discover()37    if source in ("all", "firstrate_fundamentals"):38        from findata_fundamentals import FirstRateFundamentalsConnector39        out["firstrate_fundamentals"] = FirstRateFundamentalsConnector().discover()40    if source in ("all", "sec_edgar"):41        from findata_fundamentals import SecEdgarConnector42        out["sec_edgar"] = SecEdgarConnector().status()43    typer.echo(json.dumps(out, indent=2, default=str))444546@app.command()47def worker(once: bool = False, no_scheduler: bool = False, kinds: str | None = None) -> None:48    """Run the single ingest worker (+ scheduler)."""49    from findata_ingest.worker import main50    main(once=once, kinds=kinds.split(",") if kinds else None, with_scheduler=not no_scheduler)515253@ingest_app.command("metadata")54def ingest_metadata(types: str = "stock,etf") -> None:55    from findata_ingest import queue56    typer.echo(queue.enqueue("metadata", None, {"types": types.split(",")}, priority=10, created_by="cli"))575859@ingest_app.command("incremental")60def ingest_incremental(type_: str = typer.Option("stock", "--type"), period: str = "day", timeframe: str = "1min",61                       adjustment: str = "UNADJUSTED", force: bool = False) -> None:62    from findata_ingest import queue63    from findata_ingest.tasks.common import DATASET_ASSET64    typer.echo(queue.enqueue("incremental", DATASET_ASSET[type_], {"type": type_, "period": period, "timeframe": timeframe,65                             "adjustment": adjustment, "force": force}, priority=20, created_by="cli"))666768@ingest_app.command("backfill")69def ingest_backfill(ticker_range: str, type_: str = typer.Option("stock", "--type"), timeframe: str = "1min",70                    adjustment: str = "UNADJUSTED", symbols: str | None = None, max_symbols: int = 0) -> None:71    """Bounded backfill of one ticker_range letter (full archive). Disk budget enforced by the lake."""72    from findata_ingest import queue73    from findata_ingest.tasks.common import DATASET_ASSET74    for letter in ticker_range.upper():75        jid = queue.enqueue("backfill", DATASET_ASSET[type_], {"type": type_, "ticker_range": letter, "timeframe": timeframe, "adjustment": adjustment,76                            "symbols": symbols.split(",") if symbols else None, "max_symbols": max_symbols}, priority=35, created_by="cli",77                            dedupe_key=f"backfill:{type_}:{letter}:{timeframe}:{adjustment}")78        typer.echo(f"{letter}: {jid or 'already queued'}")798081@ingest_app.command("fundamentals")82def ingest_fundamentals(tickers: str) -> None:83    from findata_ingest import queue84    typer.echo(queue.enqueue("fundamentals", "fundamentals.financials", {"tickers": tickers.split(",")}, priority=30, created_by="cli"))858687@ingest_app.command("derive")88def ingest_derive(dates: str | None = None, source: str = "market_bars.stock.1m.raw") -> None:89    from findata_ingest import queue90    typer.echo(queue.enqueue("derive", source.replace(".1m.", ".5m."), {"source_dataset": source, "target_interval": "5m", "dates": dates.split(",") if dates else []}, created_by="cli"))919293@ingest_app.command("compaction")94def ingest_compaction(dataset: str = "market_bars.stock.1m.raw", min_age_days: int = 35) -> None:95    from findata_ingest import queue96    typer.echo(queue.enqueue("compaction", dataset, {"min_age_days": min_age_days}, priority=60, created_by="cli"))979899@ingest_app.command("jobs")100def ingest_jobs(limit: int = 20) -> None:101    from findata_core.db import fetch_all102    for r in fetch_all("SELECT id, kind, dataset_id, status, attempts, created_at, finished_at, left(last_error, 80) err FROM ingest_jobs ORDER BY created_at DESC LIMIT %s", (limit,)):103        typer.echo(f"{str(r['id'])[:8]} {r['kind']:<12} {r['dataset_id']!s:<28} {r['status']:<9} a={r['attempts']} {r['created_at']:%m-%d %H:%M} {r['err'] or ''}")104105106@app.command()107def backup(now: bool = True) -> None:108    from findata_ingest import queue109    typer.echo(queue.enqueue("backup", None, {}, priority=5, created_by="cli"))110111112@app.command("restore-drill")113def restore_drill(dest: Path = Path("/tmp/findata-restore-drill"), dataset: str = "market_bars.stock.1m.raw") -> None:114    from findata_core.config import get_settings115116    from findata_ingest.tasks.backup import restore_drill as rd117    typer.echo(json.dumps(rd(get_settings().backup_target, dest, dataset), indent=2, default=str))118119120@app.command("create-owner")121def create_owner(email: str, password: str | None = None) -> None:122    """Create (or reset the password of) the owner account; prints the TOTP provisioning URI."""123    from findata_api.auth import create_owner as _co124    typer.echo(json.dumps(_co(email, password), indent=2))125126127@app.command("create-key")128def create_key(email: str, name: str, scopes: str = "read:market,read:fundamentals,query,export") -> None:129    from findata_api.auth import create_api_key_for_email130    typer.echo(json.dumps(create_api_key_for_email(email, name, scopes.split(",")), indent=2))131132133@app.command()134def status() -> None:135    from findata_core.db import fetch_all, fetch_one136137    from findata_ingest.lake import Lake138    lake = Lake()139    typer.echo(f"lake {lake.root}  free {lake.free_gb():.1f} GB  curated {lake.used_bytes('curated')/1e9:.2f} GB  raw {lake.used_bytes('raw')/1e9:.2f} GB")140    for r in fetch_all("SELECT d.id, d.status, d.current_version, v.file_count, v.row_count, v.bytes FROM datasets d LEFT JOIN dataset_versions v ON v.dataset_id=d.id AND v.version=d.current_version ORDER BY d.id"):141        typer.echo(f"  {r['id']:<36} {r['status']:<22} v{r['current_version']:<4} files={r['file_count'] or 0:<6} rows={r['row_count'] or 0:<12} {(r['bytes'] or 0)/1e6:.1f} MB")142    q = fetch_one("SELECT count(*) FILTER (WHERE status='queued') q, count(*) FILTER (WHERE status='running') r, count(*) FILTER (WHERE status='dead') d FROM ingest_jobs")143    typer.echo(f"jobs queued={q['q']} running={q['r']} dead={q['d']}")144145146if __name__ == "__main__":147    app()148
Files · 9a819d1829671b07bdaf966a2d99dfb979de93f5
Menu

Theme