# Master Prompt: U.S. Equity Portfolio Research — Multi-Agent Orchestration

## Objective
Build a 40-position U.S. equity portfolio through a 314-agent swarm (11 sector analysts → 300+ stock analysts → 1 portfolio committee), using institutional-grade data from S&P Global, SEC EDGAR, Yahoo Finance, IMF, and World Bank. Output two deliverables: (1) an Arabic BDF (.pptd) presentation with slide animations, and (2) an interactive Three.js 3D capital flow visualization, both branded in EL7.AI dark theme with Cairo font.

---

## Required Skills (Load at Stage Gate)

| Stage | Skill | Load When |
|-------|-------|-----------|
| All | `equity-research` | Before any analyst agent launches |
| Stage 4 | `pptx` | Before BDF generation begins |

## Required Plugins (Load at Stage Gate)

| Plugin | Purpose | Load When |
|--------|---------|-----------|
| `sp_data` (S&P Global Market Intelligence) | Standardized fundamentals, consensus estimates, ownership, executive data, ratios, valuation metrics | Stage 1 + Stage 2 |
| `sec_edgar` | Official filings (10-K, 10-Q, 8-K), XBRL facts, insider trades (Form 4), institutional holdings (13F) | Stage 1 + Stage 2 |
| `yahoo_finance` | Real-time prices, financial metrics, earnings, margins, dividends, balance sheet, analyst coverage | Stage 1 + Stage 2 |
| `imf` | Global macro: GDP growth, inflation, unemployment, government debt, trade balances, COFER reserves | Stage 1 (macro context) |
| `world_bank_open_data` | Long-run country indicators, structural development data | Stage 1 (macro context) |

---

## Stage 1: Sector Analysis (11 Parallel Agents)

**Role:** Sector_Analyst_{01-11}  
**Agent Type:** `explore` (read-only research)  
**Parallelism:** All 11 launch simultaneously  

### Mission
Each sector analyst covers ONE GICS sector. Load `equity-research/SKILL.md` first, then scan the top ~30 stocks in the assigned sector using all 5 data plugins. Produce a Sector Research Brief.

### Sector Assignments
| Agent | Sector | Primary Tickers (sample) |
|-------|--------|--------------------------|
| Sector_01 | Information Technology | MSFT, AAPL, NVDA, GOOGL, META, TSM, AVGO, PANW, ACN, CRWD, DXCM |
| Sector_02 | Financials | JPM, V, MA, SPGI, BLK, CME, GS, MS, BX, KKR, AXP |
| Sector_03 | Health Care | JNJ, UNH, LLY, ABBV, MRK, PFE, TMO, ABT, DHR, SYK, REGN |
| Sector_04 | Communication Services | GOOGL, META, NFLX, DIS, CMCSA, VZ, T, CHTR, SPOT, EA |
| Sector_05 | Consumer Discretionary | AMZN, TSLA, HD, MCD, BKNG, LOW, NKE, TJX, SBUX, LULU |
| Sector_06 | Industrials | GE, RTX, CAT, PH, UNP, HON, LMT, BA, TDG, DE, CSL |
| Sector_07 | Consumer Staples | WMT, COST, PG, KO, PEP, WFC, MDLZ, CL, GIS, KMB, STZ |
| Sector_08 | Energy | XOM, CVX, COP, EOG, SLB, OXY, NEE, LNG, MPC, VLO, PSX |
| Sector_09 | Materials | LIN, SHW, FCX, NEM, ECL, APD, DD, MLM, VMC, STLD, NUE |
| Sector_10 | Real Estate | AMT, PLD, CCI, EQIX, PSA, O, AVB, VICI, EXR, WPC, SPG |
| Sector_11 | Utilities | NEE, DUK, SO, AEP, SRE, EXC, XEL, ETR, PEG, ED, WEC |

### Data Collection Protocol (Per Sector)
1. **Macro context** — Use `imf` plugin for U.S. GDP growth, inflation, Fed rates. Use `world_bank_open_data` for structural indicators.
2. **Sector-level data** — Use `sp_data` for sector median valuation multiples, earnings growth rates, ROE medians.
3. **Company screening** — Use `yahoo_finance` for real-time prices, P/E, market cap, 52-week range for top 30 tickers.
4. **Filings scan** — Use `sec_edgar` for latest 10-K risk factors and recent 8-K material events on top 10 candidates.
5. **Ownership check** — Use `sp_data` for institutional ownership concentration and `sec_edgar` for insider activity.

