| """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__) |
|
|
| |
| |
| |
|
|
| 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 |
|
|
|
|
| |
| |
| |
|
|
| 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 |
|
|
| 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) |
|
|
| |
| |
| 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) |
|
|
| |
| |
| 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) |
| else: |
| logger.warning("All tabs failed for %s — NOT writing file (will retry next run)", ticker) |
|
|
| return len(articles) |
|
|
|
|
| |
| 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 |
|
|
| |
| 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)) |
|
|
|
|
| |
| |
| |
|
|
| 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"]) |
| |
| 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}" |
| |
| 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: |
| 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) |
|
|
| |
| 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.""" |
| |
| 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)) |
|
|
| |
| 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)) |
|
|
|
|
| |
| |
| |
|
|
| 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() |
|
|
| |
| 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 |
|
|
| |
| _run_part_a(tickers, tickers_dir) |
|
|
| |
| await _run_part_b(scenarios_dir) |
|
|
| logger.info("News collection complete.") |
|
|