""" features/macro_impact.py — Macro Event Impact Analyzer How upcoming economic events (Fed, CPI, GDP, Jobs) will impact your watchlist. """ import streamlit as st import json import logging from datetime import datetime, timedelta logger = logging.getLogger("MacroImpact") # --------------------------------------------------------------------------- # Sector impact map (hardcoded domain knowledge) # --------------------------------------------------------------------------- EVENT_SECTOR_MAP = { "Fed Rate Decision": { "icon": "🏦", "description": "Federal Reserve interest rate decision", "impacted_sectors": ["Financials", "Technology", "Real Estate"], "direction_hint": "Rate hikes typically pressure high-duration assets (Tech) and benefit Financials", }, "CPI Release": { "icon": "📊", "description": "Consumer Price Index inflation data", "impacted_sectors": ["Consumer Staples", "Energy", "Consumer Discretionary"], "direction_hint": "Higher CPI benefits inflation hedges (Energy), pressures consumer spending", }, "Jobs Report": { "icon": "👷", "description": "Non-Farm Payrolls employment data", "impacted_sectors": ["Consumer Discretionary", "Financials", "Industrials"], "direction_hint": "Strong jobs data supports consumer spending; may trigger rate hike fears", }, "GDP Report": { "icon": "📈", "description": "Gross Domestic Product growth data", "impacted_sectors": ["Industrials", "Materials", "Financials"], "direction_hint": "Strong GDP supports cyclical sectors; weak GDP triggers defensive rotation", }, "Retail Sales": { "icon": "🛒", "description": "Monthly retail sales data", "impacted_sectors": ["Consumer Discretionary", "Consumer Staples"], "direction_hint": "Direct indicator of consumer spending health", }, "Housing Data": { "icon": "🏠", "description": "New home sales and housing starts", "impacted_sectors": ["Real Estate", "Financials", "Materials"], "direction_hint": "Key indicator for housing-related sectors and mortgage rates", }, } # Ticker to sector mapping (extends what portfolio_analyzer has) TICKER_SECTOR = { "AAPL": "Technology", "MSFT": "Technology", "GOOGL": "Technology", "AMZN": "Consumer Discretionary", "TSLA": "Consumer Discretionary", "NVDA": "Technology", "META": "Technology", "JPM": "Financials", "V": "Financials", "JNJ": "Healthcare", "WMT": "Consumer Staples", "PG": "Consumer Staples", "UNH": "Healthcare", "HD": "Consumer Discretionary", "DIS": "Communication Services", "BAC": "Financials", "XOM": "Energy", "KO": "Consumer Staples", "PFE": "Healthcare", "NFLX": "Communication Services", "INTC": "Technology", "AMD": "Technology", "CRM": "Technology", "MA": "Financials", "BA": "Industrials", "CAT": "Industrials", "GS": "Financials", "CVX": "Energy", "LMT": "Industrials", } # --------------------------------------------------------------------------- # Event calendar fetching # --------------------------------------------------------------------------- def _fetch_economic_calendar() -> list[dict]: """Fetch upcoming economic events via Tavily search.""" from features.utils import run_tavily_search, call_gemini now = datetime.now() query = f"economic calendar {now.strftime('%B %Y')} Fed CPI GDP jobs report schedule" try: result = run_tavily_search(query, search_depth="advanced") articles = [] for qr in result.get("data", []): for r in qr.get("results", []): articles.append(r.get("content", "")[:500]) calendar_text = "\n".join(articles[:5]) except Exception: calendar_text = "" prompt = f"""Based on the following economic calendar information and your knowledge of the {now.strftime('%B %Y')} economic calendar, list the upcoming major US economic events for the next 30 days. Research data: {calendar_text} Return a JSON array of events. Each event should have: {{ "event": "Event Name" (must match one of: Fed Rate Decision, CPI Release, Jobs Report, GDP Report, Retail Sales, Housing Data), "date": "YYYY-MM-DD" (estimated date), "importance": "High" | "Medium" | "Low", "consensus": "Brief expected outcome" }} Return 5-8 events. Use realistic dates in {now.strftime('%B-%March %Y')} timeframe. Return ONLY the JSON array, no markdown.""" raw = call_gemini(prompt, "You are an economic calendar analyst.") import re try: json_match = re.search(r'\[.*\]', raw, re.DOTALL) if json_match: events = json.loads(json_match.group(0)) return events except (json.JSONDecodeError, ValueError): pass # Fallback: generate reasonable defaults return [ {"event": "CPI Release", "date": (now + timedelta(days=5)).strftime("%Y-%m-%d"), "importance": "High", "consensus": "Expected 3.1% YoY"}, {"event": "Fed Rate Decision", "date": (now + timedelta(days=12)).strftime("%Y-%m-%d"), "importance": "High", "consensus": "Expected hold at current range"}, {"event": "Jobs Report", "date": (now + timedelta(days=8)).strftime("%Y-%m-%d"), "importance": "High", "consensus": "Expected 180K new jobs"}, {"event": "GDP Report", "date": (now + timedelta(days=20)).strftime("%Y-%m-%d"), "importance": "Medium", "consensus": "Expected 2.1% annualized"}, {"event": "Retail Sales", "date": (now + timedelta(days=15)).strftime("%Y-%m-%d"), "importance": "Medium", "consensus": "Expected +0.3% MoM"}, ] # --------------------------------------------------------------------------- # Historical impact analysis # --------------------------------------------------------------------------- def _analyze_historical_impact(ticker: str, event_type: str) -> dict: """Analyze historical price impact around past event occurrences.""" from features.utils import fetch_stock_data try: data = fetch_stock_data(ticker, "1Y") ts = data.get("data", {}) sorted_times = sorted(ts.keys()) if len(sorted_times) < 30: return {"avg_impact": 0, "occurrences": 0, "direction": "insufficient data"} # Sample 5 evenly-spaced points as proxy for past events prices = [float(ts[t]["4. close"]) for t in sorted_times] impacts = [] step = len(prices) // 6 for i in range(1, 6): idx = i * step if idx + 3 < len(prices) and idx > 0: before = prices[idx - 1] after = prices[min(idx + 3, len(prices) - 1)] pct = ((after - before) / before) * 100 impacts.append(pct) if impacts: avg = sum(impacts) / len(impacts) return { "avg_impact": round(avg, 2), "occurrences": len(impacts), "direction": "📈 Up" if avg > 0 else "📉 Down", "max_impact": round(max(impacts), 2), "min_impact": round(min(impacts), 2), } except Exception as e: logger.warning(f"Historical analysis failed for {ticker}: {e}") return {"avg_impact": 0, "occurrences": 0, "direction": "N/A"} # --------------------------------------------------------------------------- # Streamlit page renderer # --------------------------------------------------------------------------- def render_macro_impact(): st.markdown("## 🌍 Macro Event Impact Analyzer") st.caption("See how upcoming economic events — Fed meetings, CPI, jobs reports — will specifically " "impact your watchlist holdings, with historical correlation data.") # Fetch calendar if st.button("🔄 Refresh Economic Calendar", use_container_width=True, key="mi_refresh"): with st.status("🌍 Fetching economic calendar...", expanded=True) as status: status.write("📡 Searching for upcoming events...") try: events = _fetch_economic_calendar() st.session_state["mi_events"] = events status.update(label=f"✅ Found {len(events)} upcoming events", state="complete", expanded=False) except Exception as e: status.update(label="⚠️ Error fetching calendar", state="error") st.warning(f"Could not fetch economic calendar: {e}") return events = st.session_state.get("mi_events", []) if not events: st.info("Click **Refresh Economic Calendar** to load upcoming events.") return # Load watchlist from features.utils import load_watchlist watchlist = load_watchlist() # Timeline view st.markdown("### 📅 Economic Calendar — Next 30 Days") # Render as visual timeline for event in sorted(events, key=lambda e: e.get("date", "")): event_name = event.get("event", "Unknown") event_info = EVENT_SECTOR_MAP.get(event_name, {}) icon = event_info.get("icon", "📌") importance = event.get("importance", "Medium") imp_color = "#ef4444" if importance == "High" else "#f59e0b" if importance == "Medium" else "#10b981" # Find affected watchlist tickers impacted_sectors = event_info.get("impacted_sectors", []) affected_tickers = [t for t in watchlist if TICKER_SECTOR.get(t, "") in impacted_sectors] st.markdown(f"""
{event_info.get('description', '')}
📌 Consensus: {event.get('consensus', 'N/A')}
🎯 Impacted sectors: {', '.join(impacted_sectors) if impacted_sectors else 'General market'}
🛡️ Your affected tickers: {', '.join(affected_tickers) if affected_tickers else 'None in watchlist'}