""" Macro Intel Module (macro_intel.py) — Phase 2 Builds a weekly UK macro indicator pack for the digest / briefing layer. Output mirrors the top of the user's manual benchmark: 4-8 quantified bullets per week covering rates, labour market, business distress, sector tailwinds, and sentiment. Design notes - No new API keys. Reuses feedparser + a few free, public UK macro feeds (Bank of England, ONS bulletins, BBC Business, Sky Business) plus a topic filter for macro-flavoured items in our existing RSS feeds (CIPD, IoD, KPMG/REC). - One LLM batch call per run extracts structured indicators with source URLs — no free-text bullets, so the digest can render them cleanly and we can audit later. - Cached in `macro_pulse` (week_start UNIQUE per indicator). Calling generate_macro_pulse() again in the same week upserts. """ from __future__ import annotations import os import json import sqlite3 from datetime import datetime, timedelta, date from pathlib import Path from typing import Optional, Callable import feedparser from dotenv import load_dotenv env_path = Path(__file__).parent / '.env' load_dotenv(dotenv_path=env_path, override=True) DATABASE = "leads.db" # --------------------------------------------------------------------------- # Macro feed list — free, no-key, UK-centric # --------------------------------------------------------------------------- MACRO_FEEDS = [ # Central bank — rate decisions, financial stability, market data {"name": "Bank of England", "url": "https://www.bankofengland.co.uk/rss/news"}, {"name": "BoE Statistics", "url": "https://www.bankofengland.co.uk/rss/statistics"}, # Government / fiscal — Treasury announcements, OBR fiscal reports {"name": "HM Treasury", "url": "https://www.gov.uk/government/organisations/hm-treasury.atom"}, {"name": "OBR", "url": "https://obr.uk/feed/"}, # National statistics — labour market, GDP, CPI bulletins {"name": "ONS releases", "url": "https://www.ons.gov.uk/releasecalendar?rss"}, # General-business feeds — filtered for macro {"name": "BBC Business", "url": "http://feeds.bbci.co.uk/news/business/rss.xml"}, {"name": "Sky News Business", "url": "https://feeds.skynews.com/feeds/rss/business.xml"}, {"name": "FT UK", "url": "https://www.ft.com/rss/home/uk"}, {"name": "Guardian Business", "url": "https://www.theguardian.com/uk/business/rss"}, {"name": "Economist Britain", "url": "https://www.economist.com/britain/rss.xml"}, {"name": "Economist F&E", "url": "https://www.economist.com/finance-and-economics/rss.xml"}, # Labour market specialists (Personnel Today returns 200; CIPD/Reuters # were dropped — Reuters returns 401, CIPD's RSS now redirects to 0 items) {"name": "Personnel Today", "url": "https://www.personneltoday.com/feed/"}, # Construction / industry health (mirrors the manual benchmark's # construction-PMI angle on input costs and admins) {"name": "Construction News", "url": "https://www.constructionnews.co.uk/feed/"}, {"name": "Building", "url": "https://www.building.co.uk/rss"}, ] # Macro keyword filter — applied to general business feeds where most # items are company-specific. Bank of England / ONS feeds skip this. MACRO_KEYWORDS = [ # Rates / yields "interest rate", "base rate", "bank rate", "rate cut", "rate rise", "gilt", "gilt yield", "borrowing cost", # Inflation "inflation", "CPI", "RPI", "price index", # Labour market "unemployment", "labour market", "labor market", "wage growth", "vacancies", "redundancies", "hiring freeze", "headcount", "graduate hiring", "job market", "payroll", "earnings", # GDP / growth "GDP", "recession", "growth forecast", "economic outlook", "PMI", "purchasing managers", # Business confidence / distress "business confidence", "consumer confidence", "IoD", "financial distress", "insolvency", "administration", "profit warning", "corporate distress", # Construction / industry "construction output", "construction costs", "input cost", "manufacturing output", # Government finances "borrowing", "fiscal", "Budget", "Autumn Statement", "Spring Statement", "tax rise", "national insurance", ] # Curium-relevance hint — surfaced to the LLM so it interprets each # indicator with sales-context rather than generic news. CURIUM_RELEVANCE_HINT = ( "Curium Solutions is a UK transformation consultancy (programme delivery, " "change, M&A integration, leadership development, culture). Bias the " "`implication` field toward what each indicator means for our buyers — " "CHROs, CTOs, CFOs, Programme Directors. Examples: rising borrowing " "costs → cost-out programmes; hiring freezes → workforce restructuring; " "business distress → turnaround programmes." ) def _is_macro_relevant(text: str, source: str) -> bool: """Filter applied to general business feeds. Official statistics / central-bank / fiscal-authority feeds skip this — by definition everything they publish is macro-relevant.""" if source in ( "Bank of England", "BoE Statistics", "ONS releases", "HM Treasury", "OBR", ): return True t = (text or "").lower() return any(kw.lower() in t for kw in MACRO_KEYWORDS) def _date_within(pub_struct, days: int) -> bool: if not pub_struct: return True # be tolerant — undated items kept try: pub_dt = datetime(*pub_struct[:6]) except (TypeError, ValueError): return True return pub_dt >= (datetime.now() - timedelta(days=days)) def fetch_macro_items(days: int = 7, progress_cb: Optional[Callable[[str], None]] = None) -> list[dict]: """Pull recent macro-relevant items from the feed list.""" out = [] for feed_cfg in MACRO_FEEDS: name, url = feed_cfg["name"], feed_cfg["url"] if progress_cb: progress_cb(f"macro: fetching {name}…") try: feed = feedparser.parse( url, request_headers={"User-Agent": "Mozilla/5.0 CuriumMacroIntel"}, ) except Exception as e: if progress_cb: progress_cb(f"macro {name}: failed ({type(e).__name__})") continue kept = 0 for entry in (feed.entries or [])[:40]: title = (getattr(entry, "title", "") or "").strip() summary = (getattr(entry, "summary", "") or "").strip() link = (getattr(entry, "link", "") or "").strip() pub_struct = (getattr(entry, "published_parsed", None) or getattr(entry, "updated_parsed", None)) if not _date_within(pub_struct, days): continue body = f"{title}\n{summary}" if not _is_macro_relevant(body, name): continue date_str = "" if pub_struct: try: date_str = datetime(*pub_struct[:6]).date().isoformat() except (TypeError, ValueError): pass out.append({ "title": title[:300], "summary": summary[:600], "url": link, "source": name, "date": date_str, }) kept += 1 if progress_cb: progress_cb(f"macro {name}: {kept} relevant items") return out # --------------------------------------------------------------------------- # LLM extraction # --------------------------------------------------------------------------- SYSTEM_PROMPT = """You are a UK macro analyst writing a weekly indicator pack for a transformation consultancy's sales team. You will receive a list of recent UK macro-flavoured news items. Your job is to extract 4-8 QUANTIFIED indicators that a Sales Director would want at the top of a Monday digest. Format mirrors the top of an FT or Reuters macro brief: each bullet leads with a number. Strict rules: - Every bullet MUST have a number or quantified change (rate %, yield %, headcount %, distress count, growth %, deadline, £/$ figure). - No editorialising. No "This is a sign of…", no "we believe…", no future-tense speculation. - `implication` is one short sentence linking the indicator to a transformation/people-services buying context (Curium hint provided). - Skip company-specific news entirely — that goes elsewhere in the digest. - Skip duplicates: if 3 articles all cover the BoE rate decision, pick the most authoritative source and emit ONE indicator. - If there are fewer than 4 quantified indicators in the input, return only what you have. Do NOT invent. Output format — ONLY a JSON array, no other text: [ { "category": "rates|labour|distress|sector|sentiment|other", "indicator": "", "value_text": "", "value_numeric": , "unit": "%|£m|£bn|people|null", "change_text": "", "implication": "", "source": "", "source_url": "" } ]""" def _generate_bullets_via_llm(items: list[dict], progress_cb: Optional[Callable[[str], None]] = None ) -> list[dict]: """One Claude call. Returns sanitized list of indicator dicts.""" if not items: return [] api_key = os.environ.get("ANTHROPIC_API_KEY") if not api_key: if progress_cb: progress_cb("macro: ANTHROPIC_API_KEY not set, skipping LLM step") return [] from anthropic import Anthropic client = Anthropic(api_key=api_key) # Cap input — feedparser sometimes returns 200 items per feed items = items[:60] bullet_text = "\n\n".join( f"--- ITEM {i+1} ({it['source']}, {it.get('date','')}) ---\n" f"Title: {it['title']}\n" f"Summary: {it['summary']}\n" f"URL: {it['url']}" for i, it in enumerate(items) ) user_msg = ( f"{CURIUM_RELEVANCE_HINT}\n\n" f"Here are {len(items)} UK macro-flavoured news items from the last 7 days. " f"Extract 4-8 quantified indicators following the rules in your system prompt.\n\n" f"{bullet_text}" ) if progress_cb: progress_cb(f"macro: LLM extracting from {len(items)} items…") try: message = client.messages.create( model="claude-sonnet-4-20250514", max_tokens=4000, system=SYSTEM_PROMPT, messages=[{"role": "user", "content": user_msg}], ) except Exception as e: if progress_cb: progress_cb(f"macro: LLM call failed: {e}") return [] text = message.content[0].text.strip() if text.startswith("```"): lines = text.split("\n") if lines[0].startswith("```"): lines = lines[1:] if lines and lines[-1].strip() == "```": lines = lines[:-1] text = "\n".join(lines).strip() try: raw = json.loads(text) except json.JSONDecodeError: if progress_cb: progress_cb(f"macro: LLM returned non-JSON: {text[:120]}") return [] if not isinstance(raw, list): return [] import re as _re # An indicator without a real number is just an editorial line — # reject it. We require either an explicit digit somewhere in # value_text OR a parseable value_numeric. _has_digit = _re.compile(r"\d") cleaned = [] dropped_no_number = 0 for r in raw: if not isinstance(r, dict): continue indicator = (r.get("indicator") or "").strip()[:200] value_text = (r.get("value_text") or "").strip()[:80] if not indicator or not value_text: continue cat = (r.get("category") or "other").lower().strip() if cat not in {"rates", "labour", "distress", "sector", "sentiment", "other"}: cat = "other" v_num = r.get("value_numeric") if isinstance(v_num, str): try: v_num = float(v_num.replace(",", "")) except ValueError: v_num = None # Enforce "every bullet must have a number" — the manual benchmark's # whole point is quantified facts. Editorial-only bullets get dropped. if not _has_digit.search(value_text) and not isinstance(v_num, (int, float)): dropped_no_number += 1 continue cleaned.append({ "category": cat, "indicator": indicator, "value_text": value_text, "value_numeric": v_num if isinstance(v_num, (int, float)) else None, "unit": (r.get("unit") or None), "change_text": (r.get("change_text") or "")[:200] or None, "implication": (r.get("implication") or "")[:300] or None, "source": (r.get("source") or "")[:80], "source_url": (r.get("source_url") or "")[:500], }) if dropped_no_number and progress_cb: progress_cb(f"macro: dropped {dropped_no_number} non-quantified indicators") return cleaned[:10] # --------------------------------------------------------------------------- # Persistence # --------------------------------------------------------------------------- def _week_start_iso(d: Optional[date] = None) -> str: """ISO Monday of the week containing `d` (defaults to today).""" d = d or date.today() return (d - timedelta(days=d.weekday())).isoformat() def store_macro_pulse(week_start: str, bullets: list[dict]) -> int: """Upsert bullets into macro_pulse for `week_start`. Returns count.""" if not bullets: return 0 conn = sqlite3.connect(DATABASE) cur = conn.cursor() now = datetime.now().isoformat() n = 0 for b in bullets: try: cur.execute(""" INSERT INTO macro_pulse (week_start, category, indicator, value_text, value_numeric, unit, change_text, implication, source, source_url, generated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT(week_start, indicator) DO UPDATE SET category=excluded.category, value_text=excluded.value_text, value_numeric=excluded.value_numeric, unit=excluded.unit, change_text=excluded.change_text, implication=excluded.implication, source=excluded.source, source_url=excluded.source_url, generated_at=excluded.generated_at """, ( week_start, b["category"], b["indicator"], b["value_text"], b["value_numeric"], b["unit"], b["change_text"], b["implication"], b["source"], b["source_url"], now, )) n += 1 except sqlite3.Error as e: print(f"macro_pulse upsert failed for {b.get('indicator')}: {e}") continue conn.commit() conn.close() return n def get_macro_pulse(week_start: Optional[str] = None) -> list[dict]: """Read the cached pulse for a given week (defaults to current week).""" week_start = week_start or _week_start_iso() conn = sqlite3.connect(DATABASE) conn.row_factory = sqlite3.Row rows = conn.execute(""" SELECT category, indicator, value_text, value_numeric, unit, change_text, implication, source, source_url, generated_at FROM macro_pulse WHERE week_start = ? ORDER BY CASE category WHEN 'rates' THEN 1 WHEN 'labour' THEN 2 WHEN 'distress' THEN 3 WHEN 'sector' THEN 4 WHEN 'sentiment' THEN 5 ELSE 6 END, generated_at DESC """, (week_start,)).fetchall() conn.close() return [dict(r) for r in rows] # --------------------------------------------------------------------------- # Public entry point # --------------------------------------------------------------------------- def generate_macro_pulse(days: int = 7, force: bool = False, progress_cb: Optional[Callable[[str], None]] = None ) -> list[dict]: """End-to-end: fetch → LLM extract → persist → return bullets. `force=False` returns the cached pulse for this week if one exists, avoiding repeat LLM cost. Set `force=True` to regenerate. """ week_start = _week_start_iso() if not force: existing = get_macro_pulse(week_start) if existing: if progress_cb: progress_cb(f"macro: using cached pulse ({len(existing)} indicators)") return existing items = fetch_macro_items(days=days, progress_cb=progress_cb) if progress_cb: progress_cb(f"macro: {len(items)} candidate items collected") bullets = _generate_bullets_via_llm(items, progress_cb=progress_cb) stored = store_macro_pulse(week_start, bullets) if progress_cb: progress_cb(f"macro: {stored} indicators stored for week {week_start}") return bullets if __name__ == "__main__": def log(msg: str) -> None: print(f"[macro] {msg}") bullets = generate_macro_pulse(days=7, force=True, progress_cb=log) print(f"\n=== UK Macro Pulse — week of {_week_start_iso()} ===\n") for b in bullets: print(f"• [{b['category']}] {b['indicator']}: {b['value_text']}" + (f" ({b['change_text']})" if b['change_text'] else "")) if b.get("implication"): print(f" → {b['implication']}") if b.get("source_url"): print(f" {b['source']}: {b['source_url']}") print()