{
  "version": "2.0.0",
  "exportedAt": "2026-03-03T22:15:41.413Z",
  "pipeline": {
    "id": "pipeline-1768421472058",
    "name": "pipeline-1768421472058",
    "label": "Market Direction",
    "version": "1.0.0",
    "changeVersion": 1397,
    "variables": {},
    "nodes": [
      {
        "id": "node-1768421510514",
        "type": "credentials",
        "dependencies": [],
        "position": {
          "x": 1151.636381558982,
          "y": 232.27480465609358
        },
        "config": {
          "authType": "interactive",
          "clientId": "4dc2b681-f357-4a88-8cc1-059c66b457b2",
          "tenantId": "common"
        }
      },
      {
        "id": "node-1768421514730",
        "type": "web:cors-proxy",
        "dependencies": [],
        "position": {
          "x": -180.19937612384794,
          "y": 350.0390266105171
        },
        "config": {
          "provider": "local"
        }
      },
      {
        "id": "node-1768421535857",
        "type": "web:request",
        "dependencies": [],
        "position": {
          "x": 163.1181871455486,
          "y": 255.63962816053578
        },
        "config": {
          "url": "https://stooq.com/q/d/l/?s=msft.us&i=d",
          "method": "GET",
          "authType": "anonymous",
          "enableCache": true,
          "cacheTTL": 6000
        },
        "label": "Historical MSFT"
      },
      {
        "id": "node-1768421882343",
        "type": "web:request",
        "dependencies": [],
        "position": {
          "x": 161.78229368051134,
          "y": 430.9266945528029
        },
        "config": {
          "url": "https://stooq.com/q/d/l/?s=nvda.us&i=d",
          "method": "GET",
          "authType": "anonymous",
          "enableCache": true,
          "cacheTTL": 6003
        },
        "label": "Historical Nvidia"
      },
      {
        "id": "node-1768421932193",
        "type": "web:request",
        "dependencies": [],
        "position": {
          "x": 162.65707553300263,
          "y": 607.6329013840099
        },
        "config": {
          "url": "https://stooq.com/q/d/l/?s=xom.us&i=d",
          "method": "GET",
          "authType": "anonymous",
          "enableCache": true,
          "cacheTTL": 6004
        },
        "label": "Historical Oil"
      },
      {
        "id": "node-1768421973860",
        "type": "web:request",
        "dependencies": [],
        "position": {
          "x": 165.63359881998053,
          "y": 781.1772831082262
        },
        "config": {
          "url": "https://stooq.com/q/d/l/?s=gold.us&i=d",
          "method": "GET",
          "authType": "anonymous",
          "enableCache": true,
          "cacheTTL": 6004
        },
        "label": "Historical Gold"
      },
      {
        "id": "node-1768422218683",
        "type": "transform:python",
        "dependencies": [],
        "position": {
          "x": 525.1312413993455,
          "y": 271.6671582585746
        },
        "config": {
          "code": "import csv\nimport io\nfrom datetime import datetime\nfrom typing import List, Dict, Any\n\n# --- CONFIG / MAPPINGS -------------------------------------------------------\n\nSYMBOL_ORDER = [\"MSFT\", \"NVDA\", \"XOM\", \"GC\"]\nROLES = {\n    \"MSFT\": \"growth\",\n    \"NVDA\": \"growth\",\n    \"XOM\": \"cyclical\",\n    \"GC\": \"hedge\",\n}\n\n# Equal weights for now (we'll promote to variables later)\nWEIGHTS = {sym: 1.0 / len(SYMBOL_ORDER) for sym in SYMBOL_ORDER}\n\nMAX_DAYS = 250  # how many daily candles to keep\n\n\n# --- CSV PARSING -------------------------------------------------------------\n\ndef parse_stooq_csv(csv_text: str, max_days: int = MAX_DAYS) -> List[Dict[str, Any]]:\n    \"\"\"\n    Parse Stooq CSV into a list of rows (dicts) sorted by date ascending.\n    Only keep the last max_days rows.\n    Expected columns: Date,Open,High,Low,Close,Volume\n    \"\"\"\n    if not csv_text:\n        return []\n\n    f = io.StringIO(csv_text)\n    reader = csv.DictReader(f)\n\n    rows = []\n    for row in reader:\n        # Let errors bubble up, outer pipeline will catch\n        dt = datetime.strptime(row[\"Date\"], \"%Y-%m-%d\").date()\n        rows.append({\n            \"date\": dt.isoformat(),\n            \"open\": float(row[\"Open\"]),\n            \"high\": float(row[\"High\"]),\n            \"low\": float(row[\"Low\"]),\n            \"close\": float(row[\"Close\"]),\n            \"volume\": float(row.get(\"Volume\", 0.0) or 0.0),\n        })\n\n    # Sort ascending by date just in case\n    rows.sort(key=lambda r: r[\"date\"])\n\n    if max_days and len(rows) > max_days:\n        rows = rows[-max_days:]\n\n    return rows\n\n\n# --- METRIC + LABELING HELPERS ----------------------------------------------\n\ndef percent_return(new: float, old: float) -> float:\n    \"\"\"\n    Return percentage move in percentage points.\n    Example: new=102, old=100 -> 2.0 (i.e., +2%)\n    \"\"\"\n    if old == 0:\n        return 0.0\n    return (new - old) / old * 100.0\n\n\ndef compute_trend(closes: List[float], lookback: int) -> float:\n    if len(closes) <= lookback:\n        return 0.0\n    start = closes[-(lookback + 1)]\n    end = closes[-1]\n    return percent_return(end, start)\n\n\ndef label_today(move_pct: float) -> str:\n    \"\"\"\n    Label based on today's percentage move in percentage points.\n    Thresholds chosen to be intuitive; tweak if needed.\n    \"\"\"\n    if move_pct >= 2.0:\n        return \"strong_up\"\n    elif move_pct >= 0.5:\n        return \"up\"\n    elif move_pct <= -2.0:\n        return \"strong_down\"\n    elif move_pct <= -0.5:\n        return \"down\"\n    else:\n        return \"flat\"\n\n\ndef label_trend(trend_20d: float) -> str:\n    \"\"\"\n    Use 20d trend as main direction signal.\n    \"\"\"\n    if trend_20d >= 5.0:\n        return \"up_trend\"\n    elif trend_20d <= -5.0:\n        return \"down_trend\"\n    else:\n        return \"sideways\"\n\n\ndef label_volatility(day_range_pct: float) -> str:\n    \"\"\"\n    day_range_pct in percentage points (e.g., 1.5 = +1.5% intraday range).\n    \"\"\"\n    if day_range_pct <= 1.0:\n        return \"quiet\"\n    elif day_range_pct <= 3.0:\n        return \"normal\"\n    else:\n        return \"volatile\"\n\n\n# --- REGIME + ROTATION -------------------------------------------------------\n\ndef infer_regime(asset_moves: Dict[str, float]) -> str:\n    \"\"\"\n    asset_moves: symbol -> % move today (percentage points).\n\n    Regime logic:\n\n    risk_on:  growth\u2191 && hedge\u2193\n    risk_off: growth\u2193 && hedge\u2191\n    sleepy:   |pct| small for all\n    else:     mixed\n    \"\"\"\n    growth_moves = [v for s, v in asset_moves.items() if ROLES.get(s) == \"growth\"]\n    hedge_moves = [v for s, v in asset_moves.items() if ROLES.get(s) == \"hedge\"]\n\n    if not asset_moves:\n        return \"mixed\"\n\n    max_abs = max(abs(v) for v in asset_moves.values())\n    if max_abs < 0.2:  # all moves smaller than +/-0.2%\n        return \"sleepy\"\n\n    avg_growth = sum(growth_moves) / len(growth_moves) if growth_moves else 0.0\n    avg_hedge = sum(hedge_moves) / len(hedge_moves) if hedge_moves else 0.0\n\n    if avg_growth > 0.0 and avg_hedge < 0.0:\n        return \"risk_on\"\n    if avg_growth < 0.0 and avg_hedge > 0.0:\n        return \"risk_off\"\n\n    return \"mixed\"\n\n\ndef infer_rotation(asset_moves: Dict[str, float]) -> str:\n    \"\"\"\n    Rotation logic:\n\n    towards_growth       if avg_growth > 0.3 and avg_cyc < -0.3\n    towards_cyclicals    if avg_growth < -0.3 and avg_cyc > 0.3\n    none                 otherwise\n\n    Thresholds in percentage points.\n    \"\"\"\n    growth_moves = [v for s, v in asset_moves.items() if ROLES.get(s) == \"growth\"]\n    cyc_moves = [v for s, v in asset_moves.items() if ROLES.get(s) == \"cyclical\"]\n\n    avg_growth = sum(growth_moves) / len(growth_moves) if growth_moves else 0.0\n    avg_cyc = sum(cyc_moves) / len(cyc_moves) if cyc_moves else 0.0\n\n    if avg_growth > 0.3 and avg_cyc < -0.3:\n        return \"towards_growth\"\n    if avg_growth < -0.3 and avg_cyc > 0.3:\n        return \"towards_cyclicals\"\n    return \"none\"\n\n\ndef compute_weighted_return(asset_moves: Dict[str, float], weights: Dict[str, float]) -> float:\n    total_weight = sum(weights.get(s, 0.0) for s in asset_moves.keys())\n    if total_weight == 0:\n        return 0.0\n    return sum(asset_moves[s] * weights.get(s, 0.0) for s in asset_moves.keys()) / total_weight\n\n\n# --- MAIN NODE LOGIC ---------------------------------------------------------\n\ndef build_output() -> Dict[str, Any]:\n    # 1) Collect CSV inputs (fixed mapping for now)\n    csv_by_symbol: Dict[str, str] = {}\n\n    for idx, sym in enumerate(SYMBOL_ORDER):\n        var_name = f\"input_{idx}\"\n        csv_text = globals().get(var_name, None)\n        if not csv_text:\n            continue\n        csv_by_symbol[sym] = csv_text\n\n    # 2) Parse Stooq CSVs\n    history_by_symbol: Dict[str, List[Dict[str, Any]]] = {}\n    for sym, csv_text in csv_by_symbol.items():\n        rows = parse_stooq_csv(csv_text, max_days=MAX_DAYS)\n        if len(rows) < 2:\n            # need at least 2 days for prev_close and %_today\n            continue\n        history_by_symbol[sym] = rows\n\n    # 3) Compute per-asset metrics\n    per_asset: Dict[str, Dict[str, Any]] = {}\n    todays_moves: Dict[str, float] = {}\n    as_of_date = None\n\n    for sym, rows in history_by_symbol.items():\n        closes = [r[\"close\"] for r in rows]\n        last_row = rows[-1]\n        prev_row = rows[-2]\n\n        last_close = last_row[\"close\"]\n        prev_close = prev_row[\"close\"]\n\n        pct_today = percent_return(last_close, prev_close)\n\n        # Using last day's OHLC for an intraday-ish range\n        day_range_pct = percent_return(last_row[\"high\"], last_row[\"low\"])\n\n        trend_5d = compute_trend(closes, 5)\n        trend_20d = compute_trend(closes, 20)\n\n        today_label = label_today(pct_today)\n        trend_label = label_trend(trend_20d)\n        vol_label = label_volatility(day_range_pct)\n\n        per_asset[sym] = {\n            \"symbol\": sym,\n            \"role\": ROLES.get(sym, \"other\"),\n            \"last_close\": last_close,\n            \"prev_close\": prev_close,\n            \"pct_today\": pct_today,\n            \"day_range_pct\": day_range_pct,\n            \"trend_5d\": trend_5d,\n            \"trend_20d\": trend_20d,\n            \"today_label\": today_label,\n            \"trend_label\": trend_label,\n            \"vol_label\": vol_label,\n            \"history\": rows,\n        }\n\n        todays_moves[sym] = pct_today\n        as_of_date = last_row[\"date\"]  # they should all share same last date\n\n    # 4) Basket-level metrics: regime, rotation, weighted return\n    regime = infer_regime(todays_moves)\n    rotation = infer_rotation(todays_moves)\n    weighted_return = compute_weighted_return(todays_moves, WEIGHTS)\n\n    basket = {\n        \"weighted_return\": weighted_return,\n        \"regime\": regime,\n        \"rotation\": rotation,\n    }\n\n    # 5) Final data structure (no chart, no Excel, no AI text yet)\n    result = {\n        \"symbols\": list(per_asset.keys()),\n        \"weights\": WEIGHTS,\n        \"as_of\": as_of_date if as_of_date else None,  # already an ISO string\n        \"per_asset\": per_asset,\n        \"basket\": basket,\n    }\n\n    return result\n\n\n# --- Final output for the node -----------------------------------------------\n\noutput = build_output()\noutput\n",
          "inputs": []
        },
        "label": "Only last 250 days"
      },
      {
        "id": "node-1768424122614",
        "type": "transform:python",
        "dependencies": [],
        "position": {
          "x": 842.523425474221,
          "y": 62.19421816749099
        },
        "config": {
          "code": "import json\nfrom typing import Dict, Any, List\n\n\ndef ensure_dict_from_input(raw) -> Dict[str, Any]:\n    \"\"\"\n    Accept either a dict (already parsed) or a JSON string and return a dict.\n    \"\"\"\n    if isinstance(raw, dict):\n        return raw\n    if raw is None:\n        return {}\n    if isinstance(raw, str):\n        raw = raw.strip()\n        if not raw:\n            return {}\n        return json.loads(raw)\n    # Fallback: try to stringify + parse\n    return json.loads(str(raw))\n\n\ndef build_output() -> Dict[str, Any]:\n    # 1) Get upstream blob from input_0\n    upstream = ensure_dict_from_input(globals().get(\"input_0\"))\n\n    symbols: List[str] = upstream.get(\"symbols\", [])\n    weights: Dict[str, float] = upstream.get(\"weights\", {})\n    as_of = upstream.get(\"as_of\")\n    per_asset = upstream.get(\"per_asset\", {}) or {}\n    basket = upstream.get(\"basket\", {}) or {}\n\n    # 2) Prepare assets subset for AI (exclude full history to keep prompt lean)\n    assets_for_ai: Dict[str, Dict[str, Any]] = {}\n\n    for sym in symbols:\n        m = per_asset.get(sym)\n        if not m:\n            continue\n\n        assets_for_ai[sym] = {\n            \"symbol\": m.get(\"symbol\"),\n            \"role\": m.get(\"role\"),\n            \"last_close\": m.get(\"last_close\"),\n            \"prev_close\": m.get(\"prev_close\"),\n            \"pct_today\": m.get(\"pct_today\"),\n            \"day_range_pct\": m.get(\"day_range_pct\"),\n            \"trend_5d\": m.get(\"trend_5d\"),\n            \"trend_20d\": m.get(\"trend_20d\"),\n            \"today_label\": m.get(\"today_label\"),\n            \"trend_label\": m.get(\"trend_label\"),\n            \"vol_label\": m.get(\"vol_label\"),\n        }\n\n    # Roles: infer from per_asset to keep it single source of truth\n    roles_map: Dict[str, str] = {}\n    for sym, m in per_asset.items():\n        role = m.get(\"role\")\n        if role:\n            roles_map[sym] = role\n\n    # 3) Build narration_input for the AI node\n    narration_input = {\n        \"as_of\": as_of,\n        \"assets\": assets_for_ai,\n        \"basket\": {\n            \"weighted_return\": basket.get(\"weighted_return\"),\n            \"regime\": basket.get(\"regime\"),\n            \"rotation\": basket.get(\"rotation\"),\n            \"weights\": weights,\n        },\n        \"universe\": {\n            \"symbols\": symbols,\n            \"roles\": roles_map,\n        },\n    }\n\n    # 4) Build table_rows for Excel (one per asset + basket summary row)\n    table_rows: List[Dict[str, Any]] = []\n\n    for sym in symbols:\n        m = per_asset.get(sym)\n        if not m:\n            continue\n\n        table_rows.append({\n            \"symbol\": m.get(\"symbol\"),\n            \"role\": m.get(\"role\"),\n            \"last_close\": m.get(\"last_close\"),\n            \"prev_close\": m.get(\"prev_close\"),\n            \"pct_today\": m.get(\"pct_today\"),\n            \"trend_5d\": m.get(\"trend_5d\"),\n            \"trend_20d\": m.get(\"trend_20d\"),\n            \"today_label\": m.get(\"today_label\"),\n            \"trend_label\": m.get(\"trend_label\"),\n            \"vol_label\": m.get(\"vol_label\"),\n        })\n\n    # Basket summary row \u2013 Excel can highlight this\n    table_rows.append({\n        \"symbol\": \"BASKET\",\n        \"role\": \"basket\",\n        \"last_close\": None,\n        \"prev_close\": None,\n        \"pct_today\": basket.get(\"weighted_return\"),\n        \"trend_5d\": None,\n        \"trend_20d\": None,\n        \"today_label\": basket.get(\"regime\"),\n        \"trend_label\": basket.get(\"rotation\"),\n        \"vol_label\": None,\n    })\n\n    return {\n        \"narration_input\": narration_input,\n        \"table_rows\": table_rows,\n    }\n\n\noutput = build_output()\noutput",
          "inputs": []
        },
        "label": "Get last EOD data"
      },
      {
        "id": "node-1768424266205",
        "type": "ai:evaluate",
        "dependencies": [],
        "position": {
          "x": 849.5969157376658,
          "y": 354.6917171735145
        },
        "config": {
          "apiKey": "",
          "model": "gpt-4",
          "systemPrompt": "",
          "userPrompt": "",
          "resourceName": "your-company-ai-service",
          "deploymentName": "gpt-4.1",
          "prompt": "You are a neutral, factual market commentator.\n\nYou receive structured JSON called \"narration_input\" describing a small multi-asset basket:\n- Per-asset:\n  - symbol (e.g., MSFT, NVDA, XOM, GC)\n  - role: \"growth\", \"cyclical\", or \"hedge\"\n  - last_close, prev_close\n  - pct_today (percentage move today, e.g. -1.5 = -1.5%)\n  - day_range_pct (intraday range as a percentage of the low)\n  - trend_5d, trend_20d (percentage change over those windows)\n  - today_label: strong_up / up / flat / down / strong_down\n  - trend_label: up_trend / sideways / down_trend\n  - vol_label: quiet / normal / volatile\n\n- Basket:\n  - weighted_return (percentage points for the whole basket)\n  - regime: risk_on / risk_off / mixed / sleepy\n  - rotation: none / towards_growth / towards_cyclicals\n  - weights per symbol\n\n- Universe:\n  - list of symbols\n  - roles per symbol\n\nTASK:\nWrite a concise 3\u20136 sentence intraday market summary in plain language.\nAudience: mid-office, risk-aware, not retail. \nFocus on:\n- which assets are leading/lagging today,\n- how growth vs cyclicals vs hedge behave,\n- the inferred regime (risk_on / risk_off / mixed / sleepy),\n- any rotation (e.g. towards cyclicals).\n\nRULES:\n- Do NOT give investment advice or recommendations.\n- Do NOT talk about what someone \"should\" do.\n- Do NOT invent data that is not implied by the JSON.\n- You may mention numbers approximately (e.g. \"around 2%\" or \"mid-single digits\") instead of exact decimals.\n- Do not mention the JSON structure or field names; write like a human market color note.\n\nFormat answer so that it is suitable for sending on email and display directly\n\nJSON:\n{{input0}}",
          "maxTokens": 4000
        },
        "label": "Summary of latest EOD"
      },
      {
        "id": "node-1768424390270",
        "type": "data:project",
        "dependencies": [],
        "position": {
          "x": 846.8772352351011,
          "y": 222.22311344730332
        },
        "config": {
          "fields": [
            "narration_input"
          ]
        },
        "label": "Extract for interpretation"
      },
      {
        "id": "node-1768424880329",
        "type": "email:send",
        "dependencies": [],
        "position": {
          "x": 836.1875439679418,
          "y": 636.0818957530079
        },
        "config": {
          "to": "boss@your-corp.com",
          "subject": "Todays summary"
        },
        "label": "Mail summary to corp",
        "hiddenHandles": [
          "body"
        ]
      },
      {
        "id": "node-1768461091386",
        "type": "excel:insert-image",
        "dependencies": [],
        "position": {
          "x": 829.8969240548375,
          "y": 943.1855051699359
        },
        "config": {
          "sheetName": "Dashboard",
          "cell": "H34",
          "width": 600,
          "height": 250
        },
        "label": "Add graph to Dashboard"
      },
      {
        "id": "node-1769280063720",
        "type": "flow:manual-intervention",
        "dependencies": [],
        "position": {
          "x": 849,
          "y": 504
        },
        "config": {},
        "label": "Review and modify"
      },
      {
        "id": "node-1772121212478",
        "type": "presentation:present",
        "dependencies": [],
        "position": {
          "x": 837,
          "y": 817
        },
        "config": {
          "sheetName": "Dashboard",
          "updateMode": "full",
          "description": "Create an executive summary page",
          "presentationSpec": "{\n\"layout\": { \"columns\": 12, \"startColumn\": \"B\" },\n\"theme\": {\n\"primaryColor\": \"#1B3A5C\",\n\"accentColor\": \"#2E86DE\",\n\"backgroundColor\": \"#EAF0F6\",\n\"fontFamily\": \"Segoe UI\"\n},\n\"components\": [\n{\n\"type\": \"text\",\n\"position\": { \"row\": 0, \"col\": 0, \"rowSpan\": 1, \"colSpan\": 12 },\n\"content\": \"Market Executive Summary\",\n\"style\": \"title\",\n\"color\": \"#1B3A5C\"\n},\n{\n\"type\": \"metric\",\n\"position\": { \"row\": 1, \"col\": 0, \"rowSpan\": 1, \"colSpan\": 3 },\n\"label\": \"Avg Today Move\",\n\"formula\": \"=AVERAGE(${input_1.pct_today})\",\n\"format\": \"0.00\\\"%\\\"\",\n\"style\": \"card\",\n\"valueFontSize\": 24\n},\n{\n\"type\": \"metric\",\n\"position\": { \"row\": 1, \"col\": 3, \"rowSpan\": 1, \"colSpan\": 3 },\n\"label\": \"Avg 5D Trend\",\n\"formula\": \"=AVERAGE(${input_1.trend_5d})\",\n\"format\": \"0.00\\\"%\\\"\",\n\"style\": \"card\",\n\"valueFontSize\": 24\n},\n{\n\"type\": \"metric\",\n\"position\": { \"row\": 1, \"col\": 6, \"rowSpan\": 1, \"colSpan\": 3 },\n\"label\": \"Avg 20D Trend\",\n\"formula\": \"=AVERAGE(${input_1.trend_20d})\",\n\"format\": \"0.00\\\"%\\\"\",\n\"style\": \"card\",\n\"valueFontSize\": 24\n},\n{\n\"type\": \"metric\",\n\"position\": { \"row\": 1, \"col\": 9, \"rowSpan\": 1, \"colSpan\": 3 },\n\"label\": \"Avg Intraday Range\",\n\"formula\": \"=AVERAGE(${input_1.day_range_pct})\",\n\"format\": \"0.00\\\"%\\\"\",\n\"style\": \"card\",\n\"valueFontSize\": 24\n},\n{\n\"type\": \"separator\",\n\"position\": { \"row\": 2, \"col\": 0, \"rowSpan\": 1, \"colSpan\": 12 },\n\"style\": \"space\"\n},\n{\n\"type\": \"chart\",\n\"position\": { \"row\": 3, \"col\": 0, \"rowSpan\": 1, \"colSpan\": 6 },\n\"chartType\": \"Column\",\n\"dataSource\": \"input_1\",\n\"categories\": \"symbol\",\n\"series\": [\n{ \"column\": \"pct_today\", \"label\": \"Today %\" }\n],\n\"title\": \"Intraday Performance by Asset\",\n\"axisLabels\": { \"x\": \"Asset\", \"y\": \"% Change\" },\n\"showLegend\": false,\n\"colors\": [\"#2E86DE\"]\n},\n{\n\"type\": \"chart\",\n\"position\": { \"row\": 3, \"col\": 6, \"rowSpan\": 1, \"colSpan\": 6 },\n\"chartType\": \"Column\",\n\"dataSource\": \"input_1\",\n\"categories\": \"symbol\",\n\"series\": [\n{ \"column\": \"trend_20d\", \"label\": \"20D Trend %\" }\n],\n\"title\": \"20-Day Trend by Asset\",\n\"axisLabels\": { \"x\": \"Asset\", \"y\": \"% Trend\" },\n\"showLegend\": false,\n\"colors\": [\"#1B3A5C\"]\n},\n{\n\"type\": \"separator\",\n\"position\": { \"row\": 4, \"col\": 0, \"rowSpan\": 1, \"colSpan\": 12 },\n\"style\": \"space\"\n},\n{\n\"type\": \"table\",\n\"position\": { \"row\": 5, \"col\": 0, \"rowSpan\": 1, \"colSpan\": 8 },\n\"dataSource\": \"input_1\",\n\"columns\": [\"symbol\", \"role\", \"last_close\", \"pct_today\", \"trend_5d\", \"trend_20d\", \"vol_label\"],\n\"columnLabels\": {\n\"symbol\": \"Symbol\",\n\"role\": \"Role\",\n\"last_close\": \"Last Close\",\n\"pct_today\": \"Today %\",\n\"trend_5d\": \"5D %\",\n\"trend_20d\": \"20D %\",\n\"vol_label\": \"Volatility\"\n},\n\"headerStyle\": { \"bold\": true, \"fillColor\": \"#1B3A5C\", \"fontColor\": \"#FFFFFF\", \"fontSize\": 10 },\n\"alternateRowColor\": \"#F5F7FA\",\n\"conditionalFormats\": [\n{\n\"type\": \"colorScale\",\n\"column\": \"pct_today\"\n},\n{\n\"type\": \"colorScale\",\n\"column\": \"trend_20d\"\n}\n],\n\"sortBy\": \"pct_today\",\n\"sortOrder\": \"asc\",\n\"maxRows\": 10\n},\n{\n\"type\": \"formula_cell\",\n\"position\": { \"row\": 5, \"col\": 8, \"rowSpan\": 2, \"colSpan\": 4 },\n\"label\": \"Narrative Summary\",\n\"formula\": \"=${input_0.value}\",\n\"fontSize\": 10,\n\"backgroundColor\": \"#FFFFFF\",\n\"align\": \"left\"\n}\n]\n}\n"
        },
        "label": "Summarize in sheet"
      },
      {
        "id": "transform:python-1772575864282-393",
        "type": "transform:python",
        "dependencies": [],
        "position": {
          "x": 522.0760058477471,
          "y": 499.31125665589593
        },
        "config": {
          "code": "import json\nimport io\nimport base64\nfrom datetime import datetime\nfrom typing import Dict, Any, List\n\nimport matplotlib.pyplot as plt   # fail fast if not bundled\n\n\ndef ensure_dict_from_input(raw) -> Dict[str, Any]:\n    if isinstance(raw, dict):\n        return raw\n    if raw is None:\n        return {}\n    if isinstance(raw, str):\n        raw = raw.strip()\n        if not raw:\n            return {}\n        return json.loads(raw)\n    return json.loads(str(raw))\n\n\ndef build_role_series(per_asset: Dict[str, Any],\n                      role_map: Dict[str, str],\n                      window_max_days: int = 130):\n\n    date_to_symbol_close: Dict[datetime, Dict[str, float]] = {}\n\n    for sym, meta in per_asset.items():\n        history = meta.get(\"history\", []) or []\n        for row in history:\n            d_str = row.get(\"date\")\n            c = row.get(\"close\")\n            if d_str is None or c is None:\n                continue\n            dt = datetime.strptime(d_str, \"%Y-%m-%d\")\n            if dt not in date_to_symbol_close:\n                date_to_symbol_close[dt] = {}\n            date_to_symbol_close[dt][sym] = float(c)\n\n    if not date_to_symbol_close:\n        raise ValueError(\"No historical data available to build role series.\")\n\n    all_dates = sorted(date_to_symbol_close.keys())\n\n    symbols = list(per_asset.keys())\n    last_close = {s: None for s in symbols}\n    daily_symbol_closes = {}\n\n    for dt in all_dates:\n        sym_closes = {}\n        for s in symbols:\n            if s in date_to_symbol_close[dt]:\n                last_close[s] = date_to_symbol_close[dt][s]\n            if last_close[s] is not None:\n                sym_closes[s] = last_close[s]\n        if sym_closes:\n            daily_symbol_closes[dt] = sym_closes\n\n    dates = sorted(daily_symbol_closes.keys())\n    if len(dates) > window_max_days:\n        dates = dates[-window_max_days:]\n\n    roles = set(role_map.values())\n    role_closes = {r: [] for r in roles}\n    effective_dates = []\n\n    for dt in dates:\n        sym_closes = daily_symbol_closes.get(dt, {})\n        if not sym_closes:\n            continue\n\n        role_values = {r: [] for r in roles}\n        for s, close in sym_closes.items():\n            r = role_map.get(s)\n            if r:\n                role_values[r].append(close)\n\n        if not any(role_values[r] for r in roles):\n            continue\n\n        for r in roles:\n            if role_values[r]:\n                role_closes[r].append(sum(role_values[r]) / len(role_values[r]))\n            else:\n                if role_closes[r]:\n                    role_closes[r].append(role_closes[r][-1])\n                else:\n                    role_closes[r].append(None)\n\n        effective_dates.append(dt)\n\n    return effective_dates, role_closes\n\n\ndef rebase_to_100(series: List[float]) -> List[float]:\n    base = next((v for v in series if v is not None), None)\n    if base is None:\n        raise ValueError(\"Cannot rebase series with no valid base value.\")\n    return [(v / base * 100.0 if v is not None else None) for v in series]\n\n\ndef make_chart_base64(dates: List[datetime],\n                      role_series: Dict[str, List[float]]) -> str:\n\n    if not dates or not role_series:\n        raise ValueError(\"No data available to chart.\")\n\n    fig, ax = plt.subplots(figsize=(8, 4))\n\n    fig.patch.set_alpha(0.0)\n    ax.set_facecolor(\"none\")\n\n    for role, series in role_series.items():\n        rebased = rebase_to_100(series)\n        y = [v if v is not None else float('nan') for v in rebased]\n        ax.plot(dates, y, linewidth=2, label=role)\n\n    ax.set_title(\"6-Month Indexed Role Performance (start=100)\")\n    ax.set_xlabel(\"\")\n    ax.set_ylabel(\"Index\")\n\n    ax.spines[\"top\"].set_visible(False)\n    ax.spines[\"right\"].set_visible(False)\n\n    ax.grid(True, alpha=0.2)\n    ax.legend(frameon=False)\n\n    fig.autofmt_xdate()\n    fig.tight_layout()\n\n    buf = io.BytesIO()\n    fig.savefig(buf, format=\"png\", transparent=True, dpi=200)\n\n    buf.seek(0)\n    return base64.b64encode(buf.read()).decode(\"ascii\")\n\n\ndef build_output() -> Dict[str, Any]:\n    upstream = ensure_dict_from_input(globals().get(\"input_0\"))\n    per_asset = upstream.get(\"per_asset\") or {}\n\n    if not per_asset:\n        raise ValueError(\"Historical per_asset data missing.\")\n\n    role_map = {\n        s: meta.get(\"role\")\n        for s, meta in per_asset.items()\n        if meta.get(\"role\")\n    }\n\n    dates, role_series = build_role_series(per_asset, role_map, window_max_days=130)\n    chart_base64 = make_chart_base64(dates, role_series)\n\n    return {\"chart_base64\": chart_base64}\n\n\noutput = build_output()\nchart_base64 = output[\"chart_base64\"]\n\nf\"data:image/png;base64,{chart_base64}\"",
          "inputs": [],
          "testInputs": [
            ""
          ],
          "packages": [
            "matplotlib"
          ]
        },
        "label": "Create Role Performance (Copy)"
      }
    ],
    "triggers": [
      {
        "id": "pipeline-1768421472058-trigger-manual",
        "label": "Manual",
        "type": "manual",
        "enabled": true,
        "description": "Executes when \"Run Pipeline\" button is pressed",
        "position": {
          "x": -167.49999999999972,
          "y": 76.24999999999997
        }
      },
      {
        "id": "pipeline-1768421472058-trigger-startup",
        "label": "On Startup",
        "type": "startup",
        "enabled": true,
        "description": "Executes when the workbook is opened"
      },
      {
        "id": "pipeline-1768421472058-trigger-every-5min",
        "label": "Default Timer",
        "type": "cron",
        "enabled": true,
        "cron": "0 */5 * * * *",
        "description": "Executes every 5 minutes (customizable)"
      }
    ],
    "edges": [
      {
        "source": "node-1768421514730",
        "target": "node-1768421535857",
        "sourceHandle": "proxy-out",
        "targetHandle": "proxy",
        "id": "node-1768421514730-node-1768421535857-proxy-out-proxy",
        "type": "proxy"
      },
      {
        "source": "pipeline-1768421472058-trigger-manual",
        "target": "node-1768421535857",
        "sourceHandle": "execution-out",
        "targetHandle": "execution-in",
        "id": "pipeline-1768421472058-trigger-manual-node-1768421535857-execution-out-execution",
        "type": "execution"
      },
      {
        "source": "node-1768421514730",
        "target": "node-1768421882343",
        "sourceHandle": "proxy-out",
        "targetHandle": "proxy",
        "id": "node-1768421514730-node-1768421882343-proxy-out-proxy",
        "type": "proxy"
      },
      {
        "source": "node-1768421535857",
        "target": "node-1768421882343",
        "sourceHandle": "execution-out",
        "targetHandle": "execution-in",
        "id": "node-1768421535857-node-1768421882343-execution-out-execution",
        "type": "execution"
      },
      {
        "source": "node-1768421514730",
        "target": "node-1768421932193",
        "sourceHandle": "proxy-out",
        "targetHandle": "proxy",
        "id": "node-1768421514730-node-1768421932193-proxy-out-proxy",
        "type": "proxy"
      },
      {
        "source": "node-1768421882343",
        "target": "node-1768421932193",
        "sourceHandle": "execution-out",
        "targetHandle": "execution-in",
        "id": "node-1768421882343-node-1768421932193-execution-out-execution",
        "type": "execution"
      },
      {
        "source": "node-1768421932193",
        "target": "node-1768421973860",
        "sourceHandle": "execution-out",
        "targetHandle": "execution-in",
        "id": "node-1768421932193-node-1768421973860-execution-out-execution",
        "type": "execution"
      },
      {
        "source": "node-1768421514730",
        "target": "node-1768421973860",
        "sourceHandle": "proxy-out",
        "targetHandle": "proxy",
        "id": "node-1768421514730-node-1768421973860-proxy-out-proxy",
        "type": "proxy"
      },
      {
        "source": "node-1768421535857",
        "target": "node-1768422218683",
        "sourceHandle": "data-out",
        "targetHandle": "input-0",
        "id": "node-1768421535857-node-1768422218683-data-out-orderedInput",
        "type": "orderedInput",
        "inputIndex": 0
      },
      {
        "source": "node-1768421973860",
        "target": "node-1768422218683",
        "sourceHandle": "execution-out",
        "targetHandle": "execution-in",
        "id": "node-1768421973860-node-1768422218683-execution-out-execution",
        "type": "execution"
      },
      {
        "source": "node-1768421882343",
        "target": "node-1768422218683",
        "sourceHandle": "data-out",
        "targetHandle": "input-1",
        "id": "node-1768421882343-node-1768422218683-data-out-orderedInput",
        "type": "orderedInput",
        "inputIndex": 1
      },
      {
        "source": "node-1768421932193",
        "target": "node-1768422218683",
        "sourceHandle": "data-out",
        "targetHandle": "input-2",
        "id": "node-1768421932193-node-1768422218683-data-out-orderedInput",
        "type": "orderedInput",
        "inputIndex": 2
      },
      {
        "source": "node-1768421973860",
        "target": "node-1768422218683",
        "sourceHandle": "data-out",
        "targetHandle": "input-3",
        "id": "node-1768421973860-node-1768422218683-data-out-orderedInput",
        "type": "orderedInput",
        "inputIndex": 3
      },
      {
        "source": "node-1768422218683",
        "target": "node-1768424122614",
        "sourceHandle": "data-out",
        "targetHandle": "input-0",
        "id": "node-1768422218683-node-1768424122614-data-out-orderedInput",
        "type": "orderedInput",
        "inputIndex": 0
      },
      {
        "source": "node-1768422218683",
        "target": "node-1768424122614",
        "sourceHandle": "execution-out",
        "targetHandle": "execution-in",
        "id": "node-1768422218683-node-1768424122614-execution-out-execution",
        "type": "execution"
      },
      {
        "source": "node-1768424122614",
        "target": "node-1768424390270",
        "sourceHandle": "data-out",
        "targetHandle": "data-in",
        "id": "node-1768424122614-node-1768424390270-data-out-data",
        "type": "data"
      },
      {
        "source": "node-1768424122614",
        "target": "node-1768424390270",
        "sourceHandle": "execution-out",
        "targetHandle": "execution-in",
        "id": "node-1768424122614-node-1768424390270-execution-out-execution",
        "type": "execution"
      },
      {
        "source": "node-1768424390270",
        "target": "node-1768424266205",
        "sourceHandle": "data-out",
        "targetHandle": "input-0",
        "id": "node-1768424390270-node-1768424266205-data-out-orderedInput",
        "type": "orderedInput",
        "inputIndex": 0
      },
      {
        "source": "node-1768421510514",
        "target": "node-1768424880329",
        "sourceHandle": "credentials",
        "targetHandle": "credentials",
        "id": "node-1768421510514-node-1768424880329-credentials-credential",
        "type": "credential",
        "required": true
      },
      {
        "source": "node-1768424390270",
        "target": "node-1768424266205",
        "sourceHandle": "execution-out",
        "targetHandle": "execution-in",
        "id": "node-1768424390270-node-1768424266205-execution-out-execution",
        "type": "execution"
      },
      {
        "source": "node-1768424266205",
        "target": "node-1769280063720",
        "sourceHandle": "data-out",
        "targetHandle": "input-0",
        "id": "node-1768424266205-node-1769280063720-data-out-orderedInput",
        "type": "orderedInput",
        "inputIndex": 0
      },
      {
        "source": "node-1768424266205",
        "target": "node-1769280063720",
        "sourceHandle": "execution-out",
        "targetHandle": "execution-in",
        "id": "node-1768424266205-node-1769280063720-execution-out-execution",
        "type": "execution"
      },
      {
        "source": "node-1769280063720",
        "target": "node-1768424880329",
        "sourceHandle": "execution-out",
        "targetHandle": "execution-in",
        "id": "node-1769280063720-node-1768424880329-execution-out-execution",
        "type": "execution"
      },
      {
        "source": "node-1769280063720",
        "target": "node-1768424880329",
        "sourceHandle": "output-0",
        "targetHandle": "body",
        "id": "node-1769280063720-node-1768424880329-output-0-data",
        "type": "data"
      },
      {
        "source": "node-1768421510514",
        "target": "node-1768424266205",
        "sourceHandle": "credentials",
        "targetHandle": "credentials",
        "id": "node-1768421510514-node-1768424266205-credentials-credential",
        "type": "credential",
        "required": true
      },
      {
        "source": "node-1768424880329",
        "target": "node-1772121212478",
        "sourceHandle": "execution-out",
        "targetHandle": "execution-in",
        "id": "node-1768424880329-node-1772121212478-execution-out-execution",
        "type": "execution"
      },
      {
        "source": "node-1769280063720",
        "target": "node-1772121212478",
        "sourceHandle": "output-0",
        "targetHandle": "input-0",
        "id": "node-1769280063720-node-1772121212478-output-0-orderedInput",
        "type": "orderedInput",
        "inputIndex": 0
      },
      {
        "source": "node-1768424390270",
        "target": "node-1772121212478",
        "sourceHandle": "data-out",
        "targetHandle": "input-1",
        "id": "node-1768424390270-node-1772121212478-data-out-orderedInput",
        "type": "orderedInput",
        "inputIndex": 1
      },
      {
        "source": "node-1772121212478",
        "target": "node-1768461091386",
        "sourceHandle": "execution-out",
        "targetHandle": "execution-in",
        "id": "node-1772121212478-node-1768461091386-execution-out-execution",
        "type": "execution"
      },
      {
        "source": "node-1768422218683",
        "target": "transform:python-1772575864282-393",
        "sourceHandle": "data-out",
        "targetHandle": "input-0",
        "id": "node-1768422218683-transform:python-1772575864282-393-data-out-orderedInput",
        "type": "orderedInput",
        "inputIndex": 0
      },
      {
        "source": "transform:python-1772575864282-393",
        "target": "node-1768461091386",
        "sourceHandle": "data-out",
        "targetHandle": "data-in",
        "id": "transform:python-1772575864282-393-node-1768461091386-data-out-data",
        "type": "data"
      },
      {
        "source": "node-1768422218683",
        "target": "transform:python-1772575864282-393",
        "sourceHandle": "execution-out",
        "targetHandle": "execution-in",
        "id": "node-1768422218683-transform:python-1772575864282-393-execution-out-execution",
        "type": "execution"
      }
    ]
  }
}