### Output: Sector Research Brief
Save as `stage1/sector_{NN}_{sector_name}.md`. Must include:
- Sector macro backdrop (rates, GDP, policy)
- Top 10 candidate stocks with: ticker, market cap, P/E, PEG, ROE, revenue growth, Quality Score (1-10), initial rating (Buy/Hold/Sell)
- Sector-specific risks (regulatory, cyclical, competitive)
- 3 best + 3 worst positioned companies with one-line rationale each

---

## Stage 2: Stock Deep-Dive (300+ Parallel Agents)

**Role:** Stock_Analyst_{Ticker}  
**Agent Type:** `coder` (research + file writing)  
**Parallelism:** Batches of 20-30, launched sequentially per batch  

### Mission
Each stock analyst loads `equity-research/SKILL.md` and produces a **Tear Sheet** (3-5 page depth) for ONE assigned stock. Use ALL 5 data plugins for cross-verified data.

### Input
- Assigned ticker from Stage 1 sector briefs
- Sector analyst's initial Quality Score and rating

### Data Collection Protocol (Per Stock)
1. **Fundamentals** — `sp_data`: standardized financials (IS/BS/CF), consensus estimates, key ratios
2. **Valuation** — `yahoo_finance`: current price, P/E, EV/EBITDA, P/B, dividend yield, 52-week range
3. **Filings** — `sec_edgar`: latest 10-K (business description, risk factors, MD&A), latest 10-Q, recent 8-Ks
4. **Ownership** — `sec_edgar` (13F institutional holders) + `sp_data` (ownership concentration)
5. **Insider activity** — `sec_edgar`: Form 4 transactions (last 12 months)
6. **Analyst coverage** — `yahoo_finance`: analyst recommendations, target price, earnings estimates
7. **Macro relevance** — Cross-reference `imf` data for sensitivity (rates, inflation, currency)

### Analysis Framework (from equity-research skill)
Apply the **Six-Dimension Analysis**:
1. Business Model — Revenue drivers, growth runways, addressable market
2. Competitive Moat — Switching costs, network effects, cost advantage, brand
3. Profitability — Gross/operating/net margins, ROIC, ROE trends
4. Cash Flow Quality — FCF conversion, working capital intensity, CapEx needs
5. Balance Sheet — Net debt/EBITDA, interest coverage, liquidity
6. Valuation — P/E, EV/EBITDA, P/B vs sector median and 5-year history

### Scoring Output
Each analyst outputs a final **Quality Score (1-10)** and **Rating**:
| Score | Rating | Action |
|-------|--------|--------|
| 9 | Strong Buy | Core position (3.0-3.5%) |
| 8 | Buy | Full position (2.5-3.0%) |
| 7 | Buy | Starter position (2.0-2.5%) |
| 6 | Hold / Watch | Below line or small |
| ≤5 | Avoid | Exclude |

### Output: Stock Tear Sheet
Save as `stage2/{TICKER}_tear_sheet.md`. Must include:
- Executive summary (1 paragraph)
- Six-dimension analysis (bullets, data-backed)
- Financial snapshot table (revenue, EBITDA, net income, FCF, margins — 3 years)
- Valuation table (current + sector median + 5-year range)
- Bull / Bear / Base case (1 paragraph each)
- Risks (3-5 items with probability × impact)
- Catalyst calendar (next 4 quarters)
- Final Quality Score (1-10) + Rating + Suggested Weight
- Source attribution for every data point

---

## Stage 3: Portfolio Allocation Committee (1 Agent)

**Role:** Portfolio_Allocation_Committee  
**Agent Type:** `plan` (synthesis + review)  

### Mission
Synthesize all 300+ tear sheets into a single portfolio construction document. Apply constraints, diversification rules, and risk overlays.

### Inputs
- All `stage1/sector_*.md` files
- All `stage2/*_tear_sheet.md` files

### Portfolio Construction Rules
1. **Quality floor:** Only Score ≥ 6 considered. Score 8-9 = core positions.
2. **Sector cap:** Max 20% in any single sector.
3. **Position sizing:**
   - Score 9 → 3.0-3.5%
   - Score 8 → 2.5-3.0%
   - Score 7 → 2.0-2.5%
   - Score 6 → 1.5-2.0% (watchlist only)
