Download code/collect_news.py from DeepAuto-AI/MacroLens: direct link, hf CLI and curl.
- Browser
- Download file 11.8 kB
-
https://huggingface.co/datasets/DeepAuto-AI/MacroLens/resolve/main/code/collect_news.py
- Command line
-
hf download hf://datasets/DeepAuto-AI/MacroLens/code/collect_news.py
-
curl -L -o collect_news.py https://huggingface.co/datasets/DeepAuto-AI/MacroLens/resolve/main/code/collect_news.py
11.8 kB
| """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.") | |