File size: 8,428 Bytes
48cf766
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
"""
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