PolyHedra / README.md
yf176
fix: remove unavailable Finnhub candle path
2f0f2ac
|
Raw History Blame Contribute Delete
10.1 kB
metadata
title: Polyhedra
emoji: πŸ”¬
colorFrom: blue
colorTo: purple
sdk: docker
pinned: false

Polyhedra

Governed Multi-Agent Quant Analysis

License: MIT Python 3.11+ Version

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
πŸ’Ό 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

git clone https://github.com/yf176/polyhedra.git
cd polyhedra
pip install -e .

2. Set environment variables

# 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 <TICKER>
/poly watchlist remove <TICKER>
/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 <id>  ← act on a trade proposal
/poly trade close <id>                  ← close an open position (fetches live price)
/poly trade hold <id>                   ← suppress alerts for 1 hour
/poly monitor pause|resume              ← pause / resume the background monitor
/poly monitor interval <minutes>        ← change polling frequency

All slash commands are also available as @BotName <command> <args>.


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/<id>/

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

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