yf176 commited on
Commit Β·
748cf22
1
Parent(s): 30cc2cc
refactor: make quant runtime the product path
Browse files- README.md +20 -17
- pyproject.toml +3 -3
- src/polyhedra/__init__.py +6 -3
- src/polyhedra/agents/__init__.py +1 -17
- src/polyhedra/agents/coordinator.py +6 -6
- src/polyhedra/app.py +4 -4
- src/polyhedra/cli/main.py +49 -43
- src/polyhedra/messaging/slack.py +11 -23
- tests/test_quant_v6/test_scope_routing.py +13 -4
README.md
CHANGED
|
@@ -9,29 +9,31 @@ pinned: false
|
|
| 9 |
|
| 10 |
# Polyhedra
|
| 11 |
|
| 12 |
-
**
|
| 13 |
|
| 14 |
[](https://opensource.org/licenses/MIT)
|
| 15 |
[](https://www.python.org/downloads/)
|
| 16 |
-
[ + news + earnings (Finnhub) for every watchlist ticker |
|
| 71 |
| **TrendAnalyst** | Computes SMA/EMA crossovers, RSI overbought/oversold, MACD signals |
|
| 72 |
| **SentimentAnalyst** | Scores news headlines via LLM, aggregates ticker sentiment |
|
| 73 |
-
| **MarketEventWatcher** |
|
| 74 |
| **OptionsFlowWatcher** | Records available options context and avoids unsupported unusual-flow claims |
|
| 75 |
| **MacroContextWatcher** | Identifies the current macro main line and relevant weighted drivers |
|
| 76 |
| **UnusualEventDetector** | Filters market, options, macro, and cross-market context into meaningful event candidates |
|
| 77 |
-
| **EventRouter** |
|
| 78 |
-
| **BTCAnalyst / SPYAnalyst / QQQAnalyst / GLDAnalyst** | Performs asset-specific
|
| 79 |
| **QuantResearcher** | Synthesises fundamental + macro context |
|
| 80 |
| **Backtester** | Back-tests signal combinations against historical OHLCV data |
|
| 81 |
| **RiskAnalyst** | Sizes positions, sets stop-loss / take-profit, checks portfolio heat |
|
|
@@ -144,7 +146,8 @@ The bot will fetch market data, run the full quant pipeline, and post a trade su
|
|
| 144 |
/poly watchlist add <TICKER>
|
| 145 |
/poly watchlist remove <TICKER>
|
| 146 |
/poly watchlist show
|
| 147 |
-
/poly quant
|
|
|
|
| 148 |
/poly portfolio β summary of open paper positions
|
| 149 |
/poly trade approve|reject|revise <id> β act on a trade proposal
|
| 150 |
/poly trade close <id> β close an open position (fetches live price)
|
|
@@ -168,8 +171,8 @@ src/polyhedra/
|
|
| 168 |
datafetcher.py # OHLCV + news + earnings per ticker
|
| 169 |
trendanalyst.py # Technical analysis
|
| 170 |
sentimentanalyst.py # LLM-scored news sentiment
|
| 171 |
-
market_watchers.py #
|
| 172 |
-
asset_analysts.py #
|
| 173 |
quantresearcher.py # Signal synthesis
|
| 174 |
backtester.py # Signal backtests
|
| 175 |
riskanalyst.py # Position sizing, stop/target, heat check
|
|
|
|
| 9 |
|
| 10 |
# Polyhedra
|
| 11 |
|
| 12 |
+
**Governed Multi-Agent Quant Analysis**
|
| 13 |
|
| 14 |
[](https://opensource.org/licenses/MIT)
|
| 15 |
[](https://www.python.org/downloads/)
|
| 16 |
+
[](pyproject.toml)
|
| 17 |
|
| 18 |
+
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.
|
| 19 |
|
| 20 |
---
|
| 21 |
|
| 22 |
+
## What's New in v8.0
|
| 23 |
|
| 24 |
+
**Governed collaboration release** β agents coordinate through typed artifacts in the existing session instead of relying on a hard-coded linear mention chain.
|
| 25 |
|
| 26 |
| Area | Change |
|
| 27 |
|------|--------|
|
| 28 |
+
| **Typed collaboration** | All 19 quant agents have registered typed input/output contracts and exact artifact identities |
|
| 29 |
+
| **Dependency routing** | General and specialized branches activate from one frozen per-run routing plan and join at QuantResearcher |
|
| 30 |
+
| **Filename ACL** | Each agent receives a scoped file interface for declared current-run and read-only baseline artifacts |
|
| 31 |
+
| **Delta and replay** | Eligible completed runs become immutable baselines; UI replay uses the recorded plan, permissions, and results |
|
| 32 |
+
| **Evidence and export** | Run packages include input snapshots, outputs, evidence ledgers, traces, and trusted strategist performance state |
|
| 33 |
+
| **Finley preserved** | Publisher/Finley remains the final human-facing Slack and UI output layer after strategy |
|
| 34 |
+
| **Paper-trading guardrail** | No real capital; every output remains simulation-only and requires human approval |
|
| 35 |
|
| 36 |
+
> **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.
|
| 37 |
|
| 38 |
<details>
|
| 39 |
<summary>Previous releases</summary>
|
|
|
|
| 72 |
| **DataFetcher** | Downloads OHLCV (yfinance) + news + earnings (Finnhub) for every watchlist ticker |
|
| 73 |
| **TrendAnalyst** | Computes SMA/EMA crossovers, RSI overbought/oversold, MACD signals |
|
| 74 |
| **SentimentAnalyst** | Scores news headlines via LLM, aggregates ticker sentiment |
|
| 75 |
+
| **MarketEventWatcher** | Organizes current event context for `BTC`, `SPY`, `QQQ`, and `GLD` |
|
| 76 |
| **OptionsFlowWatcher** | Records available options context and avoids unsupported unusual-flow claims |
|
| 77 |
| **MacroContextWatcher** | Identifies the current macro main line and relevant weighted drivers |
|
| 78 |
| **UnusualEventDetector** | Filters market, options, macro, and cross-market context into meaningful event candidates |
|
| 79 |
+
| **EventRouter** | Publishes event-to-ticker assignments for specialized analysis |
|
| 80 |
+
| **BTCAnalyst / SPYAnalyst / QQQAnalyst / GLDAnalyst** | Performs asset-specific reasoning, signal weighting, setup, confirmation, and outcome assessment |
|
| 81 |
| **QuantResearcher** | Synthesises fundamental + macro context |
|
| 82 |
| **Backtester** | Back-tests signal combinations against historical OHLCV data |
|
| 83 |
| **RiskAnalyst** | Sizes positions, sets stop-loss / take-profit, checks portfolio heat |
|
|
|
|
| 146 |
/poly watchlist add <TICKER>
|
| 147 |
/poly watchlist remove <TICKER>
|
| 148 |
/poly watchlist show
|
| 149 |
+
/poly quant [ticker] β run the governed quant workflow
|
| 150 |
+
/poly yolo [ticker] β same runtime with YOLO progress UX
|
| 151 |
/poly portfolio β summary of open paper positions
|
| 152 |
/poly trade approve|reject|revise <id> β act on a trade proposal
|
| 153 |
/poly trade close <id> β close an open position (fetches live price)
|
|
|
|
| 171 |
datafetcher.py # OHLCV + news + earnings per ticker
|
| 172 |
trendanalyst.py # Technical analysis
|
| 173 |
sentimentanalyst.py # LLM-scored news sentiment
|
| 174 |
+
market_watchers.py # Event, options, macro, detector, router agents
|
| 175 |
+
asset_analysts.py # BTC/SPY/QQQ/GLD specialized analysts
|
| 176 |
quantresearcher.py # Signal synthesis
|
| 177 |
backtester.py # Signal backtests
|
| 178 |
riskanalyst.py # Position sizing, stop/target, heat check
|
pyproject.toml
CHANGED
|
@@ -1,14 +1,14 @@
|
|
| 1 |
[project]
|
| 2 |
name = "polyhedra"
|
| 3 |
-
version = "
|
| 4 |
-
description = "
|
| 5 |
readme = "README.md"
|
| 6 |
requires-python = ">=3.11"
|
| 7 |
license = {text = "MIT"}
|
| 8 |
authors = [
|
| 9 |
{name = "Polyhedra Team", email = "team@polyhedra.dev"}
|
| 10 |
]
|
| 11 |
-
keywords = ["
|
| 12 |
classifiers = [
|
| 13 |
"Development Status :: 4 - Beta",
|
| 14 |
"Intended Audience :: Science/Research",
|
|
|
|
| 1 |
[project]
|
| 2 |
name = "polyhedra"
|
| 3 |
+
version = "8.0.0"
|
| 4 |
+
description = "Governed collaborative multi-agent quant analysis and paper-trading simulation"
|
| 5 |
readme = "README.md"
|
| 6 |
requires-python = ">=3.11"
|
| 7 |
license = {text = "MIT"}
|
| 8 |
authors = [
|
| 9 |
{name = "Polyhedra Team", email = "team@polyhedra.dev"}
|
| 10 |
]
|
| 11 |
+
keywords = ["multi-agent", "quant", "paper-trading", "slack", "analysis"]
|
| 12 |
classifiers = [
|
| 13 |
"Development Status :: 4 - Beta",
|
| 14 |
"Intended Audience :: Science/Research",
|
src/polyhedra/__init__.py
CHANGED
|
@@ -1,10 +1,13 @@
|
|
| 1 |
-
|
| 2 |
|
| 3 |
-
__version__ = "
|
| 4 |
|
| 5 |
-
|
|
|
|
| 6 |
def main():
|
| 7 |
from polyhedra.server import main as _main
|
|
|
|
| 8 |
return _main()
|
| 9 |
|
|
|
|
| 10 |
__all__ = ["main", "__version__"]
|
|
|
|
| 1 |
+
"""Polyhedra collaborative multi-agent quant analysis system."""
|
| 2 |
|
| 3 |
+
__version__ = "8.0.0"
|
| 4 |
|
| 5 |
+
|
| 6 |
+
# Lazy import to avoid MCP dependency during testing.
|
| 7 |
def main():
|
| 8 |
from polyhedra.server import main as _main
|
| 9 |
+
|
| 10 |
return _main()
|
| 11 |
|
| 12 |
+
|
| 13 |
__all__ = ["main", "__version__"]
|
src/polyhedra/agents/__init__.py
CHANGED
|
@@ -1,12 +1,4 @@
|
|
| 1 |
-
"""
|
| 2 |
-
Multi-agent orchestration system for Slack and CLI sessions.
|
| 3 |
-
Quant pipeline: DataFetcher β TrendAnalyst β ... β QuantStrategist.
|
| 4 |
-
Research pipeline: Scout β Strategist β Critic β Scribe (disabled in V4.x).
|
| 5 |
-
Entry points: messaging/slack.py, cli/main.py.
|
| 6 |
-
Do not import from agent/ (workflow engine) in this module.
|
| 7 |
-
"""
|
| 8 |
-
|
| 9 |
-
import os
|
| 10 |
|
| 11 |
from polyhedra.agents.base import Agent, AgentResponse, Mention
|
| 12 |
|
|
@@ -15,11 +7,3 @@ __all__ = [
|
|
| 15 |
"AgentResponse",
|
| 16 |
"Mention",
|
| 17 |
]
|
| 18 |
-
|
| 19 |
-
if os.getenv("POLYHEDRA_ENABLE_RESEARCH", "false").lower() == "true":
|
| 20 |
-
from polyhedra.agents.scout import ScoutAgent
|
| 21 |
-
from polyhedra.agents.strategist import StrategistAgent
|
| 22 |
-
from polyhedra.agents.critic import CriticAgent
|
| 23 |
-
from polyhedra.agents.scribe import ScribeAgent
|
| 24 |
-
|
| 25 |
-
__all__ += ["ScoutAgent", "StrategistAgent", "CriticAgent", "ScribeAgent"]
|
|
|
|
| 1 |
+
"""Shared agent primitives for the quant-only Polyhedra product runtime."""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
|
| 3 |
from polyhedra.agents.base import Agent, AgentResponse, Mention
|
| 4 |
|
|
|
|
| 7 |
"AgentResponse",
|
| 8 |
"Mention",
|
| 9 |
]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
src/polyhedra/agents/coordinator.py
CHANGED
|
@@ -224,10 +224,10 @@ class CoordinatorAgent(Agent):
|
|
| 224 |
|
| 225 |
name = "Coordinator"
|
| 226 |
role = "coordinator"
|
| 227 |
-
role_title = "
|
| 228 |
system_prompt = (
|
| 229 |
-
"You are Coordinator
|
| 230 |
-
"You orchestrate
|
| 231 |
"You are concise, structured, and always transparent about what is happening next."
|
| 232 |
)
|
| 233 |
|
|
@@ -277,7 +277,7 @@ class CoordinatorService:
|
|
| 277 |
Usage::
|
| 278 |
|
| 279 |
service = CoordinatorService(session=session, post_fn=..., checkpoint_fn=...)
|
| 280 |
-
await service.dispatch(from_role="human", text="@
|
| 281 |
"""
|
| 282 |
|
| 283 |
def __init__(
|
|
@@ -569,8 +569,8 @@ class CoordinatorService:
|
|
| 569 |
if self._mode != "yolo":
|
| 570 |
welcome += [
|
| 571 |
"",
|
| 572 |
-
"Type your
|
| 573 |
-
"_Example:_ `@
|
| 574 |
]
|
| 575 |
await self._post("coordinator", "\n".join(welcome))
|
| 576 |
self.session.post("coordinator", "\n".join(welcome))
|
|
|
|
| 224 |
|
| 225 |
name = "Coordinator"
|
| 226 |
role = "coordinator"
|
| 227 |
+
role_title = "Quant Coordinator"
|
| 228 |
system_prompt = (
|
| 229 |
+
"You are Coordinator for a collaborative paper-trading analysis team. "
|
| 230 |
+
"You orchestrate quant agents, manage checkpoints, and keep the analysis on track. "
|
| 231 |
"You are concise, structured, and always transparent about what is happening next."
|
| 232 |
)
|
| 233 |
|
|
|
|
| 277 |
Usage::
|
| 278 |
|
| 279 |
service = CoordinatorService(session=session, post_fn=..., checkpoint_fn=...)
|
| 280 |
+
await service.dispatch(from_role="human", text="@datafetcher fetch SPY")
|
| 281 |
"""
|
| 282 |
|
| 283 |
def __init__(
|
|
|
|
| 569 |
if self._mode != "yolo":
|
| 570 |
welcome += [
|
| 571 |
"",
|
| 572 |
+
"Type your quant analysis goal to begin, or @mention an agent directly.",
|
| 573 |
+
"_Example:_ `@datafetcher fetch SPY`",
|
| 574 |
]
|
| 575 |
await self._post("coordinator", "\n".join(welcome))
|
| 576 |
self.session.post("coordinator", "\n".join(welcome))
|
src/polyhedra/app.py
CHANGED
|
@@ -1269,8 +1269,8 @@ def create_app():
|
|
| 1269 |
|
| 1270 |
app = FastAPI(
|
| 1271 |
title="Polyhedra",
|
| 1272 |
-
description="
|
| 1273 |
-
version="
|
| 1274 |
)
|
| 1275 |
|
| 1276 |
@app.get("/health", tags=["ops"])
|
|
@@ -1293,14 +1293,14 @@ def create_app():
|
|
| 1293 |
|
| 1294 |
@app.get("/api/health", tags=["web"])
|
| 1295 |
async def api_health() -> JSONResponse:
|
| 1296 |
-
"""Health endpoint for the
|
| 1297 |
from polyhedra import __version__
|
| 1298 |
|
| 1299 |
return JSONResponse({
|
| 1300 |
"status": "ok",
|
| 1301 |
"service": "polyhedra",
|
| 1302 |
"version": __version__,
|
| 1303 |
-
"ui": "
|
| 1304 |
"llm": _llm_config_status(),
|
| 1305 |
})
|
| 1306 |
|
|
|
|
| 1269 |
|
| 1270 |
app = FastAPI(
|
| 1271 |
title="Polyhedra",
|
| 1272 |
+
description="Governed multi-agent quant analysis system",
|
| 1273 |
+
version="8.0.0",
|
| 1274 |
)
|
| 1275 |
|
| 1276 |
@app.get("/health", tags=["ops"])
|
|
|
|
| 1293 |
|
| 1294 |
@app.get("/api/health", tags=["web"])
|
| 1295 |
async def api_health() -> JSONResponse:
|
| 1296 |
+
"""Health endpoint for the quant workspace UI."""
|
| 1297 |
from polyhedra import __version__
|
| 1298 |
|
| 1299 |
return JSONResponse({
|
| 1300 |
"status": "ok",
|
| 1301 |
"service": "polyhedra",
|
| 1302 |
"version": __version__,
|
| 1303 |
+
"ui": "v8.0-quant-workspace",
|
| 1304 |
"llm": _llm_config_status(),
|
| 1305 |
})
|
| 1306 |
|
src/polyhedra/cli/main.py
CHANGED
|
@@ -1,9 +1,8 @@
|
|
| 1 |
-
"""
|
| 2 |
|
| 3 |
Commands
|
| 4 |
--------
|
| 5 |
-
poly init Start a new
|
| 6 |
-
poly search Invoke Scout directly (no full session needed)
|
| 7 |
poly state Print the current Research State
|
| 8 |
poly resume Rejoin an existing session by ID
|
| 9 |
poly export Export all session artifacts as a zip
|
|
@@ -13,12 +12,11 @@ poly sessions List all saved sessions
|
|
| 13 |
|
| 14 |
Usage examples
|
| 15 |
--------------
|
| 16 |
-
poly init "
|
| 17 |
-
poly search "sparse attention mechanisms"
|
| 18 |
poly state
|
| 19 |
poly resume abc12345
|
| 20 |
poly export --output ./my_exports
|
| 21 |
-
poly role
|
| 22 |
poly mcp
|
| 23 |
"""
|
| 24 |
|
|
@@ -37,16 +35,19 @@ from rich.table import Table
|
|
| 37 |
|
| 38 |
from polyhedra.agents.coordinator import CoordinatorService, CheckpointResult
|
| 39 |
from polyhedra.agents.coordinator import CoordinatorAgent
|
| 40 |
-
from polyhedra.agents.
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
|
|
|
|
|
|
|
|
|
| 44 |
from polyhedra.core.role_registry import RoleEntry
|
| 45 |
from polyhedra.core.session import SessionManager
|
| 46 |
|
| 47 |
app = typer.Typer(
|
| 48 |
name="poly",
|
| 49 |
-
help="Polyhedra
|
| 50 |
no_args_is_help=True,
|
| 51 |
rich_markup_mode="markdown",
|
| 52 |
)
|
|
@@ -60,18 +61,40 @@ _sm = SessionManager()
|
|
| 60 |
# --------------------------------------------------------------------------- #
|
| 61 |
|
| 62 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 63 |
def _build_full_session(goal: str = "", platform: str = "cli", human_roles: list[str] | None = None) -> tuple:
|
| 64 |
-
"""Create a new session with
|
| 65 |
human_roles = human_roles or []
|
| 66 |
session = _sm.create(goal=goal, platform=platform)
|
| 67 |
|
| 68 |
-
|
| 69 |
-
(ScoutAgent, "scout"),
|
| 70 |
-
(StrategistAgent, "strategist"),
|
| 71 |
-
(CriticAgent, "critic"),
|
| 72 |
-
(ScribeAgent, "scribe"),
|
| 73 |
-
]:
|
| 74 |
-
session.registry.register(RoleEntry(role=role, agent=agent_cls(session_dir=session.session_dir) if role == "scribe" else agent_cls()))
|
| 75 |
|
| 76 |
for r in human_roles:
|
| 77 |
session.registry.take_over(r)
|
|
@@ -107,7 +130,7 @@ def _build_full_session(goal: str = "", platform: str = "cli", human_roles: list
|
|
| 107 |
|
| 108 |
@app.command()
|
| 109 |
def init(
|
| 110 |
-
goal: Annotated[str, typer.Argument(help="One-sentence
|
| 111 |
roles: Annotated[
|
| 112 |
Optional[str],
|
| 113 |
typer.Option("--roles", "-r", help="Comma-separated roles to activate (default: all)."),
|
|
@@ -117,18 +140,18 @@ def init(
|
|
| 117 |
typer.Option("--human", "-H", help="Comma-separated roles you will hold yourself."),
|
| 118 |
] = None,
|
| 119 |
) -> None:
|
| 120 |
-
"""Start a new collaborative
|
| 121 |
|
| 122 |
human_roles = [r.strip().lower() for r in (human or "").split(",") if r.strip()]
|
| 123 |
selected_roles = (
|
| 124 |
[r.strip().lower() for r in roles.split(",") if r.strip()]
|
| 125 |
if roles
|
| 126 |
-
else [
|
| 127 |
)
|
| 128 |
|
| 129 |
session, service = _build_full_session(goal=goal, human_roles=human_roles)
|
| 130 |
|
| 131 |
-
console.print(Panel(f"[bold green]Polyhedra
|
| 132 |
|
| 133 |
asyncio.run(
|
| 134 |
service.initialize_session(goal=goal, selected_roles=selected_roles, human_roles=human_roles)
|
|
@@ -152,25 +175,6 @@ def init(
|
|
| 152 |
asyncio.run(service.dispatch(from_role="human", text=user_input))
|
| 153 |
|
| 154 |
|
| 155 |
-
@app.command()
|
| 156 |
-
def search(
|
| 157 |
-
query: Annotated[str, typer.Argument(help="Search query for Scout.")],
|
| 158 |
-
) -> None:
|
| 159 |
-
"""Invoke Scout directly to search for papers (no full session required)."""
|
| 160 |
-
from polyhedra.agents.base import Mention
|
| 161 |
-
|
| 162 |
-
console.print(f"[bold cyan]@Scout[/bold cyan] searching for: [italic]{query}[/italic]\n")
|
| 163 |
-
|
| 164 |
-
scout = ScoutAgent()
|
| 165 |
-
|
| 166 |
-
async def run() -> None:
|
| 167 |
-
mention = Mention(mentioned_role="scout", from_role="human", content=query)
|
| 168 |
-
response = await scout.handle(mention, [], {})
|
| 169 |
-
console.print(Markdown(response.content))
|
| 170 |
-
|
| 171 |
-
asyncio.run(run())
|
| 172 |
-
|
| 173 |
-
|
| 174 |
@app.command()
|
| 175 |
def state(
|
| 176 |
session_id: Annotated[Optional[str], typer.Argument(help="Session ID (uses latest if omitted).")] = None,
|
|
@@ -199,6 +203,8 @@ def resume(
|
|
| 199 |
err_console.print(f"[red]Session {session_id} not found.[/red]")
|
| 200 |
raise typer.Exit(1)
|
| 201 |
|
|
|
|
|
|
|
| 202 |
console.print(Panel(
|
| 203 |
f"[bold green]Resuming session[/bold green] [bold]{session_id}[/bold]\n"
|
| 204 |
f"Goal: [italic]{session.goal}[/italic]",
|
|
@@ -242,7 +248,7 @@ def export(
|
|
| 242 |
typer.Option("--output", "-o", help="Directory to write the zip file."),
|
| 243 |
] = Path("./exports"),
|
| 244 |
) -> None:
|
| 245 |
-
"""Export all session
|
| 246 |
sid = session_id or _latest_session_id()
|
| 247 |
if not sid:
|
| 248 |
err_console.print("[red]No sessions found.[/red]")
|
|
|
|
| 1 |
+
"""Polyhedra quant command-line interface.
|
| 2 |
|
| 3 |
Commands
|
| 4 |
--------
|
| 5 |
+
poly init Start a new quant session
|
|
|
|
| 6 |
poly state Print the current Research State
|
| 7 |
poly resume Rejoin an existing session by ID
|
| 8 |
poly export Export all session artifacts as a zip
|
|
|
|
| 12 |
|
| 13 |
Usage examples
|
| 14 |
--------------
|
| 15 |
+
poly init "SPY analysis"
|
|
|
|
| 16 |
poly state
|
| 17 |
poly resume abc12345
|
| 18 |
poly export --output ./my_exports
|
| 19 |
+
poly role trendanalyst human
|
| 20 |
poly mcp
|
| 21 |
"""
|
| 22 |
|
|
|
|
| 35 |
|
| 36 |
from polyhedra.agents.coordinator import CoordinatorService, CheckpointResult
|
| 37 |
from polyhedra.agents.coordinator import CoordinatorAgent
|
| 38 |
+
from polyhedra.agents.quant import (
|
| 39 |
+
BacktesterAgent, BTCAnalyst, DataFetcherAgent, EventRouter, GLDAnalyst,
|
| 40 |
+
MacroContextWatcher, MarketEventWatcher, OptionsFlowWatcher,
|
| 41 |
+
PortfolioMonitorAgent, PublisherAgent, QQQAnalyst, QuantResearcherAgent,
|
| 42 |
+
QuantStrategistAgent, RiskAnalystAgent, SentimentAnalystAgent, SPYAnalyst,
|
| 43 |
+
TrendAnalystAgent, UnusualEventDetector, VizAgent,
|
| 44 |
+
)
|
| 45 |
from polyhedra.core.role_registry import RoleEntry
|
| 46 |
from polyhedra.core.session import SessionManager
|
| 47 |
|
| 48 |
app = typer.Typer(
|
| 49 |
name="poly",
|
| 50 |
+
help="Polyhedra collaborative multi-agent quant team.",
|
| 51 |
no_args_is_help=True,
|
| 52 |
rich_markup_mode="markdown",
|
| 53 |
)
|
|
|
|
| 61 |
# --------------------------------------------------------------------------- #
|
| 62 |
|
| 63 |
|
| 64 |
+
_QUANT_AGENTS = (
|
| 65 |
+
(DataFetcherAgent, "datafetcher"),
|
| 66 |
+
(TrendAnalystAgent, "trendanalyst"),
|
| 67 |
+
(SentimentAnalystAgent, "sentimentanalyst"),
|
| 68 |
+
(MarketEventWatcher, "marketeventwatcher"),
|
| 69 |
+
(OptionsFlowWatcher, "optionsflowwatcher"),
|
| 70 |
+
(MacroContextWatcher, "macrocontextwatcher"),
|
| 71 |
+
(UnusualEventDetector, "unusualeventdetector"),
|
| 72 |
+
(EventRouter, "eventrouter"),
|
| 73 |
+
(BTCAnalyst, "btcanalyst"),
|
| 74 |
+
(SPYAnalyst, "spyanalyst"),
|
| 75 |
+
(QQQAnalyst, "qqqanalyst"),
|
| 76 |
+
(GLDAnalyst, "gldanalyst"),
|
| 77 |
+
(QuantResearcherAgent, "quantresearcher"),
|
| 78 |
+
(BacktesterAgent, "backtester"),
|
| 79 |
+
(RiskAnalystAgent, "riskanalyst"),
|
| 80 |
+
(QuantStrategistAgent, "quantstrategist"),
|
| 81 |
+
(VizAgent, "vizagent"),
|
| 82 |
+
(PortfolioMonitorAgent, "portfoliomonitor"),
|
| 83 |
+
(PublisherAgent, "publisher"),
|
| 84 |
+
)
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def _register_quant_agents(session) -> None:
|
| 88 |
+
for agent_cls, role in _QUANT_AGENTS:
|
| 89 |
+
session.registry.register(RoleEntry(role=role, agent=agent_cls()))
|
| 90 |
+
|
| 91 |
+
|
| 92 |
def _build_full_session(goal: str = "", platform: str = "cli", human_roles: list[str] | None = None) -> tuple:
|
| 93 |
+
"""Create a new session with the current quant agents registered."""
|
| 94 |
human_roles = human_roles or []
|
| 95 |
session = _sm.create(goal=goal, platform=platform)
|
| 96 |
|
| 97 |
+
_register_quant_agents(session)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 98 |
|
| 99 |
for r in human_roles:
|
| 100 |
session.registry.take_over(r)
|
|
|
|
| 130 |
|
| 131 |
@app.command()
|
| 132 |
def init(
|
| 133 |
+
goal: Annotated[str, typer.Argument(help="One-sentence quant analysis goal.")],
|
| 134 |
roles: Annotated[
|
| 135 |
Optional[str],
|
| 136 |
typer.Option("--roles", "-r", help="Comma-separated roles to activate (default: all)."),
|
|
|
|
| 140 |
typer.Option("--human", "-H", help="Comma-separated roles you will hold yourself."),
|
| 141 |
] = None,
|
| 142 |
) -> None:
|
| 143 |
+
"""Start a new collaborative quant session."""
|
| 144 |
|
| 145 |
human_roles = [r.strip().lower() for r in (human or "").split(",") if r.strip()]
|
| 146 |
selected_roles = (
|
| 147 |
[r.strip().lower() for r in roles.split(",") if r.strip()]
|
| 148 |
if roles
|
| 149 |
+
else [role for _, role in _QUANT_AGENTS]
|
| 150 |
)
|
| 151 |
|
| 152 |
session, service = _build_full_session(goal=goal, human_roles=human_roles)
|
| 153 |
|
| 154 |
+
console.print(Panel(f"[bold green]Polyhedra Quant[/bold green] β Session [bold]{session.session_id}[/bold]", border_style="green"))
|
| 155 |
|
| 156 |
asyncio.run(
|
| 157 |
service.initialize_session(goal=goal, selected_roles=selected_roles, human_roles=human_roles)
|
|
|
|
| 175 |
asyncio.run(service.dispatch(from_role="human", text=user_input))
|
| 176 |
|
| 177 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 178 |
@app.command()
|
| 179 |
def state(
|
| 180 |
session_id: Annotated[Optional[str], typer.Argument(help="Session ID (uses latest if omitted).")] = None,
|
|
|
|
| 203 |
err_console.print(f"[red]Session {session_id} not found.[/red]")
|
| 204 |
raise typer.Exit(1)
|
| 205 |
|
| 206 |
+
_register_quant_agents(session)
|
| 207 |
+
|
| 208 |
console.print(Panel(
|
| 209 |
f"[bold green]Resuming session[/bold green] [bold]{session_id}[/bold]\n"
|
| 210 |
f"Goal: [italic]{session.goal}[/italic]",
|
|
|
|
| 248 |
typer.Option("--output", "-o", help="Directory to write the zip file."),
|
| 249 |
] = Path("./exports"),
|
| 250 |
) -> None:
|
| 251 |
+
"""Export all session state, run records, inputs, and artifacts as a zip."""
|
| 252 |
sid = session_id or _latest_session_id()
|
| 253 |
if not sid:
|
| 254 |
err_console.print("[red]No sessions found.[/red]")
|
src/polyhedra/messaging/slack.py
CHANGED
|
@@ -26,7 +26,6 @@ import os
|
|
| 26 |
import re
|
| 27 |
from typing import Any
|
| 28 |
|
| 29 |
-
from polyhedra.agents.quant.market_scope import split_v5_v6_markets
|
| 30 |
|
| 31 |
logger = logging.getLogger(__name__)
|
| 32 |
|
|
@@ -244,8 +243,8 @@ class SlackIntegration:
|
|
| 244 |
await client.chat_postMessage(
|
| 245 |
channel=channel_id,
|
| 246 |
text=(
|
| 247 |
-
"*Polyhedra
|
| 248 |
-
"β’ `/poly init <goal>` β start a new
|
| 249 |
"β’ `/poly init <goal> --force` β replace existing session\n"
|
| 250 |
"β’ `/poly init <goal> --yolo` β silent YOLO run (Finley posts at end)\n"
|
| 251 |
"β’ `/poly yolo [ticker]` β run YOLO in the current session\n"
|
|
@@ -255,7 +254,7 @@ class SlackIntegration:
|
|
| 255 |
"β’ `/poly export` β export all artifacts as a zip\n"
|
| 256 |
"β’ `/poly role <name> human|agent` β take over / release a role\n"
|
| 257 |
"β’ `/poly resume <session_id>` β rejoin an existing session\n"
|
| 258 |
-
"β’ `/poly quant [ticker]` β run
|
| 259 |
"β’ `/poly quant report` β post most recent quant findings\n"
|
| 260 |
"β’ `/poly portfolio` β show paper portfolio + P&L\n"
|
| 261 |
"β’ `/poly trade approve|reject|revise|close|hold <id>` β act on trades\n"
|
|
@@ -935,7 +934,7 @@ class SlackIntegration:
|
|
| 935 |
# ------------------------------------------------------------------ #
|
| 936 |
|
| 937 |
async def _cmd_quant(self, client: Any, channel_id: str, args: str) -> None:
|
| 938 |
-
"""
|
| 939 |
service = self._sessions.get(channel_id)
|
| 940 |
if not service:
|
| 941 |
await self._init_from_mention(
|
|
@@ -953,8 +952,6 @@ class SlackIntegration:
|
|
| 953 |
await self._cmd_quant_report(client, channel_id)
|
| 954 |
return
|
| 955 |
|
| 956 |
-
# Optional extra ticker from args (e.g. `/poly quant TSLA`)
|
| 957 |
-
extra = f" {args}" if args else ""
|
| 958 |
requested = _extract_tickers_from_text(args)
|
| 959 |
if not requested:
|
| 960 |
try:
|
|
@@ -963,32 +960,23 @@ class SlackIntegration:
|
|
| 963 |
requested = list(rs.quant_state.watchlist) if rs.quant_state else []
|
| 964 |
except Exception:
|
| 965 |
requested = []
|
| 966 |
-
|
| 967 |
-
use_v6 = bool(requested) and len(v6_requested) == len(requested)
|
| 968 |
-
if use_v6:
|
| 969 |
await client.chat_postMessage(
|
| 970 |
channel=channel_id,
|
| 971 |
-
text=
|
| 972 |
-
"β‘ *V6 specialized quant analysis startingβ¦*\n"
|
| 973 |
-
"_β οΈ Paper trading simulation only. Not financial advice._\n\n"
|
| 974 |
-
f"Scope: {', '.join(v6_requested)}. "
|
| 975 |
-
"Dispatching `@datafetcher`; TrendAnalyst will hand off into the V6 agent workflow."
|
| 976 |
-
),
|
| 977 |
)
|
| 978 |
-
text = f"@datafetcher{extra} fetch market data for V6 workflow"
|
| 979 |
-
await service.dispatch(from_role="human", text=text)
|
| 980 |
return
|
| 981 |
-
|
|
|
|
| 982 |
await client.chat_postMessage(
|
| 983 |
channel=channel_id,
|
| 984 |
text=(
|
| 985 |
-
"
|
| 986 |
"_β οΈ Paper trading simulation only. Not financial advice._\n\n"
|
| 987 |
-
f"
|
| 988 |
),
|
| 989 |
)
|
| 990 |
-
|
| 991 |
-
await service.dispatch(from_role="human", text=text)
|
| 992 |
|
| 993 |
async def _cmd_yolo(self, client: Any, channel_id: str, args: str) -> None:
|
| 994 |
"""Run YOLO in the active session, using V7 baseline/session-delta context."""
|
|
|
|
| 26 |
import re
|
| 27 |
from typing import Any
|
| 28 |
|
|
|
|
| 29 |
|
| 30 |
logger = logging.getLogger(__name__)
|
| 31 |
|
|
|
|
| 243 |
await client.chat_postMessage(
|
| 244 |
channel=channel_id,
|
| 245 |
text=(
|
| 246 |
+
"*Polyhedra Quant* β available commands:\n"
|
| 247 |
+
"β’ `/poly init <goal>` β start a new quant session\n"
|
| 248 |
"β’ `/poly init <goal> --force` β replace existing session\n"
|
| 249 |
"β’ `/poly init <goal> --yolo` β silent YOLO run (Finley posts at end)\n"
|
| 250 |
"β’ `/poly yolo [ticker]` β run YOLO in the current session\n"
|
|
|
|
| 254 |
"β’ `/poly export` β export all artifacts as a zip\n"
|
| 255 |
"β’ `/poly role <name> human|agent` β take over / release a role\n"
|
| 256 |
"β’ `/poly resume <session_id>` β rejoin an existing session\n"
|
| 257 |
+
"β’ `/poly quant [ticker]` β run the governed quant workflow\n"
|
| 258 |
"β’ `/poly quant report` β post most recent quant findings\n"
|
| 259 |
"β’ `/poly portfolio` β show paper portfolio + P&L\n"
|
| 260 |
"β’ `/poly trade approve|reject|revise|close|hold <id>` β act on trades\n"
|
|
|
|
| 934 |
# ------------------------------------------------------------------ #
|
| 935 |
|
| 936 |
async def _cmd_quant(self, client: Any, channel_id: str, args: str) -> None:
|
| 937 |
+
"""Run the same governed quant workflow used by YOLO and the UI."""
|
| 938 |
service = self._sessions.get(channel_id)
|
| 939 |
if not service:
|
| 940 |
await self._init_from_mention(
|
|
|
|
| 952 |
await self._cmd_quant_report(client, channel_id)
|
| 953 |
return
|
| 954 |
|
|
|
|
|
|
|
| 955 |
requested = _extract_tickers_from_text(args)
|
| 956 |
if not requested:
|
| 957 |
try:
|
|
|
|
| 960 |
requested = list(rs.quant_state.watchlist) if rs.quant_state else []
|
| 961 |
except Exception:
|
| 962 |
requested = []
|
| 963 |
+
if not requested:
|
|
|
|
|
|
|
| 964 |
await client.chat_postMessage(
|
| 965 |
channel=channel_id,
|
| 966 |
+
text="Add a watchlist ticker or run `/poly quant SPY`.",
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 967 |
)
|
|
|
|
|
|
|
| 968 |
return
|
| 969 |
+
await self._seed_service_watchlist(service, requested)
|
| 970 |
+
service._mode = "yolo"
|
| 971 |
await client.chat_postMessage(
|
| 972 |
channel=channel_id,
|
| 973 |
text=(
|
| 974 |
+
"β‘ *Quant analysis starting*\n"
|
| 975 |
"_β οΈ Paper trading simulation only. Not financial advice._\n\n"
|
| 976 |
+
f"Scope: {', '.join(requested)}. Finley will post the final output."
|
| 977 |
),
|
| 978 |
)
|
| 979 |
+
await service.run_yolo(requested)
|
|
|
|
| 980 |
|
| 981 |
async def _cmd_yolo(self, client: Any, channel_id: str, args: str) -> None:
|
| 982 |
"""Run YOLO in the active session, using V7 baseline/session-delta context."""
|
tests/test_quant_v6/test_scope_routing.py
CHANGED
|
@@ -47,11 +47,16 @@ class _FakeClient:
|
|
| 47 |
class _FakeService:
|
| 48 |
def __init__(self, session_dir: Path) -> None:
|
| 49 |
self.dispatched: list[str] = []
|
|
|
|
|
|
|
| 50 |
self.session = SimpleNamespace(session_dir=session_dir)
|
| 51 |
|
| 52 |
async def dispatch(self, from_role: str, text: str) -> None:
|
| 53 |
self.dispatched.append(text)
|
| 54 |
|
|
|
|
|
|
|
|
|
|
| 55 |
|
| 56 |
class _FakeYoloService(_FakeService):
|
| 57 |
def __init__(self, session_dir: Path) -> None:
|
|
@@ -321,14 +326,16 @@ async def test_yolo_converts_upstream_human_route_to_next_planned_agent(tmp_path
|
|
| 321 |
|
| 322 |
|
| 323 |
@pytest.mark.asyncio
|
| 324 |
-
async def
|
| 325 |
integration = SlackIntegration.__new__(SlackIntegration)
|
| 326 |
service = _FakeService(tmp_path)
|
| 327 |
integration._sessions = {"C123": service}
|
| 328 |
|
| 329 |
await SlackIntegration._cmd_quant(integration, _FakeClient(), "C123", "SPY")
|
| 330 |
|
| 331 |
-
assert service.
|
|
|
|
|
|
|
| 332 |
|
| 333 |
|
| 334 |
@pytest.mark.asyncio
|
|
@@ -353,14 +360,16 @@ async def test_trend_analyst_hands_v6_scope_to_market_event_watcher(tmp_path: Pa
|
|
| 353 |
|
| 354 |
|
| 355 |
@pytest.mark.asyncio
|
| 356 |
-
async def
|
| 357 |
integration = SlackIntegration.__new__(SlackIntegration)
|
| 358 |
service = _FakeService(tmp_path)
|
| 359 |
integration._sessions = {"C123": service}
|
| 360 |
|
| 361 |
await SlackIntegration._cmd_quant(integration, _FakeClient(), "C123", "AAPL")
|
| 362 |
|
| 363 |
-
assert service.
|
|
|
|
|
|
|
| 364 |
|
| 365 |
|
| 366 |
@pytest.mark.asyncio
|
|
|
|
| 47 |
class _FakeService:
|
| 48 |
def __init__(self, session_dir: Path) -> None:
|
| 49 |
self.dispatched: list[str] = []
|
| 50 |
+
self.runs: list[list[str]] = []
|
| 51 |
+
self._mode = "investigation"
|
| 52 |
self.session = SimpleNamespace(session_dir=session_dir)
|
| 53 |
|
| 54 |
async def dispatch(self, from_role: str, text: str) -> None:
|
| 55 |
self.dispatched.append(text)
|
| 56 |
|
| 57 |
+
async def run_yolo(self, tickers: list[str]):
|
| 58 |
+
self.runs.append(tickers)
|
| 59 |
+
|
| 60 |
|
| 61 |
class _FakeYoloService(_FakeService):
|
| 62 |
def __init__(self, session_dir: Path) -> None:
|
|
|
|
| 326 |
|
| 327 |
|
| 328 |
@pytest.mark.asyncio
|
| 329 |
+
async def test_quant_command_uses_shared_runtime_for_specialized_markets(tmp_path: Path) -> None:
|
| 330 |
integration = SlackIntegration.__new__(SlackIntegration)
|
| 331 |
service = _FakeService(tmp_path)
|
| 332 |
integration._sessions = {"C123": service}
|
| 333 |
|
| 334 |
await SlackIntegration._cmd_quant(integration, _FakeClient(), "C123", "SPY")
|
| 335 |
|
| 336 |
+
assert service.runs == [["SPY"]]
|
| 337 |
+
assert service.dispatched == []
|
| 338 |
+
assert service._mode == "yolo"
|
| 339 |
|
| 340 |
|
| 341 |
@pytest.mark.asyncio
|
|
|
|
| 360 |
|
| 361 |
|
| 362 |
@pytest.mark.asyncio
|
| 363 |
+
async def test_quant_command_uses_shared_runtime_for_general_markets(tmp_path: Path) -> None:
|
| 364 |
integration = SlackIntegration.__new__(SlackIntegration)
|
| 365 |
service = _FakeService(tmp_path)
|
| 366 |
integration._sessions = {"C123": service}
|
| 367 |
|
| 368 |
await SlackIntegration._cmd_quant(integration, _FakeClient(), "C123", "AAPL")
|
| 369 |
|
| 370 |
+
assert service.runs == [["AAPL"]]
|
| 371 |
+
assert service.dispatched == []
|
| 372 |
+
assert service._mode == "yolo"
|
| 373 |
|
| 374 |
|
| 375 |
@pytest.mark.asyncio
|