Spaces:
Sleeping
Sleeping
Download batch_runner.py from bdschi1/financial-model-builder-v2: direct link, hf CLI and curl.
- Browser
- Download file 8.43 kB
-
https://huggingface.co/spaces/bdschi1/financial-model-builder-v2/resolve/main/batch_runner.py
- Command line
-
hf download hf://spaces/bdschi1/financial-model-builder-v2/batch_runner.py
-
curl -L -o batch_runner.py https://huggingface.co/spaces/bdschi1/financial-model-builder-v2/resolve/main/batch_runner.py
8.43 kB
| """ | |
| Batch runner β run the SMB pipeline for multiple tickers sequentially. | |
| Each ticker gets its own subdirectory under output_dir/{TICKER}/. | |
| Failures are isolated β one ticker failing does not stop the batch. | |
| A batch_summary.txt is written at the end. | |
| If 2+ tickers succeed, a peer_comparison.xlsx comp sheet is generated. | |
| """ | |
| import os | |
| import time | |
| import traceback | |
| from datetime import datetime | |
| from typing import Callable | |
| import app_runner | |
| def run_batch( | |
| tickers: list[str], | |
| output_dir: str, | |
| options: dict = None, | |
| on_progress: Callable[[str, str, str, bool], None] = None, | |
| ) -> list[dict]: | |
| """ | |
| Run SMB pipeline for multiple tickers sequentially. | |
| Args: | |
| tickers: ["AAPL", "MSFT", "GOOG"] | |
| output_dir: base output directory | |
| options: {"years": 5, "buyside": True, "sellside": True, ...} | |
| on_progress: callback(ticker, stage, message, is_error) | |
| Returns list of result dicts (one per ticker). | |
| """ | |
| options = options or {} | |
| progress = on_progress or (lambda *a: None) | |
| results = [] | |
| total = len(tickers) | |
| batch_start = time.time() | |
| progress("BATCH", "init", f"Starting batch: {total} ticker(s)", False) | |
| for idx, raw_ticker in enumerate(tickers, 1): | |
| ticker = raw_ticker.strip().upper() | |
| if not ticker: | |
| continue | |
| ticker_dir = os.path.join(output_dir, ticker) | |
| os.makedirs(ticker_dir, exist_ok=True) | |
| progress(ticker, "start", f"[{idx}/{total}] Starting {ticker}...", False) | |
| ticker_start = time.time() | |
| # Collect result from on_complete callback | |
| result_holder = [None] | |
| def _on_ticker_progress(stage, message, is_error=False): | |
| progress(ticker, stage, message, is_error) | |
| def _on_ticker_complete(result): | |
| result_holder[0] = result | |
| try: | |
| app_runner.run_pipeline( | |
| ticker=ticker, | |
| output_dir=ticker_dir, | |
| years=options.get("years", 5), | |
| llm_provider=options.get("llm_provider", "none"), | |
| buyside=options.get("buyside", True), | |
| skip_footnotes=options.get("skip_footnotes", False), | |
| eqr=options.get("eqr", False), | |
| sellside=options.get("sellside", False), | |
| licensing=options.get("licensing", False), | |
| lbo=options.get("lbo", False), | |
| ipo=options.get("ipo", False), | |
| pptx=options.get("pptx", False), | |
| on_progress=_on_ticker_progress, | |
| on_complete=_on_ticker_complete, | |
| ) | |
| result = result_holder[0] | |
| if result is None: | |
| result = { | |
| "success": False, | |
| "ticker": ticker, | |
| "error": "Pipeline returned no result", | |
| "elapsed_seconds": time.time() - ticker_start, | |
| } | |
| except Exception as e: | |
| result = { | |
| "success": False, | |
| "ticker": ticker, | |
| "error": str(e), | |
| "traceback": traceback.format_exc(), | |
| "elapsed_seconds": time.time() - ticker_start, | |
| } | |
| progress(ticker, "error", f"ERROR: {ticker} failed β {e}", True) | |
| result["ticker"] = ticker | |
| results.append(result) | |
| status = "OK" if result.get("success") else "FAIL" | |
| elapsed = result.get("elapsed_seconds", 0) | |
| progress(ticker, "done", f"[{idx}/{total}] {ticker}: {status} ({elapsed:.1f}s)", False) | |
| # Write batch summary | |
| batch_elapsed = time.time() - batch_start | |
| summary_path = os.path.join(output_dir, "batch_summary.txt") | |
| _write_summary(results, batch_elapsed, summary_path) | |
| progress("BATCH", "done", f"Batch complete: {summary_path}", False) | |
| # Generate peer comparison sheet if 2+ tickers succeeded | |
| comp_path = aggregate_batch_for_comps(results, output_dir, on_progress=progress) | |
| if comp_path: | |
| progress("BATCH", "comps", f"Peer comparison: {comp_path}", False) | |
| return results | |
| def aggregate_batch_for_comps( | |
| results: list[dict], | |
| output_dir: str, | |
| target_ticker: str | None = None, | |
| on_progress: Callable = None, | |
| ) -> str | None: | |
| """ | |
| After batch completes, aggregate financial data from each ticker | |
| and produce a peer comparison workbook. | |
| Returns path to the comp sheet, or None if <2 tickers succeeded. | |
| """ | |
| progress = on_progress or (lambda *a: None) | |
| # Filter to successful results that have stashed data | |
| eligible = [] | |
| for r in results: | |
| if not r.get("success"): | |
| continue | |
| ad = r.get("annual_data") | |
| md = r.get("market_data") | |
| if not ad or not ad.get("years"): | |
| continue | |
| ci = r.get("company_info", {}) | |
| eligible.append({ | |
| "ticker": r.get("ticker", "???"), | |
| "company_name": r.get("company_name") or ci.get("name", r.get("ticker", "")), | |
| "annual_data": ad, | |
| "market_data": md or {}, | |
| "sic": ci.get("sic", ""), | |
| "industry": (md or {}).get("industry", ""), | |
| }) | |
| if len(eligible) < 2: | |
| progress("BATCH", "comps", | |
| f"Peer comparison skipped ({len(eligible)} ticker(s) β need 2+)", False) | |
| return None | |
| try: | |
| from peer_comp_sheet import write_peer_comp_sheet | |
| comp_path = os.path.join(output_dir, "peer_comparison.xlsx") | |
| progress("BATCH", "comps", | |
| f"Generating peer comparison for {len(eligible)} companies...", False) | |
| result = write_peer_comp_sheet( | |
| comp_path, | |
| eligible, | |
| target_ticker=target_ticker or eligible[0]["ticker"], | |
| ) | |
| if result: | |
| size_mb = os.path.getsize(comp_path) / (1024 * 1024) | |
| progress("BATCH", "comps", | |
| f" Saved: {comp_path} ({size_mb:.1f} MB)", False) | |
| return comp_path | |
| except ImportError: | |
| progress("BATCH", "comps", | |
| "Peer comparison skipped (peer_comp_sheet not available)", True) | |
| except Exception as e: | |
| progress("BATCH", "comps", f"Peer comparison failed: {e}", True) | |
| return None | |
| def _write_summary(results: list[dict], batch_elapsed: float, path: str): | |
| """Write a human-readable batch summary to a text file.""" | |
| succeeded = [r for r in results if r.get("success")] | |
| failed = [r for r in results if not r.get("success")] | |
| lines = [ | |
| "=" * 60, | |
| " SEC Model Builder β Batch Summary", | |
| f" {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}", | |
| "=" * 60, | |
| "", | |
| f" Total tickers: {len(results)}", | |
| f" Succeeded: {len(succeeded)}", | |
| f" Failed: {len(failed)}", | |
| f" Elapsed: {batch_elapsed:.1f}s", | |
| "", | |
| ] | |
| if succeeded: | |
| lines.append(" SUCCEEDED:") | |
| for r in succeeded: | |
| name = r.get("company_name") or r["ticker"] | |
| t = r.get("elapsed_seconds", 0) | |
| lines.append(f" {r['ticker']:8s} {name:40s} {t:6.1f}s") | |
| for key in ("spreading_path", "eqr_path", "sellside_path", | |
| "licensing_path", "lbo_path", "ipo_path", "footnote_path"): | |
| p = r.get(key) | |
| if p: | |
| short_key = key.replace("_path", "") | |
| lines.append(f" {short_key}: {p}") | |
| lines.append("") | |
| if failed: | |
| lines.append(" FAILED:") | |
| for r in failed: | |
| t = r.get("elapsed_seconds", 0) | |
| err = r.get("error", "Unknown") | |
| lines.append(f" {r['ticker']:8s} {t:6.1f}s {err}") | |
| lines.append("") | |
| lines.append("=" * 60) | |
| with open(path, "w") as f: | |
| f.write("\n".join(lines) + "\n") | |
| def parse_tickers(text: str) -> list[str]: | |
| """ | |
| Parse ticker input β supports comma-separated, newline-separated, or mixed. | |
| Returns deduplicated list preserving order. | |
| """ | |
| # Replace commas and newlines with spaces, then split | |
| normalized = text.replace(",", " ").replace("\n", " ").replace("\r", " ") | |
| raw = [t.strip().upper() for t in normalized.split() if t.strip()] | |
| # Deduplicate preserving order | |
| seen = set() | |
| result = [] | |
| for t in raw: | |
| if t not in seen: | |
| seen.add(t) | |
| result.append(t) | |
| return result | |