--- title: Polyhedra emoji: 🔬 colorFrom: blue colorTo: purple sdk: docker pinned: false --- # Polyhedra **Governed Multi-Agent Quant Analysis** [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) [![Python 3.11+](https://img.shields.io/badge/python-3.11+-blue.svg)](https://www.python.org/downloads/) [![Version](https://img.shields.io/badge/version-8.0.0-green.svg)](pyproject.toml) Polyhedra is a Slack-native and browser-accessible multi-agent quant analysis system. Every run uses a frozen dependency graph, typed agent inputs and outputs, filename-scoped permissions, replayable run records, and Finley as the final paper-trading output layer. --- ## What's New in v8.0 **Governed collaboration release** — agents coordinate through typed artifacts in the existing session instead of relying on a hard-coded linear mention chain. | Area | Change | |------|--------| | **Typed collaboration** | All 19 quant agents have registered typed input/output contracts and exact artifact identities | | **Dependency routing** | General and specialized branches activate from one frozen per-run routing plan and join at QuantResearcher | | **Filename ACL** | Each agent receives a scoped file interface for declared current-run and read-only baseline artifacts | | **Delta and replay** | Eligible completed runs become immutable baselines; UI replay uses the recorded plan, permissions, and results | | **Evidence and export** | Run packages include input snapshots, outputs, evidence ledgers, traces, and trusted strategist performance state | | **Finley preserved** | Publisher/Finley remains the final human-facing Slack and UI output layer after strategy | | **Paper-trading guardrail** | No real capital; every output remains simulation-only and requires human approval | > **Scope boundary** — `BTC`, `SPY`, `QQQ`, and `GLD` activate specialized analysts. Other valid tickers activate the general branch. Mixed runs may use both before joining at QuantResearcher.
Previous releases ### v4.2 | Feature | Description | |---------|-------------| | 📊 **VizAgent** | Generates static PNG charts (candlestick + volume, RSI/MACD, backtest, risk heatmap, portfolio P&L) and posts them directly to Slack | | 🔔 **PortfolioMonitorAgent** | Scheduled background monitor polls Finnhub for each open position; fires take-profit / stop-loss / ±% move alerts with pre-filled action templates | | 🤖 **Coordinator input templates** | After each quant checkpoint or human-route, the Coordinator auto-generates one-click Slack reply templates (approve / reject / revise / route to alternate agent) | | 💬 `/poly monitor` | New slash command — pause, resume, or set the polling interval for the portfolio monitor | | 🔴 `/poly trade close` | Close an open paper position; fetches real-time Finnhub price and logs P&L | | ⏸ `/poly trade hold` | Suppress monitor alerts for a position for 1 hour | | ⏱ Background scheduler | `mount_to_fastapi` launches an `asyncio` loop that dispatches `@portfoliomonitor` every N minutes (default 30, configurable via `POLYHEDRA_MONITOR_INTERVAL`) | ### v4.0 / v4.1 | Feature | Description | |---------|-------------| | 📈 Quant paper-trading team | Seven specialized quant agents: DataFetcher → TrendAnalyst → SentimentAnalyst → QuantResearcher → Backtester → RiskAnalyst → QuantStrategist | | 💹 Live market data | OHLCV via **yfinance** (free, no key); news & earnings via **Finnhub** free tier | | 🛡️ Risk management | Dynamic position sizing, stop-loss / take-profit targets, portfolio heat checks | | 📊 Technical indicators | SMA, EMA, RSI, MACD computed locally from 90-day daily candles | | 📋 Watchlist commands | `/poly watchlist add|remove|show ` | | 💼 Trade proposals | `approve`, `reject`, `revise` from Slack |
--- ## Quant Agent Team | Agent | Responsibility | |-------|---------------| | **DataFetcher** | Downloads OHLCV (yfinance) + news + earnings (Finnhub) for every watchlist ticker | | **TrendAnalyst** | Computes SMA/EMA crossovers, RSI overbought/oversold, MACD signals | | **SentimentAnalyst** | Scores news headlines via LLM, aggregates ticker sentiment | | **MarketEventWatcher** | Organizes current event context for `BTC`, `SPY`, `QQQ`, and `GLD` | | **OptionsFlowWatcher** | Records available options context and avoids unsupported unusual-flow claims | | **MacroContextWatcher** | Identifies the current macro main line and relevant weighted drivers | | **UnusualEventDetector** | Filters market, options, macro, and cross-market context into meaningful event candidates | | **EventRouter** | Publishes event-to-ticker assignments for specialized analysis | | **BTCAnalyst / SPYAnalyst / QQQAnalyst / GLDAnalyst** | Performs asset-specific reasoning, signal weighting, setup, confirmation, and outcome assessment | | **QuantResearcher** | Synthesises fundamental + macro context | | **Backtester** | Back-tests signal combinations against historical OHLCV data | | **RiskAnalyst** | Sizes positions, sets stop-loss / take-profit, checks portfolio heat | | **QuantStrategist** | Produces final paper-trade proposals (direction, size, entry, target, stop) | | **PublisherAgent / Finley** | Writes the final human-readable Slack market post | | **VizAgent** 📊 | Generates candlestick, RSI/MACD, backtest, risk heatmap, and P&L PNG charts | | **PortfolioMonitorAgent** 🔔 | Polls open positions on a schedule; fires threshold alerts with action templates | --- ## Quick Start ### 1. Install ```bash git clone https://github.com/yf176/polyhedra.git cd polyhedra pip install -e . ``` ### 2. Set environment variables ```bash # LLM (pick one) export GEMINI_API_KEY=your-key export POLYHEDRA_LLM_PROVIDER=gemini # or export ANTHROPIC_API_KEY=sk-ant-your-key # or export OPENAI_API_KEY=sk-your-key # or export OPENROUTER_API_KEY=sk-or-your-key export POLYHEDRA_LLM_PROVIDER=openrouter export POLYHEDRA_LLM_MODEL=nvidia/nemotron-3.5-super-vl:free # Market data (Yahoo daily OHLCV; Finnhub quote/news/earnings) export FINNHUB_API_KEY=your-finnhub-key # https://finnhub.io/dashboard # Optional preferred read-only options source; Yahoo remains a fallback. # Set MARKETDATA_TOKEN as an HF Space Secret for the free MarketData.app tier. # Historical chains are prior-session context, not live options flow. export MARKETDATA_TOKEN=your-marketdata-key # Slack (optional) export SLACK_BOT_TOKEN=xoxb-... export SLACK_SIGNING_SECRET=... # Default watchlist (optional, comma-separated) export POLYHEDRA_QUANT_WATCHLIST=AAPL,MSFT,NVDA,GOOGL ``` ### 3. Quant paper-trading session (Slack) ``` /poly init paper trading session /poly watchlist add GLD /poly watchlist add NVDA /poly quant ``` Or via `@mention`: ``` @PolyBot watchlist add GLD @PolyBot quant ``` The bot will fetch market data, run the full quant pipeline, and post a trade summary with entry price, stop-loss, take-profit, and position size. --- ## Slack Commands ``` /poly watchlist add /poly watchlist remove /poly watchlist show /poly quant [ticker] ← run the governed quant workflow /poly yolo [ticker] ← same runtime with YOLO progress UX /poly portfolio ← summary of open paper positions /poly trade approve|reject|revise ← act on a trade proposal /poly trade close ← close an open position (fetches live price) /poly trade hold ← suppress alerts for 1 hour /poly monitor pause|resume ← pause / resume the background monitor /poly monitor interval ← change polling frequency ``` All slash commands are also available as `@BotName `. --- ## Architecture ``` src/polyhedra/ agents/ base.py # Agent ABC, Mention, AgentResponse coordinator.py # CoordinatorAgent + CoordinatorService quant/ datafetcher.py # OHLCV + news + earnings per ticker trendanalyst.py # Technical analysis sentimentanalyst.py # LLM-scored news sentiment market_watchers.py # Event, options, macro, detector, router agents asset_analysts.py # BTC/SPY/QQQ/GLD specialized analysts quantresearcher.py # Signal synthesis backtester.py # Signal backtests riskanalyst.py # Position sizing, stop/target, heat check quantstrategist.py # Paper-trade proposal strategy publisher.py # Finley, final Slack output core/ research_state.py # Shared session and quant state role_registry.py # Agent/human role tracking + takeover session.py # Session lifecycle, JSONL thread log mention_parser.py # @mention regex extraction messaging/ slack.py # Slack Bolt integration (slash + @mention) cli/ main.py # poly CLI (Typer + Rich) app.py # FastAPI server (uvicorn entry point) server.py # Legacy v2.x MCP server services/ finnhub.py # Finnhub client (news, earnings; OHLCV via yfinance) llm.py # LLM provider abstraction ``` **Session storage** — `~/.polyhedra/sessions//` | File | Contents | |------|----------| | `session.json` | Metadata (goal, platform, registered roles) | | `thread.jsonl` | Append-only message log | | `research_state.json` | Live session and quant state | | `quant/` | Agent artifacts for market data, analysis, risk, strategy, and posts | | `market_data/` | Per-ticker JSON (OHLCV, news, earnings, indicators) | | `paper_trades.json` | Simulated trade log | --- ## Development ```bash pip install -e ".[dev]" # Run all tests py -3 -m pytest --no-cov # Run Phase 1 exit-criteria tests py -3 -m pytest tests/test_phase1_e2e.py --no-cov -v # Type check mypy src # Format / lint black src tests ruff check src tests ``` --- ## License MIT