{"id":51170400,"url":"https://github.com/ronitg1/alpha-terminal","last_synced_at":"2026-06-27T00:01:44.412Z","repository":{"id":362322280,"uuid":"1253051799","full_name":"ronitg1/alpha-terminal","owner":"ronitg1","description":"Retail-investor research dashboard. AI agent panels score your stocks, a real-fill options backtester checks your strategies. Signals only — no trading execution.","archived":false,"fork":false,"pushed_at":"2026-06-26T20:55:31.000Z","size":1845,"stargazers_count":4,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"main","last_synced_at":"2026-06-26T22:18:47.179Z","etag":null,"topics":["ai-agents","backtesting","deepseek","fastapi","finance","langgraph","options-trading","polygon-io","react","retail-investing","stock-screener","typescript"],"latest_commit_sha":null,"homepage":null,"language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"other","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/ronitg1.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2026-05-29T05:40:16.000Z","updated_at":"2026-06-26T20:55:33.000Z","dependencies_parsed_at":null,"dependency_job_id":null,"html_url":"https://github.com/ronitg1/alpha-terminal","commit_stats":null,"previous_names":["ronitg1/alpha-terminal"],"tags_count":5,"template":false,"template_full_name":null,"purl":"pkg:github/ronitg1/alpha-terminal","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ronitg1%2Falpha-terminal","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ronitg1%2Falpha-terminal/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ronitg1%2Falpha-terminal/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ronitg1%2Falpha-terminal/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/ronitg1","download_url":"https://codeload.github.com/ronitg1/alpha-terminal/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ronitg1%2Falpha-terminal/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":34835785,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-05-26T15:22:16.424Z","status":"online","status_checked_at":"2026-06-26T02:00:06.560Z","response_time":106,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["ai-agents","backtesting","deepseek","fastapi","finance","langgraph","options-trading","polygon-io","react","retail-investing","stock-screener","typescript"],"created_at":"2026-06-27T00:01:43.633Z","updated_at":"2026-06-27T00:01:44.405Z","avatar_url":"https://github.com/ronitg1.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"\u003cdiv align=\"center\"\u003e\n\n# Alpha Terminal\n\n**A research terminal for retail investors. AI agent panels score your book, a realistic options backtester pressure-tests your strategies, and a market-news + earnings-call desk keeps you on top of every name — all from your laptop.**\n\n[![Version: 1.3](https://img.shields.io/badge/version-1.3-blue.svg)](CHANGELOG.md)\n[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)\n[![Python 3.12](https://img.shields.io/badge/python-3.12-blue.svg)](https://www.python.org/downloads/)\n[![Node 18+](https://img.shields.io/badge/node-18+-green.svg)](https://nodejs.org/)\n[![Tests](https://img.shields.io/badge/tests-210%20passing-brightgreen.svg)](tests/)\n[![Signals only](https://img.shields.io/badge/execution-none-lightgrey.svg)](#what-this-is-not)\n\n\u003c/div\u003e\n\n\u003e [!NOTE]\n\u003e **Version 1.3 — stable.** The six tabs (Market, Screening, Portfolio, P\u0026L, News, Calls), the options screener + realistic backtester (now runnable off any portfolio or watchlist), the intraday-capable Pattern Scanner with its own options backtest + optimizer, the P\u0026L tracker with Fidelity import, and the Finnhub fundamentals integration are feature-complete and tested (210 passing). See the [changelog](CHANGELOG.md) for what shipped and the [Roadmap](#roadmap) for what's next.\n\n\u003e **Signals only — no trading execution.** Alpha Terminal generates ideas. You decide what to do with them.\n\n---\n\n## Contents\n\n[What it does](#what-it-does) · [Why](#why-this-exists) · [Quick start](#quick-start-5-minutes) · [The dashboard](#the-dashboard-at-a-glance) · [Features](#features) · [Architecture](#architecture) · [Repo layout](#repository-layout) · [Setup](#detailed-setup) · [Troubleshooting](#troubleshooting) · [What it is NOT](#what-this-is-not) · [Roadmap](#roadmap) · [Changelog](CHANGELOG.md) · [Credits](#credits)\n\n---\n\n## What it does\n\nAlpha Terminal sits between your watchlist and your brokerage. It runs a panel of LLM-based \"agent\" analysts on your stocks, organizes them into themed sleeves, and gives you the tools to pressure-test ideas before risking capital.\n\n```\n┌────────────────────┐    ┌────────────────────┐    ┌────────────────────┐\n│  Your tickers      │ ─► │  Agent panel       │ ─► │  Portfolio Pulse   │\n│  • sleeves         │    │  • alpha_seeker    │    │  • per-agent cards │\n│  • watchlists      │    │  • damodaran       │    │  • Finnhub snapshot│\n│  • sector ETFs     │    │  • burry, graham…  │    │  • LLM idea synth  │\n└────────────────────┘    └────────────────────┘    └────────────────────┘\n       │                                                      │\n       ▼                                                      ▼\n┌────────────────────┐  ┌────────────────────┐    ┌────────────────────┐\n│  Market News +     │  │  11 options        │ ─► │  Realistic options │\n│  Earnings Calls    │  │  strategy screener │    │  backtester        │\n│  • macro buckets   │  │  • adaptive strikes│    │  • profit/stop/DTE │\n│  • 9-section call  │  │  • spread legs     │    │  • slippage model  │\n│    breakdown       │  │  • real chains     │    │  • real or BSM     │\n└────────────────────┘  └────────────────────┘    └────────────────────┘\n```\n\n## Why this exists\n\nMost retail tools fall in two camps:\n1. **Charts + indicators** (Thinkorswim, TradingView) — beautiful price data, zero conviction synthesis.\n2. **Stock screeners + AI chatbots** — generic summaries, no portfolio context, no backtest.\n\nAlpha Terminal is built for one specific job: **\"I'm a serious retail investor with a thesis. Score my book, tell me what's working, let me test a new strategy before I commit.\"**\n\n---\n\n## Quick start (5 minutes)\n\n```bash\n# 1. Clone\ngit clone https://github.com/ronitg1/alpha-terminal.git\ncd alpha-terminal\n\n# 2. Python deps (3.12 + Poetry)\npoetry install --no-root\n\n# 3. Frontend deps\ncd app/frontend \u0026\u0026 npm install \u0026\u0026 cd ../..\n\n# 4. Get API keys:\n#    DeepSeek         https://platform.deepseek.com/  (required — LLM, ~$0.05 / agent call)\n#    Polygon Stocks   https://polygon.io/  (required — free: 5 req/min, Starter ~$29/mo: unlimited)\n#    Finnhub          https://finnhub.io/register  (optional but recommended — free 60/min;\n#                     powers the News tab, earnings-beat/insider data, and fills Polygon's\n#                     insider + growth/turnover gaps)\n#    (optional) Financialdatasets.ai  https://financialdatasets.ai/  for richer ratios\n#\n# 5. Configure\ncp .env.example .env\n# edit .env with your keys\n\n# 6. Run (two terminals)\npoetry run uvicorn app.backend.main:app --host 127.0.0.1 --port 8000 --reload\ncd app/frontend \u0026\u0026 npm run dev\n\n# 7. Open http://localhost:5173\n```\n\nThe dashboard opens on the **Market** tab. The left rail lists your sleeves, watchlists, and sector ETFs with live quotes; the top tabs switch between **Market · Screening · Portfolio · P\u0026L · News · Calls**. Run a morning scan (`poetry run python -m src.run_morning_scan`) to populate Portfolio Pulse with agent verdicts.\n\n---\n\n## The dashboard at a glance\n\nA three-pane terminal: a **left rail** (sleeves, watchlists, and sector ETFs with live quotes + sparklines + company names), a **main pane** that switches across six tabs, and a context-aware **AI chat** drawer.\n\n| Tab | What it's for |\n| --- | --- |\n| **Market** | Per-ticker chart (price + volume), company overview, key financials, and a Finnhub fundamentals panel (growth/turnover, analyst consensus, earnings beat/miss, peers, insider flow). |\n| **Screening** | Pattern Scanner (weekly / daily / 1h / 15m) · 11-strategy Options Screener (with chain viewer + spread-leg highlighting) · the realistic options Backtester. |\n| **Portfolio** | Portfolio Pulse — conviction rollup, high-conviction names, whole-portfolio + per-sleeve + per-name LLM thesis, and per-name agent deep dives. |\n| **P\u0026L** | Track contracts you take or like — manual entry, one-click Track from any chain row, or Fidelity CSV import. Live mark-to-market, realized + unrealized totals, win rate, equity curve. |\n| **News** | Three-column market-news desk (your book · ticker search · auto-categorized macro) with per-article AI summaries. |\n| **Calls** | Earnings-call analysis — paste text / URL / PDF → a 9-section structured breakdown. |\n\n**Portfolio Pulse** is the home base:\n\n```\n┌──────────────────────────────────────────────────────────────────────────────┐\n│ 📊 Portfolio Pulse                                                            │\n│    Scan: 2026-05-28 · 4 signals                                               │\n├──────────────────────────────────────────────────────────────────────────────┤\n│   Positions     Bullish     Bearish     Neutral     Avg Conviction            │\n│      26            8            5           13           61%                  │\n├──────────────────────────────────────────────────────────────────────────────┤\n│  HIGH CONVICTION                                                              │\n│  ┌─────────┐ ┌─────────┐ ┌─────────┐ ┌─────────┐ ┌─────────┐                 │\n│  │ NVDA    │ │ FSLR    │ │ MU      │ │ CEG     │ │ ENPH    │                 │\n│  │ bullish │ │ bullish │ │ bearish │ │ bullish │ │ bearish │                 │\n│  │ $222.82 │ │ $311.01 │ │$1064.10 │ │ $241.80 │ │ $72.33  │                 │\n│  │ ▓▓▓▓░ 78│ │ ▓▓▓░ 64 │ │ ▓▓▓░ 60 │ │ ▓▓▓▓ 81 │ │ ▓▓░ 55  │                 │\n│  │ mega tech│ │ energy │ │opportun.│ │ energy  │ │ energy  │                 │\n│  └─────────┘ └─────────┘ └─────────┘ └─────────┘ └─────────┘                 │\n├──────────────────────────────────────────────────────────────────────────────┤\n│  Portfolio Thesis                                          [✦ Run full thesis]│\n│  Full LLM analysis across every sleeve                                        │\n├──────────────────────────── BY SLEEVE ──────────────────────────────────────┤\n│ ▼ Mega Tech   7 positions   4 bullish · 3 neutral        20% alloc [✦ Run thesis]│\n│   ▓▓▓▓▓▓▓░░░  (signal mix bar)                                                │\n│   › ▌bullish▐ NVDA   Oversold mega-cap lagging QQQ — bounce…   $222.82  -0.69% │\n│   › ▌neutral▐ MSFT   No thesis — run a scan.                   $441.31  -4.17% │\n│   › ▌neutral▐ GOOGL  No thesis — run a scan.                   $361.85  -3.38% │\n│                                                                               │\n│ ▶ Energy Transition  18 positions   50% alloc            [✦ Run thesis]       │\n│ ▶ Emerging Tech      13 positions   20% alloc            [✦ Run thesis]       │\n│ ▶ Opportunistic       4 positions   10% alloc            [✦ Run thesis]       │\n└──────────────────────────────────────────────────────────────────────────────┘\n```\n\nThe left rail (not shown) lists every sleeve, watchlist, and the 10 SPDR sector ETFs with live price, % change, a sparkline, and the company name. Each sleeve has a **Run thesis** button; the top **Portfolio Thesis** card runs the whole-book analysis.\n\nClick any ticker row to expand its **deep dive** — built for idea generation, not just numbers:\n\n1. **Finnhub snapshot strip** — analyst consensus, earnings beat/miss, growth, margin, P/E, insider flow.\n2. **Agent verdict cards** — one per analyst, each with a bull/bear/neutral pill, confidence bar, full reasoning, and (for the custom agents) the edge thesis, catalysts, and kill-switch. Hit **Run agents** to score a single name on demand (ephemeral — it never overwrites the saved morning scan). Agents read fundamentals through the provider chain, so on a Polygon-only plan they fall back to Finnhub's `metric/all` rather than reasoning over null data.\n3. **Idea synthesis** — a one-click **Quick take** (fast DeepSeek thesis) or **Deep analysis** (richer, multi-section, pulls recent news), both grounded in the agent signals *and* the Finnhub fundamentals.\n\n---\n\n## Features\n\n### 🎯 Portfolio Pulse + sleeves\n\nYour book is organized into themed **sleeves** (\"Energy Transition 50% / Mega Tech 20% / Emerging Tech 20% / Opportunistic 10%\"), each scored by its own agent panel. Portfolio Pulse rolls them up: a metrics bar (positions, bull/bear/neutral counts, average conviction), a **High Conviction** strip of the top names, and per-sleeve groups you can expand. LLM thesis synthesis is available at three scopes — **whole-portfolio** (\"Run full thesis\"), **per-sleeve** (\"Run thesis\" on any sleeve), and **per-name** (Quick take / Deep analysis in the deep dive) — each a first-person-PM read grounded in the scan signals + Finnhub fundamentals, cached server-side by scan signature.\n\n### 🔎 Pattern Scanner\n\nDetects **12 classic chart patterns** on **four timeframes — weekly, daily, 1-hour, and 15-minute bars** — ranks every hit by a transparent confidence score, then — for any signal you click — shows how that pattern has historically resolved on that name and which options structures fit it.\n\n**Patterns detected** (▲ bullish / ▼ bearish):\n\n| ▲ Bullish | ▼ Bearish |\n|---|---|\n| Bullish Flag · Bull Pennant · Double Bottom · Inverse Head \u0026 Shoulders · Ascending Triangle · Cup \u0026 Handle · Falling Wedge | Head \u0026 Shoulders · Double Top · Descending Triangle · Rising Wedge · Bearish Flag |\n\n**Confidence (0–100)** is a weighted, inspectable blend — `0.4 × breakout strength + 0.3 × volume confirmation + 0.3 × trendline-touch / symmetry` — so a clean breakout on heavy volume with several trendline touches scores high, and a marginal one scores low. Overlapping detections of the same pattern are de-duplicated (highest confidence kept).\n\n**Run a scan.** Pick the universe from three tabs — **Watchlist** (all or one named list), **My Sleeves** (all or one sleeve), or **Custom** (paste any tickers) — tick which of the 12 patterns to look for, pick a **timeframe** (Weekly for long-base/position setups over months, Daily for swing setups, 1h for multi-day swings, 15m for day-trade setups) and a lookback sized to it (up to 5yr weekly, 2yr daily, 90d hourly, 30d on 15m), and scan. Intraday bars are **regular-trading-hours only** (premarket noise is filtered) and timestamps read in **US-Eastern exchange time**. Results come back as a confidence-sorted table next to a **Quick Stats** card: total signals, average confidence, bullish-vs-bearish split, and the top tickers by signal count.\n\n**Drill into any signal.** Click a row to open a full-screen chart — candlesticks plus a synced volume histogram on the scan's timeframe, every detected pattern flagged with an entry arrow and a confidence marker, and the selected pattern's **trendlines drawn directly on the chart** (pole, channel, neckline, cup walls, wedge lines) with dashed **key-level** price lines (resistance / support / neckline) labelled on the axis.\n\n**Signal Analysis side panel** answers \"is this pattern worth trading on this name?\":\n\n- **Historical win rate** — a backtest of that exact ticker + pattern *on the scan's timeframe* (730 days of daily bars, 180 days of hourly, 60 days of 15m). A signal counts as a *win* if price posts a favourable move within 20 bars that clears the timeframe's threshold — **3%** on daily, **1.5%** on 1h, **0.75%** on 15m — so \"win\" stays meaningful as bars shrink. Recent signals that don't yet have 20 forward bars are excluded so the rate isn't inflated. Shows win rate (as a gauge), total signals, the W/L split, and average win / loss size.\n- **Options plays** — three graded structures matched to the pattern's direction (**Long Call / Bull Call Spread / Cash-Secured Put** for bullish; **Long Put / Bear Put Spread / Covered Call** for bearish), each with a concrete strike (rounded to listed increments off the current price), a suggested DTE, the rationale, risk/reward, and the IV-rank regime it works best in.\n\n### 📈 Options screener (11 strategies)\n\n| Strategy | Setup |\n|---|---|\n| **Weakness** | Lagging QQQ + oversold (bounce calls or continuation puts) |\n| **Strength** | Leading QQQ + overbought (breakout calls or mean-reversion puts) |\n| **Momentum** | Absolute trend follow, no benchmark |\n| **Mean Reversion** | Z-score from 20d mean |\n| **Breakout** | Near 52w high + volume confirm |\n| **Breakdown** | Near 52w low + volume confirm |\n| **Volume Spike** | Unusual volume + big move + close-at-wick |\n| **Pullback** | Buy-the-dip-in-uptrend |\n| **Trend Bias** | Golden/Death cross context |\n| **Vol Expansion** | Realized-vol regime change |\n| **Unusual Options Activity** | Live chain vol/OI extremes |\n\nEach strategy ships a **strike + expiry recommendation** that **adapts to your picked expiry** — a +2% OTM call at 7d becomes ~+5% OTM at 50d via √-time strike scaling, same statistical reach across maturities. Click any candidate to drop into the chain viewer (calls/puts, ATM-highlighted) with the recommended contract starred; multi-leg structures (e.g. debit spreads) highlight **both** legs with BUY/SELL tags, and the \"Plays\" pills jump the chain to each expiry tier.\n\n### 🧪 Backtest engine (two modes)\n\n**Strategy mode** — run any of the 10 backtestable options strategies against the screener's historical signals. Two pricing modes:\n\n- **Real fills (Polygon)** — fetches the actual listed contract closest to the strategy's target strike + expiry (~2.5× hold-days out), then entry/exit at the actual daily close. Falls back to BSM per-trade if the contract or bar is missing.\n- **BSM proxy** — Black-Scholes against the underlying's trailing 30-day realized vol. Deterministic, no API calls. Useful for ranking strategies.\n\n**Realistic exit model** — every trade is checked each day and closes on the first trigger: **profit target** (default +50%), **stop-loss** (default −50%), **DTE roll-out** (default 21 DTE, to step out before the gamma/theta cliff), or the **hold-days backstop**. A **slippage** model (default 5% round-trip spread) crosses half the bid/ask on each side, so frictionless win rates don't mislead. The conviction gate is **percentage-based** (magnitude-weighted, not a 0–3 count), the trades table shows the **exact entered contract** (strike + expiry) with entry/exit dates, and the summary breaks trades down by how they closed (target / stop / DTE / expiry / time). A \"reality check\" banner flags when BSM or frictionless settings are inflating results.\n\n**Sleeves mode** — wraps the LLM agent panel into a backtest. Each trading day, the full agent panel votes; portfolio positions follow the consensus. Equity curve with amber-entry / blue-exit trade markers, closed-trades table with per-agent attribution.\n\n### 💰 P\u0026L Tracker\n\nTrack the contracts you actually take — and the ones you find attractive — in one ledger, marked to market from live data.\n\n**Three ways in:**\n- **One-click Track** — every contract row in the option-chain viewer has a ➕ button: tracks 1 contract at the current mid as a *paper* idea, tagged with its source.\n- **Manual entry** — an inline form for any stock or option position (long/short, qty, entry, strike/expiry), paper or real.\n- **Fidelity CSV import** — drop in either Fidelity export (Positions, or Activity/transactions). Option symbols like `-NVDA260717C200` are decoded, opening fills create positions, closing fills FIFO-match them (partial closes split correctly), and re-imports are idempotent. Rows land tagged **REAL**; nothing from the CSV is stored except the parsed positions (in the gitignored `app/data/`). See [docs/FIDELITY_INTEGRATION.md](docs/FIDELITY_INTEGRATION.md) for the auto-sync (SnapTrade/Akoya) upgrade path — and why credential-scraping is deliberately not supported.\n\n**What you see:** summary cards (realized / unrealized / total P\u0026L, win rate, open-vs-closed counts), a **realized equity curve**, and open + closed position tables. Open options are marked from the **live chain snapshot** (bid/ask mid → last trade → day close, with a per-contract aggregate fallback after hours); stocks mark at the latest close. Unrealized P\u0026L shows in dollars and percent against cost basis; the **Close** button prefills the current mark. Paper and real positions live side by side with REAL/PAPER tags, so you can compare what you did against what you only watched.\n\n### 📊 Market tab\n\nClick any ticker (left rail, sleeve, or search) to open its detail view: a price + volume chart with a timeframe selector (1W → 2Y), a company overview, the key-financials grid, and a **Finnhub fundamentals panel** — growth/turnover metrics, an analyst-consensus bar, EPS beat/miss history, peers, and recent insider flow. Falls back gracefully (price-only, \"—\" placeholders) when a data provider is slow or down.\n\n### 🛠 Custom agents\n\nThree custom agents written specifically for this project, in addition to the 19 upstream investor-persona agents:\n\n- **`alpha_seeker`** — sector-agnostic alpha generation. Two-tier framing: STRONG EDGE requires a full variant perception (\"Consensus is wrong because X\"); DIRECTIONAL LEAN allows lower-conviction reads grounded in momentum + fundamentals + news flow.\n- **`energy_transition`** — IRA tax-credit + FEOC compliance scorecard. Allowed to use industry knowledge to infer FEOC status when news flow is silent (e.g., FSLR thin-film → clean; Chinese-cell inverter shops → amber/red).\n- **`emerging_tech`** — moat + S-curve + AI-tailwind + valuation scorecard. Calibrated confidence anchors (70-90 for full alignment, 30-50 for thin data).\n\n### 📰 Market News\n\nThree-column news desk: **your book** (headlines fanned across sleeve + watchlist tickers), **ticker search** (news for any symbol), and a **macro feed** auto-categorized into Monetary / Geopolitics / Government / Economy / Energy / Markets via keyword rules. Each article has an **AI summarize** action — 3 bullets + a \"why it matters to your book\" relevance read grounded in which sleeve holds the related ticker. Finnhub-primary with a Polygon fallback for per-ticker news.\n\n### 🎙 Earnings Call Analysis\n\nPaste a transcript, paste a URL, or upload a PDF; the analysis returns a 9-section structured read: sentiment vs prior quarter, tone delta, key themes with quotes, **hedging-language flags**, **dodged-question detection**, competitive + regulatory (IRA 45X / FEOC / tariff) mentions, and an explicit **thesis-impact verdict** (confirms / strengthens / weakens / breaks). URL extraction uses httpx + BeautifulSoup; PDF parsing uses pypdf.\n\n### 🧠 Per-name analysis (Portfolio Pulse)\n\nEach portfolio name has a **Quick take** (fast DeepSeek thesis) and **Deep analysis** (richer multi-section read that also pulls news). Both are grounded in the saved agent signals **and** Finnhub fundamentals — earnings beat/miss history, growth/turnover, analyst consensus, and insider flow — so the thesis reasons over fundamentals, not just price.\n\n### 🔌 Finnhub free-tier fallback (optional)\n\nWhen `FINNHUB_API_KEY` is set, Finnhub backfills the two gaps in Massive: **insider (Form 4) transactions** (Massive returns none) and the **growth / turnover / DSO ratios** its `/ratios` endpoint omits. It also enriches the Market tab's financials with a 130-metric fundamentals grid, earnings beat/miss history, analyst consensus, peers, and insider flow. Strictly additive — the app runs unchanged without the key. (Forward analyst estimates are premium-gated and not used.)\n\n---\n\n## Architecture\n\n```mermaid\nflowchart LR\n  subgraph User[\"User · Browser\"]\n    UI[React + Vite · 5 tabs\u003cbr/\u003elocalhost:5173]\n  end\n\n  subgraph Backend[\"FastAPI Backend · localhost:8000\"]\n    Routes[/sleeves · news · transcripts\u003cbr/\u003eroutes · SSE streams/]\n    ThesisSvc[Thesis Service\u003cbr/\u003eportfolio · sleeve · ticker]\n    BacktestSvc[Backtest Service\u003cbr/\u003ereal-fill + BSM]\n  end\n\n  subgraph LLM[\"LLM Layer\"]\n    DS[DeepSeek R1 + V3]\n    Agents[Custom + upstream\u003cbr/\u003einvestor-persona agents]\n  end\n\n  subgraph Data[\"Data Providers\"]\n    PG[Polygon · stocks + options]\n    FH[Finnhub · news · fundamentals\u003cbr/\u003einsider · rate-limited]\n    FDS[(financialdatasets.ai\u003cbr/\u003efallback for ratios)]\n  end\n\n  UI --\u003e|SSE + REST| Routes\n  Routes --\u003e ThesisSvc\n  Routes --\u003e BacktestSvc\n  Routes --\u003e Agents\n  Agents --\u003e DS\n  ThesisSvc --\u003e DS\n  Agents --\u003e|prices| PG\n  Agents --\u003e|fundamentals| FDS\n  Agents --\u003e|insider + growth| FH\n  Routes --\u003e|news + enrichment| FH\n  BacktestSvc --\u003e|historical chain| PG\n  Routes --\u003e|reference + market cap| PG\n\n  classDef user fill:#1e3a5f,stroke:#3b82f6,color:#fff\n  classDef backend fill:#3f1d38,stroke:#a855f7,color:#fff\n  classDef llm fill:#0a4d3a,stroke:#10b981,color:#fff\n  classDef data fill:#5c2a0b,stroke:#f59e0b,color:#fff\n  class UI user\n  class Routes,ThesisSvc,BacktestSvc backend\n  class DS,Agents llm\n  class PG,FH,FDS data\n```\n\n### Data flow for one ticker scan\n\nA scan is kicked off by the CLI (`python -m src.run_morning_scan`) or, for a single name, the **Run agents** button in the Portfolio Pulse deep dive (`POST /sleeves/scan/ticker/{ticker}`). Both stream the same SSE events.\n\n```mermaid\nsequenceDiagram\n  participant U as User / CLI\n  participant BE as Backend\n  participant A as Agent Panel\n  participant DS as DeepSeek\n  participant PG as Polygon\n  participant FH as Finnhub\n\n  U-\u003e\u003eBE: run scan (CLI) / POST /sleeves/scan/ticker/{ticker}\n  BE--\u003e\u003eU: SSE: start\n  loop For each ticker\n    BE-\u003e\u003ePG: get_prices (2y daily bars)\n    PG--\u003e\u003eBE: OHLCV\n    BE-\u003e\u003ePG: get_financial_metrics\n    PG--\u003e\u003eBE: 403 (no ratios add-on on Starter plan)\n    BE-\u003e\u003eFH: fallback → metric/all (margins, growth, turnover, ROE)\n    FH--\u003e\u003eBE: fundamentals\n    BE-\u003e\u003eA: agent.analyze(ticker, prices + metrics + news)\n    A-\u003e\u003eDS: R1 reasoning call\n    DS--\u003e\u003eA: structured signal + confidence + reasoning\n    A--\u003e\u003eBE: per-agent verdict\n    BE--\u003e\u003eU: SSE: progress / sleeve_complete (row)\n  end\n  BE--\u003e\u003eU: SSE: complete\n```\n\n### Per-data-type provider routing\n\nThe two data providers have different sweet spots. Alpha Terminal routes each data type to the right one, with bidirectional fallbacks:\n\n| Data | Primary | Fallback | Why |\n|---|---|---|---|\n| Prices | Polygon | FDS | Polygon covers full US universe |\n| Company news (tab) | Finnhub | Polygon | Finnhub's per-ticker + macro feeds are richer |\n| Market cap | Polygon reference | FDS company facts | Polygon has it on every ticker |\n| Fundamentals | FDS | Polygon ratios | FDS covers ratios cheaply; Polygon needs an add-on |\n| Growth / turnover ratios | FDS | **Finnhub** `metric/all` | Polygon `/ratios` omits these |\n| Insider trades | FDS | **Finnhub** insider-transactions | Polygon doesn't publish them |\n| Analyst consensus / beat-miss | Finnhub | — | Free-tier `recommendation` + `earnings` |\n| Options chain | Polygon | — | Polygon Options plan only |\n\nFinnhub access is gated behind a single process-wide token-bucket limiter (≈50/min, under the free-tier 60/min ceiling) shared across every caller, so heavy navigation never trips a 429. Forward analyst estimates are premium-gated and intentionally unused. Set neither `DATA_PROVIDER` nor both keys and the routing degrades gracefully — whichever provider you have, the dashboard still renders the data it can.\n\n---\n\n## Repository layout\n\n```\nalpha-terminal/\n├── README.md                ← you are here\n├── ARCHITECTURE.md          ← contributors' deep dive\n├── CONTRIBUTING.md\n├── ATTRIBUTION.md           ← what came from virattt/ai-hedge-fund\n├── LICENSE                  ← MIT\n├── .env.example             ← copy + fill in\n│\n├── src/                     ← Python core\n│   ├── agents/                  19 upstream + 3 custom analysts\n│   │   ├── alpha_seeker.py          (custom) sector-agnostic alpha\n│   │   ├── energy_transition.py     (custom) IRA + FEOC scorecard\n│   │   ├── emerging_tech.py         (custom) moat + S-curve + AI\n│   │   └── …\n│   ├── backtesting/\n│   │   ├── options_historical.py    real Polygon fills\n│   │   ├── options_proxy.py         BSM walk-forward\n│   │   └── sleeve_attribution.py    per-agent + per-sleeve attribution\n│   ├── config/\n│   │   ├── portfolio_config.py      sleeve definitions\n│   │   └── watchlist.py             opportunistic queue\n│   ├── tools/\n│   │   ├── api.py                   per-type provider routing\n│   │   ├── massive/                 Polygon REST client\n│   │   └── finnhub/                 Finnhub client (rate-limited) + converters\n│   └── run_morning_scan.py          CLI entry point\n│\n├── app/\n│   ├── backend/                 FastAPI\n│   │   ├── routes/\n│   │   │   ├── sleeves.py               /sleeves/* (config, quotes, screener,\n│   │   │   │                            backtest, chat, ticker enrichment, thesis)\n│   │   │   ├── news.py                  /news/* (feed, ticker search, summarize)\n│   │   │   └── transcripts.py           /transcripts/* (extract, upload, analyze)\n│   │   ├── services/                    thesis, sleeve config, watchlists,\n│   │   │                                portfolio settings, finnhub_news,\n│   │   │                                transcript_analysis\n│   │   └── models/                      events + schemas\n│   └── frontend/                React + Vite\n│       └── src/\n│           ├── components/dashboard/    3-pane shell: left-nav, main-content,\n│           │                            market-view, portfolio-section, finnhub panels\n│           ├── components/sleeves/      screener, chain viewer, backtest\n│           ├── components/news/         Market News tab\n│           ├── components/transcripts/  Earnings Calls tab\n│           ├── contexts/                sleeves + dashboard state\n│           └── services/                typed API clients\n│\n├── tests/                   ← 210 tests, pytest\n└── outputs/                 ← scan CSVs + JSON sidecars (gitignored)\n```\n\n---\n\n## Detailed setup\n\n### Required: Python 3.12 + Poetry\n\n```bash\n# macOS\nbrew install python@3.12 pipx\npipx install poetry\n\n# Windows\nchoco install python --version=3.12\npip install pipx\npipx install poetry\n\n# Linux\nsudo apt install python3.12 python3.12-venv\ncurl -sSL https://install.python-poetry.org | python3 -\n```\n\n### Required: Node 18+\n\n```bash\n# macOS\nbrew install node\n\n# Windows\nchoco install nodejs\n\n# Linux\ncurl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -\nsudo apt install -y nodejs\n```\n\n### API keys — where to get each\n\n| Key | Required? | What for | How to get |\n|---|---|---|---|\n| `DEEPSEEK_API_KEY` | ✅ Yes | Agent reasoning (R1) + structured output parsing (V3) | https://platform.deepseek.com → API Keys |\n| `MASSIVE_API_KEY` | ✅ Yes | Prices, market cap, options chain | https://polygon.io → Dashboard → API Keys |\n| `FINNHUB_API_KEY` | 🟡 Strongly recommended | Market News tab; **fundamentals fallback so agents actually see data on a Polygon-only plan** (insider trades, growth/turnover ratios); analyst consensus + earnings beat/miss; per-ticker enrichment | https://finnhub.io/register (free, 60/min) |\n| `FINANCIAL_DATASETS_API_KEY` | ⚪ Optional | Alternative fundamentals provider (richer line-items) | https://financialdatasets.ai → Settings |\n| `ANTHROPIC_API_KEY` | ⚪ Optional | Reserved for an alternate LLM provider; not wired by default | https://console.anthropic.com → API Keys |\n\n`DEEPSEEK_API_KEY` + `MASSIVE_API_KEY` is the bare minimum, **but add `FINNHUB_API_KEY` too** — Polygon's Starter plan doesn't include the fundamentals/ratios add-on, so without Finnhub (or FDS) the agents reason over null fundamentals and report \"no edge.\" Finnhub's free tier fills that gap and powers the News tab. All Finnhub traffic is rate-limited to stay under the free-tier 60/min ceiling.\n\n### Configuring sleeves\n\nSleeves are defined in [`src/config/portfolio_config.py`](src/config/portfolio_config.py). Each sleeve names its own agent panel, the per-agent weights used to combine signals, and its tickers:\n\n```python\nPORTFOLIO_SLEEVES = {\n    \"energy_transition\": {\n        \"allocation_pct\": 50.0,                       # informational (see note)\n        \"agents\": [\"energy_transition\", \"aswath_damodaran\", \"michael_burry\"],\n        \"agent_weights\": {                            # must sum to 1.0\n            \"energy_transition\": 0.3333,\n            \"aswath_damodaran\": 0.3333,\n            \"michael_burry\": 0.3334,\n        },\n        \"tickers\": [\"FSLR\", \"CSIQ\", \"JKS\", \"ENPH\", \"...\"],\n    },\n    \"mega_tech\": {\"...\": \"...\"},\n    \"emerging_tech\": {\"...\": \"...\"},\n    \"opportunistic\": {\"...\": \"...\"},\n}\n```\n\nEdit this file directly, or use the **Sleeves panel in the Market tab** (shown when no ticker is selected) — **New sleeve**, rename, delete, and per-ticker edits all rewrite the file atomically and live-reload the backend.\n\nTwo invariants are enforced at import (`validate_portfolio`): per-sleeve `agent_weights` must sum to **1.0**, and total `allocation_pct` may not exceed 100%. Note that `allocation_pct` is **informational** — nothing in the scan computes against it (real capital allocation is the per-ticker overlay), so sleeves don't have to sum to exactly 100% and you can add/delete them freely.\n\n---\n\n## Troubleshooting\n\n\u003cdetails\u003e\n\u003csummary\u003e\u003cstrong\u003eVite or uvicorn shows \"Application startup complete\" but new routes 404\u003c/strong\u003e\u003c/summary\u003e\n\nuvicorn's `--reload` is fragile after many rapid file edits. Restart the process:\n\n```bash\n# Find the PID, kill, restart\nnetstat -ano | findstr :8000    # Windows\nlsof -i :8000                    # macOS/Linux\n```\n\n\u003c/details\u003e\n\n\u003cdetails\u003e\n\u003csummary\u003e\u003cstrong\u003eBlank screen after a tab crashes\u003c/strong\u003e\u003c/summary\u003e\n\nThe `\u003cTabErrorBoundary\u003e` should catch this and show \"This tab failed to render\". If you see a fully white page, it's a pre-mount crash. Reset persisted tab state:\n\n```javascript\n// In browser DevTools console\nlocalStorage.clear()\nlocation.reload()\n```\n\n\u003c/details\u003e\n\n\u003cdetails\u003e\n\u003csummary\u003e\u003cstrong\u003eAgents say \"no momentum, no fundamentals, no news\"\u003c/strong\u003e\u003c/summary\u003e\n\nThat's the data layer failing, not the agents. Check:\n1. `DATA_PROVIDER` in `.env` — if set to `fds`, smaller-cap tickers will return empty. Either unset it or set to `massive`.\n2. Polygon plan tier — you need at least **Stocks Advanced** for aggregates + news.\n3. The ticker symbol — Polygon uses class-share suffixes for some names (`BRK.B`, `GOOG` vs `GOOGL`).\n\u003c/details\u003e\n\n\u003cdetails\u003e\n\u003csummary\u003e\u003cstrong\u003eOptions backtest in \"real fills\" mode shows all trades as synthetic\u003c/strong\u003e\u003c/summary\u003e\n\nYou don't have a Polygon Options plan, or Polygon doesn't have historical chain data for the ticker in your date window. The dashboard logs a per-trade fallback to BSM. Switch the toggle to **BSM proxy** for a cleaner result, or upgrade to **Polygon Options Starter** (~$30/mo).\n\u003c/details\u003e\n\n\u003cdetails\u003e\n\u003csummary\u003e\u003cstrong\u003eManage Sleeves dialog: tickers I removed come back\u003c/strong\u003e\u003c/summary\u003e\n\nFixed in the current version. If you see it on an older build, the cause was a stale auto-open `useEffect` re-injecting from the watchlist. Pull the latest code.\n\u003c/details\u003e\n\n---\n\n## What this is NOT\n\n- **Not a brokerage.** No trade execution. The agents tell you what they think; you trade through your own broker.\n- **Not financial advice.** Open source software written by one person. Use it as a research tool. Backtest your strategies. Risk-manage your positions.\n- **Not a guarantee of returns.** The LLMs are pattern-matchers. They are wrong sometimes. Read the `kill_switch` field on every agent verdict for what would invalidate the trade.\n- **Not a production multi-user app.** Designed to run on your laptop. The sleeves config + watchlist + scan history are all local files. No auth, no multi-tenancy.\n\n---\n\n## Roadmap\n\nTrack via [GitHub issues](https://github.com/ronitg1/alpha-terminal/issues).\n\n**Recently shipped**\n\n- [x] **1.2** — risk-sized **trade plans on the options play** (buy/cut/take-profit premiums, ATR×tolerance stops, theta viability guard, contract sizer); Pattern Scanner **\"Today's plays\"** sort + filter chips; **per-sleeve Run agents**; analysis persistence; quote last-known-good + intraday chart pagination fixes (see [changelog](CHANGELOG.md))\n\n- [x] **1.1** — **P\u0026L Tracker tab** (one-click Track from chain rows, manual entry, Fidelity CSV import, live mark-to-market, equity curve); **intraday Pattern Scanner** (1h + 15m timeframes, RTH-filtered, ET timestamps, per-timeframe win-rate thresholds); production hardening from a full audit — API-key log-leak fix, SSE stall watchdog, ~46 dead frontend files removed, toasts replace alert() (see [changelog](CHANGELOG.md))\n- [x] **1.0** — per-name conviction score + recommendation in Portfolio Pulse; structured-reasoning rendering for the Fundamentals/Valuation analysts; backend scoring-engine extraction; consolidated runtime data dir; accurate Pattern Scanner docs\n- [x] Market News tab (Finnhub-backed, macro auto-categorization, AI summaries)\n- [x] Earnings-call analysis tab (paste/URL/PDF → 9-section breakdown)\n- [x] Finnhub free-tier integration — insider + growth/turnover backfill, fundamentals enrichment, shared rate limiter\n- [x] Realistic options backtester — profit-target / stop / DTE exits + slippage model\n- [x] Per-name, per-sleeve, and whole-portfolio LLM thesis in Portfolio Pulse\n\n**Up next**\n\n- [ ] 🔗 **Fidelity auto-sync** — SnapTrade (Akoya OAuth) read-only positions/fills feed into the P\u0026L tab; plan in [docs/FIDELITY_INTEGRATION.md](docs/FIDELITY_INTEGRATION.md)\n- [ ] 🗓️ **Earnings calendar** — upcoming report dates across your book (Finnhub `/calendar/earnings`), with pre/post-earnings flags on each ticker\n- [ ] 🔔 **Price + signal alerts** — threshold + conviction-change notifications\n- [ ] 📊 **Sector heatmap** — relative-strength grid across sleeves and the SPDR sectors\n- [ ] 🧾 **Trade journal** — attach notes/rationale to each idea, linked to its agent thesis\n- [ ] Trailing / peak-drawdown stop-loss mode in the backtester (currently fixed-% from entry)\n- [ ] Sleeve sparkline history + diff highlight vs the previous scan\n- [ ] Cost meter — running tally of LLM credits per session\n\n---\n\n## Credits\n\nBuilt on the shoulders of [`virattt/ai-hedge-fund`](https://github.com/virattt/ai-hedge-fund) (MIT). The 19 upstream investor-persona agents (Warren Buffett, Aswath Damodaran, Stanley Druckenmiller, Ben Graham, Charlie Munger, Michael Burry, Phil Fisher, etc.) come from there essentially unchanged. The custom analysts, the six-tab dashboard, the options screener, the realistic options backtester, the P\u0026L tracker + Fidelity import, the Market News + earnings-call desks, the Finnhub integration, and the per-type data routing are new in this project.\n\nSee [ATTRIBUTION.md](ATTRIBUTION.md) for the full diff.\n\n---\n\n## License\n\nMIT — see [LICENSE](LICENSE). Use it, fork it, change it, sell it. Just don't blame me if your trades lose money.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fronitg1%2Falpha-terminal","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fronitg1%2Falpha-terminal","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fronitg1%2Falpha-terminal/lists"}