File size: 11,814 Bytes
ff4becd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
"""Step 10 – News collection.

Collects two categories of news data:

  Part A: Per-ticker news & press releases via YFinance (FREE, recent only).
  Part B: Per-scenario event-specific news via Firecrawl (date-targeted)
          with Tavily fallback.

Output
------
  data/news/tickers/{TICKER}.json   -- per-ticker yfinance news + press
  data/news/scenarios/{scenario_id}.json -- per-scenario Firecrawl/Tavily

Resume: skips if output file already exists.
"""

from __future__ import annotations

import asyncio
import json
import logging
import os
import time
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path

import pandas as pd
from dotenv import load_dotenv

from projects.agent_builder.scripts.whatif_bench import config

load_dotenv()

logger = logging.getLogger(__name__)

# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------

def _ensure_dirs() -> tuple[Path, Path]:
    """Create news output directories and return (tickers_dir, scenarios_dir)."""
    tickers_dir = config.NEWS_DIR / "tickers"
    scenarios_dir = config.NEWS_DIR / "scenarios"
    tickers_dir.mkdir(parents=True, exist_ok=True)
    scenarios_dir.mkdir(parents=True, exist_ok=True)
    return tickers_dir, scenarios_dir


# ---------------------------------------------------------------------------
# Part A – Per-ticker news + press releases (yfinance, FREE)
# ---------------------------------------------------------------------------

def _collect_single_ticker_news(ticker: str, tickers_dir: Path, client) -> int:
    """Fetch news + press releases for a single ticker. Returns article count."""
    out_path = tickers_dir / f"{ticker}.json"
    if out_path.exists():
        return 0  # resume: already collected

    articles: list[dict] = []
    any_success = False

    for tab in ("news", "press releases"):
        for attempt in range(3):
            try:
                result = client.fetch_news_from_single_ticker(
                    ticker, tab=tab, count=config.NEWS_PER_TICKER_COUNT,
                )
                articles.extend([item.model_dump(mode="json") for item in result.root])
                any_success = True
                break
            except Exception:
                if attempt == 2:
                    logger.warning("Failed to fetch %s tab=%s after 3 attempts", ticker, tab)
                else:
                    time.sleep(2 ** attempt)

    # Fallback: if yfinance returned nothing, try Tavily for per-ticker news.
    # Tavily is a paid API but handles obscure small-caps better than yfinance.
    if not articles:
        tavily_key = os.environ.get("TAVILY_API_KEY", "")
        if tavily_key:
            try:
                from tavily import TavilyClient
                tv = TavilyClient(api_key=tavily_key)
                tv_results = tv.search(
                    query=f"{ticker} stock news financial",
                    search_depth="basic",
                    max_results=config.NEWS_PER_TICKER_COUNT,
                    topic="news",
                )
                for item in tv_results.get("results", []):
                    articles.append({
                        "source": "tavily",
                        "title": item.get("title", ""),
                        "url": item.get("url", ""),
                        "snippet": item.get("content", ""),
                        "date": item.get("published_date", ""),
                    })
                if articles:
                    any_success = True
                    logger.info("Tavily fallback for %s: %d articles", ticker, len(articles))
            except Exception as exc:
                logger.debug("Tavily fallback failed for %s: %s", ticker, exc)

    # Only write the file if at least one tab succeeded.
    # If ALL tabs failed, do NOT write — leave the file missing so it's retried next run.
    if any_success:
        tmp_path = out_path.with_suffix(".json.tmp")
        tmp_path.write_text(json.dumps(articles, default=str), encoding="utf-8")
        tmp_path.replace(out_path)  # atomic rename
    else:
        logger.warning("All tabs failed for %s — NOT writing file (will retry next run)", ticker)

    return len(articles)


# Shared lock to enforce actual rate limiting across threads
import threading
_rate_lock = threading.Lock()
_last_request_time = 0.0


def _rate_limited_worker(ticker: str, tickers_dir: Path, client) -> int:
    """Worker that enforces sequential rate limiting via a shared lock."""
    global _last_request_time
    with _rate_lock:
        elapsed = time.time() - _last_request_time
        if elapsed < config.NEWS_RATE_LIMIT_SEC:
            time.sleep(config.NEWS_RATE_LIMIT_SEC - elapsed)
        _last_request_time = time.time()
    return _collect_single_ticker_news(ticker, tickers_dir, client)


def _run_part_a(tickers: list[str], tickers_dir: Path) -> None:
    """Parallel per-ticker news collection with proper rate limiting."""
    logger.info("Part A: collecting per-ticker news for %d tickers …", len(tickers))

    from concurrent.futures import as_completed
    from projects.tools.finance.yahoo import YFinanceClient

    # Single shared client for connection reuse
    client = YFinanceClient()
    total_articles = 0
    done = 0

    with ThreadPoolExecutor(max_workers=config.NEWS_WORKERS) as pool:
        futures = {pool.submit(_rate_limited_worker, t, tickers_dir, client): t for t in tickers}
        for future in as_completed(futures):
            ticker = futures[future]
            try:
                n = future.result()
                total_articles += n
            except Exception:
                logger.exception("Error collecting news for %s", ticker)
            done += 1
            if done % 200 == 0:
                logger.info("  Part A progress: %d / %d tickers", done, len(tickers))

    logger.info("Part A complete: %d articles across %d tickers", total_articles, len(tickers))