4. **Diversification:** Minimum 8 sectors represented. Target 11.
5. **Defensive balance:** Consumer Staples + Health Care + Utilities + REITs ≥ 20%
6. **Watchlist:** Score 7-8 stocks not in portfolio = 18-stock pipeline

### Output: Portfolio Construction Document
Save as `stage3/portfolio_construction.md`. Must include:
- Final 40-position portfolio table (ticker, company, sector, score, rating, weight, rationale)
- Sector allocation table (sector, weight %, # positions, top holdings)
- Quality Score distribution (histogram: scores 3-9, universe vs portfolio)
- Top 5 portfolio risks with probability × impact × mitigation
- 18-stock watchlist with elevation rules
- Quarterly rebalancing rules (trim at +25%, replace at -15% vs S&P 500)
- Key assumptions and methodology summary

---

## Stage 4: BDF Report Generation (Animation-Enabled)

**Role:** BDF_Designer  
**Agent Type:** `coder` (file writing)  

### Mission
Convert the Portfolio Construction Document into a complete BDF (.pptd) presentation with slide animations, following the `pptx` skill specification.

### Design Specs
- **Language:** Arabic (RTL)
- **Font:** Cairo throughout
- **Theme:** EL7.AI dark
  - Primary: `#f59e0b` (amber/gold)
  - Background: `#0a0a0a` (deep black)
  - Surface: `#1a1a1a` (dark gray)
  - Text: `#ffffff` (white)
  - Muted: `#9ca3af` (gray)
  - Accent: `#2563eb` (blue)
- **Size:** 1280 × 720
- **Alignment:** Right-aligned for all text

### Slide Structure (16 slides)
| # | Type | Content |
|---|------|---------|
| 1 | cover | Title: بحث محفظة الأسهم الأمريكية |
| 2 | toc | 4 chapters |
| 3 | chapter | الفصل ١ — لقطة المحفظة |
| 4 | content | 5 KPIs + Top 10 holdings table |
| 5 | content | Quality Framework: 7 dimensions + score distribution |
| 6 | chapter | الفصل ٢ — تحليل القطاعات |
| 7 | content | Sector allocation: pie chart + table |
| 8 | content | Sector heatmap: 11×7 matrix |
| 9 | chapter | الفصل ٣ — اختيار الأسهم |
| 10 | content | Top 13 Score-9 positions |
| 11 | content | Score-8 positions (14 stocks) |
| 12 | chapter | الفصل ٤ — المخاطر والمراقبة |
| 13 | content | 5 key risks table + mitigation |
| 14 | content | 18-stock watchlist |
| 15 | content | Rebalancing rules + quarterly calendar |
| 16 | final | 314 agents deployed, methodology, disclaimer |

### BDF Animation Specification
Add slide transitions to the `.pptd` master file:

```yaml
title: بحث محفظة الأسهم الأمريكية
size: [1280, 720]
transitions:
  - type: fade
    duration: 0.5
  - type: push
    direction: left
    duration: 0.4
theme:
  colors:
    primary: "#f59e0b"
    secondary: "#6b7280"
    accent: "#2563eb"
    background: "#0a0a0a"
    surface: "#1a1a1a"
    text: "#ffffff"
    muted: "#9ca3af"
    dark: "#0a0a0a"
  textStyles:
    title:
      fontSize: 52
      color: "$text"
      fontFamily: "Cairo"
      lineHeight: 1.2
    actionTitle:
      fontSize: 28
      color: "$text"
      fontFamily: "Cairo"
      lineHeight: 1.3
    body:
      fontSize: 20
      color: "$text"
      fontFamily: "Cairo"
      lineHeight: 1.5
  tableStyles:
    default:
      fontSize: 14
      fontFamily: "Cairo"
      headerFill: "$primary"
      headerColor: "$dark"
      headerBold: true
      bodyFill: ["#1a1a1a", "#0f0f0f"]
      bodyColor: "$text"
      border: {style: solid, width: 1, color: "#2a2a2a"}
pages:
  - pages/cover_ar.page
  - pages/toc_ar.page
  - pages/ch1_ar.page
  - pages/portfolio_snapshot_ar.page
  - pages/quality_framework_ar.page
  - pages/ch2_ar.page
  - pages/sector_allocation_ar.page
  - pages/sector_heatmap_ar.page
  - pages/ch3_ar.page
  - pages/top_holdings_ar.page
  - pages/score8_positions_ar.page
  - pages/ch4_ar.page
  - pages/risk_assessment_ar.page
  - pages/watchlist_ar.page
  - pages/rebalancing_ar.page
  - pages/final_ar.page
```

### Output Files
1. `portfolio_ar.pptd` — Main BDF file
2. `pages/*.page` — 16 individual page files
3. Run `pptx/scripts/check.sh` → validate
4. Run `pptx/scripts/convert.sh` → generate `.pptx`
5. Convert `.pptx` to `.pdf` via LibreOffice or Chrome headless

---

## Stage 5: Interactive 3D Capital Flow Visualization

**Role:** Viz_Developer  
**Agent Type:** `coder` (HTML/JS/Three.js development)  
**Dependencies:** Stage 3 Portfolio Construction Document  

### Mission
Build an interactive Three.js + GSAP 3D visualization that shows portfolio capital flowing from the source (المحفظة) through 11 sector nodes to 40 position nodes. This is a standalone HTML file delivered alongside the PDF report.

### Tech Stack
| Library | Version | Purpose |
|---------|---------|---------|
| Three.js | 0.160.0 | 3D scene, meshes, particles, raycaster |
| GSAP | 3.12.5 | Animation timeline (reveal, hover, camera) |
| OrbitControls | Three.js addon | Camera drag/zoom/auto-rotate |
| Canvas API | Native | Procedural text textures (Arabic labels) |

### Visual Design Specs
- **Background:** `#0d0b08` (warm dark)
- **Primary:** `#e8b04b` (gold) for Buy positions and source node
- **Secondary:** `#8a94a6` (slate) for Hold positions
- **Sector nodes:** `#9c8659` (muted gold)
- **Ribbons:** `#c9a368` (gold stream) with additive blending
- **Particles:** `#ffd9a0` glowing dots flowing along ribbons
- **Font:** IBM Plex Sans Arabic (Google Fonts)
- **RTL layout:** HUD fixed top-right, panel slides from left

### Scene Architecture
```
Source Node (المحفظة · $100)
    ↓ ribbons (tier 0) — thickness ∝ sector weight
Sector Nodes (11) — stacked vertically, height ∝ sector weight
    ↓ ribbons (tier 1) — thickness ∝ position weight
Position Nodes (40) — grouped per sector, height ∝ position weight
```

### Interactive Features
1. **Auto-rotate** — Camera slowly orbits; pauses on user interaction, resumes after 3.5s idle
2. **Hover highlight** — Mouse over any node/ribbon dims non-related elements; tooltip shows data
3. **Click to inspect** — Click a position → camera eases to it + side panel slides in with details
4. **Click a sector** → panel shows all positions in that sector with aggregate stats
5. **Unit toggle** — Button switches between $ amount and % weight; all labels redraw
6. **Esc / close** — Returns camera to home position, closes panel

### Node Types & Glow
| Type | Color | Glow | Emissive |
|------|-------|------|----------|
| Source (المحفظة) | Gold `#e8b04b` | — | Gold 0.55 |
| Sector | Muted gold `#9c8659` | — | — |
| Position (Buy) | Gold `#e8b04b` | Yes (if Quality=9) | Gold 0.55 |
| Position (Hold) | Slate `#8a94a6` | Yes (if Quality=9) | Slate 0.55 |

### Ribbon Animation (Reveal Sequence)
```javascript
// GSAP timeline
// 1. Source node scales in (back.out)
// 2. Sector nodes scale in (staggered by sector index)
// 3. Tier-0 ribbons draw on (sector connections from source)
// 4. Position nodes scale in (staggered by sector)
// 5. Tier-1 ribbons draw on (position connections from sectors)
// 6. Labels fade in
// 7. Glow sprites fade in
// 8. Particle streams activate (opacity 0 → 0.95)
```

### Particle Stream System
- **Count per ribbon:** `Math.max(2, Math.round(flow * 4))` — density ∝ flow amount
- **Speed:** `0.05 + flow * 0.0045` — faster for larger flows
- **Jitter:** Random xyz offset per particle for organic movement
- **Sampled paths:** Pre-computed cubic bezier points at 64 samples

### Data Structure (from Stage 3)
```javascript
const POSITIONS = [
  {t: "V", c: "Visa Inc.", s: "Financials", q: 9, r: "Buy", w: 3.0,
   why: "ريادة ثنائية الاحتكار في شبكات المدفوعات؛ هوامش ربح 53%."},
  // ... 40 positions
];
const SECTORS = [
  {name: "Financials", w: 19.5},
  // ... 11 sectors
];
```

### Tooltip Content
| Hover Target | Tooltip Shows |
|-------------|---------------|
| Ribbon (tier 0) | `$X.XX · Y.Y%` from portfolio + sector name + position count |
| Ribbon (tier 1) | `$X.XX · Y.Y%` from portfolio + ticker + company name |
| Sector node | Sector name + `$X.XX · Y.Y%` + position count |
| Position node | Ticker + company + `$X.XX · Y.Y%` + rating + quality score |
| Source node | Portfolio total + position count + sector count |

### Panel Content (on click)
**Position panel:**
- Sector tag
- Ticker + company name
- Rating (colored: gold=Buy, slate=Hold)
- Quality Score / 10
- Position size ($ + %)
- Investment rationale (Arabic text)

**Sector panel:**
- Sector name
- Total allocation ($ + %)
- Position count (Buy vs Hold breakdown)
- Average quality score
- List of all positions with weights

### Output
Save as `portfolio_capital_flow.html` — a single self-contained HTML file with:
- Embedded Three.js + GSAP via CDN importmap
- All 40 positions + 11 sectors data baked in
- All textures procedurally generated (no external image assets)
- Full Arabic RTL UI

---

## Data Source Attribution (Mandatory)

Every data point in the final report must be attributed:
- **Yahoo Finance** — Real-time prices, P/E, market cap, analyst estimates
- **SEC EDGAR** — Official filings (10-K, 10-Q, 8-K), insider trades, institutional holdings
- **S&P Global Market Intelligence** — Standardized fundamentals, consensus estimates, ratios, ownership
- **IMF WEO** — U.S. GDP growth, inflation, Fed policy context
- **World Bank Open Data** — Structural economic indicators
- **Kimi Research** — Synthesis, scoring, portfolio construction logic

---

## Quality Gates

| Stage | Gate | Pass Criteria |
|-------|------|---------------|
| Stage 1 | Sector Brief Complete | ≥10 candidate stocks scored, macro context included, sector risks identified |
| Stage 2 | Tear Sheet Complete | Six dimensions covered, data attributed, Quality Score + Rating assigned |
| Stage 3 | Portfolio Valid | 40 positions, sector cap ≤20%, Quality Score ≥6, defensive balance ≥20% |
| Stage 4 | BDF Valid | `check.sh` passes with 0 errors, all Arabic RTL, Cairo font, EL7.AI colors |
| Stage 5 | 3D Viz Valid | Three.js loads, particles animate, hover/tooltip works, panel slides, camera eases |

---

## Execution Order

```
Stage 1: Launch 11 Sector_Analyst agents in parallel
    ↓ (wait for all 11 briefs)
Stage 2: Launch Stock_Analyst agents in batches of 20-30
    ↓ (wait for all tear sheets)
Stage 3: Run Portfolio_Allocation_Committee (synthesis)
    ↓ (wait for construction document)
Stage 4: Run BDF_Designer → check.sh → convert.sh → PDF
    ↓ (wait for PDF)
Stage 5: Run Viz_Developer → portfolio_capital_flow.html
```

**Total agents deployed: 315** (11 sector + ~300 stock + 1 committee + 1 designer + 1 viz developer)

---

## Copy-Paste Trigger

> **To the Orchestrator:** Execute the above 5-stage workflow. Load `equity-research` skill at Stage 1 gate and `pptx` skill at Stage 4 gate. Use `sp_data`, `sec_edgar`, `yahoo_finance`, `imf`, and `world_bank_open_data` plugins for all data collection. Output language is Arabic. Final deliverables are: (1) `portfolio_ar.pptd` → `.pptx` → `.pdf` with slide animations and EL7.AI dark theme, and (2) `portfolio_capital_flow.html` — an interactive Three.js 3D capital flow visualization with animated particle streams, hover highlights, and RTL Arabic UI.