# ---------------------------------------------------------------------------
# Part B – Scenario-event news (Firecrawl + Tavily fallback)
# ---------------------------------------------------------------------------

async def _collect_single_scenario_news(
    scenario: dict,
    scenarios_dir: Path,
    firecrawl_client,
    tavily_client,
) -> int:
    """Fetch news for a single scenario event. Returns article count."""
    sc_id = scenario["scenario_id"]
    out_path = scenarios_dir / f"{sc_id}.json"
    if out_path.exists():
        return 0

    event_date = pd.Timestamp(scenario["event_date"])
    # Wider window (±30 days) — narrow windows return empty from news APIs
    start = (event_date - pd.Timedelta(days=30)).strftime("%-m/%-d/%Y")
    end = (event_date + pd.Timedelta(days=30)).strftime("%-m/%-d/%Y")
    tbs = f"cdr:1,cd_min:{start},cd_max:{end}"
    # Simplify query: use event_type keywords + date, not full description
    event_type = scenario.get("event_type", "").replace("_", " ")
    year_month = event_date.strftime("%B %Y")
    query = f"{event_type} {year_month} financial markets impact"

    articles: list[dict] = []

    # Try Firecrawl first
    try:
        fc_results = await firecrawl_client._search(
            query=query,
            limit=config.NEWS_SCENARIO_LIMIT,
            sources=["news"],
            categories=[],
            tbs=tbs,
        )
        if fc_results and hasattr(fc_results, "news") and fc_results.news:
            for item in fc_results.news:
                articles.append({
                    "source": "firecrawl",
                    "title": getattr(item, "title", ""),
                    "url": getattr(item, "url", ""),
                    "snippet": getattr(item, "snippet", getattr(item, "description", "")),
                    "date": getattr(item, "date", ""),
                })
    except Exception:
        logger.warning("Firecrawl failed for scenario %s, trying Tavily", sc_id)

    # Tavily fallback if Firecrawl returned nothing
    if not articles and tavily_client is not None:
        try:
            tv_results = await tavily_client._search(
                query=query,
                search_depth="advanced",
                include_raw_content=True,
                max_results=config.NEWS_SCENARIO_LIMIT,
            )
            for item in tv_results.get("results", []):
                articles.append({
                    "source": "tavily",
                    "title": item.get("title", ""),
                    "url": item.get("url", ""),
                    "snippet": item.get("content", ""),
                    "date": item.get("published_date", ""),
                    "raw_content": item.get("raw_content", ""),
                })
        except Exception:
            logger.warning("Tavily also failed for scenario %s", sc_id)

    out_path.write_text(json.dumps(articles, default=str), encoding="utf-8")
    return len(articles)


async def _run_part_b(scenarios_dir: Path) -> None:
    """Async per-scenario news collection."""
    # Load scenarios
    benchmark_dir = config.get_benchmark_dir()
    scenarios_path = benchmark_dir / "scenarios.parquet"
    if not scenarios_path.exists():
        logger.warning("scenarios.parquet not found at %s — skipping Part B", scenarios_path)
        return

    scenarios_df = pd.read_parquet(scenarios_path)
    scenarios = scenarios_df.to_dict("records")
    logger.info("Part B: collecting scenario news for %d events …", len(scenarios))

    # Init clients
    firecrawl_api_key = os.environ.get("FIRECRAWL_API_KEY", "")
    tavily_api_key = os.environ.get("TAVILY_API_KEY", "")

    from projects.tools.web.firecrawl_search import FirecrawlClient
    from projects.tools.web.tavily_search import TavilyClient

    fc_client = FirecrawlClient(api_key=firecrawl_api_key) if firecrawl_api_key else None
    tv_client = TavilyClient(api_key=tavily_api_key) if tavily_api_key else None

    if fc_client is None and tv_client is None:
        logger.error("Neither FIRECRAWL_API_KEY nor TAVILY_API_KEY set — skipping Part B")
        return

    total = 0
    for i, sc in enumerate(scenarios):
        if fc_client is not None:
            n = await _collect_single_scenario_news(sc, scenarios_dir, fc_client, tv_client)
        elif tv_client is not None:
            n = await _collect_single_scenario_news(sc, scenarios_dir, None, tv_client)
        else:
            n = 0
        total += n
        await asyncio.sleep(config.NEWS_RATE_LIMIT_SEC)
        if (i + 1) % 10 == 0:
            logger.info("  Part B progress: %d / %d scenarios", i + 1, len(scenarios))

    logger.info("Part B complete: %d articles across %d scenarios", total, len(scenarios))


# ---------------------------------------------------------------------------
# Public entry points
# ---------------------------------------------------------------------------

async def run_async(tickers: list[str] | None = None) -> None:
    """Run both Part A and Part B news collection.

    Parameters
    ----------
    tickers : list[str] | None
        Ticker symbols for Part A. If None, reads from universe CSV.
    """
    tickers_dir, scenarios_dir = _ensure_dirs()

    # Resolve tickers
    if tickers is None:
        universe_path = config.UNIVERSE_DIR / "benchmark_universe.csv"
        if universe_path.exists():
            tickers = pd.read_csv(universe_path)["ticker"].tolist()
        else:
            logger.error("No tickers provided and universe CSV not found")
            return

    # Part A: synchronous (uses ThreadPoolExecutor internally)
    _run_part_a(tickers, tickers_dir)

    # Part B: async
    await _run_part_b(scenarios_dir)

    logger.info("News collection complete.")