yf176 commited on
Commit
56bdbb8
·
1 Parent(s): 61bb7f0

feat: V4.2 — VizAgent, PortfolioMonitorAgent, input templates, monitor/close/hold commands

Browse files
README.md CHANGED
@@ -13,27 +13,41 @@ pinned: false
13
 
14
  [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
15
  [![Python 3.11+](https://img.shields.io/badge/python-3.11+-blue.svg)](https://www.python.org/downloads/)
16
- [![Version](https://img.shields.io/badge/version-4.0.0-green.svg)](pyproject.toml)
17
 
18
  Polyhedra turns your workflow into a structured team of AI agents — four academic research agents **plus** a seven-agent quant paper-trading pipeline — all coordinated via `@mention` routing, Slack slash commands, and the `poly` CLI.
19
 
20
  ---
21
 
22
- ## What's New in v4.0
23
 
24
  | Feature | Description |
25
  |---------|-------------|
26
- | 📈 Quant paper-trading team | Seven specialized quant agents: DataFetcher → TechnicalAnalyst → SentimentAnalyst → FundamentalAnalyst → SignalAggregator → RiskManager → TradeExecutor |
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27
  | 💹 Live market data | OHLCV via **yfinance** (free, no key); news & earnings via **Finnhub** free tier |
28
  | 🛡️ Risk management | Dynamic position sizing, stop-loss / take-profit targets, portfolio heat checks |
29
  | 📊 Technical indicators | SMA, EMA, RSI, MACD computed locally from 90-day daily candles |
30
- | 📰 Sentiment scoring | Finnhub headline feed → LLM-scored sentiment per ticker |
31
- | 💼 Paper trades | Simulated fills logged to `session_dir/paper_trades.json` |
32
- | 📋 Watchlist commands | `/poly watchlist add|remove|show <TICKER>` (or `@Bot watchlist add <TICKER>`) |
33
- | 🔁 `@mention` routing | Any Slack `@mention` dispatches the same commands as slash commands |
34
- | ⚡ Auto-session | Watchlist and quant commands auto-create a session if none is active |
35
 
36
- > **Backward compatible** — all v3.x research agents and v2.x MCP tools continue to work unchanged.
37
 
38
  ---
39
 
@@ -49,17 +63,19 @@ Polyhedra turns your workflow into a structured team of AI agents — four acade
49
  | **Scribe** | Writer / Editor | Drafts paper sections, saves to `artifacts/` |
50
  | **Coordinator** | Orchestrator | Routes @mentions, gates costs, enforces loop limit (depth 3), updates state |
51
 
52
- ### Quant Team (v4.0)
53
 
54
  | Agent | Responsibility |
55
- |-------|----------------|
56
  | **DataFetcher** | Downloads OHLCV (yfinance) + news + earnings (Finnhub) for every watchlist ticker |
57
- | **TechnicalAnalyst** | Computes SMA/EMA crossovers, RSI overbought/oversold, MACD signals |
58
  | **SentimentAnalyst** | Scores news headlines via LLM, aggregates ticker sentiment |
59
- | **FundamentalAnalyst** | Parses earnings surprise, EPS trend, revenue signals |
60
- | **SignalAggregator** | Combines tech + sentiment + fundamental signals into a net score |
61
- | **RiskManager** | Sizes positions, sets stop-loss / take-profit, checks portfolio heat |
62
- | **TradeExecutor** | Logs simulated paper trades; enforces pre-trade risk gates |
 
 
63
 
64
  ---
65
 
@@ -162,9 +178,13 @@ poly mcp Start the legacy MCP server
162
  /poly watchlist add <TICKER>
163
  /poly watchlist remove <TICKER>
164
  /poly watchlist show
165
- /poly quant ← run full quant pipeline on watchlist
166
- /poly portfolio ← summary of open paper positions
167
- /poly trade ← status of last trade batch
 
 
 
 
168
  ```
169
 
170
  All slash commands are also available as `@BotName <command> <args>`.
 
13
 
14
  [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
15
  [![Python 3.11+](https://img.shields.io/badge/python-3.11+-blue.svg)](https://www.python.org/downloads/)
16
+ [![Version](https://img.shields.io/badge/version-4.2.0-green.svg)](pyproject.toml)
17
 
18
  Polyhedra turns your workflow into a structured team of AI agents — four academic research agents **plus** a seven-agent quant paper-trading pipeline — all coordinated via `@mention` routing, Slack slash commands, and the `poly` CLI.
19
 
20
  ---
21
 
22
+ ## What's New in v4.2
23
 
24
  | Feature | Description |
25
  |---------|-------------|
26
+ | 📊 **VizAgent** | Generates static PNG charts (candlestick + volume, RSI/MACD, backtest, risk heatmap, portfolio P&L) and posts them directly to Slack |
27
+ | 🔔 **PortfolioMonitorAgent** | Scheduled background monitor polls Finnhub for each open position; fires take-profit / stop-loss / ±% move alerts with pre-filled action templates |
28
+ | 🤖 **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) |
29
+ | 💬 `/poly monitor` | New slash command — pause, resume, or set the polling interval for the portfolio monitor |
30
+ | 🔴 `/poly trade close` | Close an open paper position; fetches real-time Finnhub price and logs P&L |
31
+ | ⏸ `/poly trade hold` | Suppress monitor alerts for a position for 1 hour |
32
+ | ⏱ Background scheduler | `mount_to_fastapi` launches an `asyncio` loop that dispatches `@portfoliomonitor` every N minutes (default 30, configurable via `POLYHEDRA_MONITOR_INTERVAL`) |
33
+
34
+ > **Backward compatible** — all v4.1 / v4.0 / v3.x / v2.x features continue to work unchanged.
35
+
36
+ <details>
37
+ <summary>Previous releases</summary>
38
+
39
+ ### v4.0 / v4.1
40
+
41
+ | Feature | Description |
42
+ |---------|-------------|
43
+ | 📈 Quant paper-trading team | Seven specialized quant agents: DataFetcher → TrendAnalyst → SentimentAnalyst → QuantResearcher → Backtester → RiskAnalyst → QuantStrategist |
44
  | 💹 Live market data | OHLCV via **yfinance** (free, no key); news & earnings via **Finnhub** free tier |
45
  | 🛡️ Risk management | Dynamic position sizing, stop-loss / take-profit targets, portfolio heat checks |
46
  | 📊 Technical indicators | SMA, EMA, RSI, MACD computed locally from 90-day daily candles |
47
+ | 📋 Watchlist commands | `/poly watchlist add|remove|show <TICKER>` |
48
+ | 💼 Trade proposals | `approve`, `reject`, `revise` from Slack |
 
 
 
49
 
50
+ </details>
51
 
52
  ---
53
 
 
63
  | **Scribe** | Writer / Editor | Drafts paper sections, saves to `artifacts/` |
64
  | **Coordinator** | Orchestrator | Routes @mentions, gates costs, enforces loop limit (depth 3), updates state |
65
 
66
+ ### Quant Team (v4.2)
67
 
68
  | Agent | Responsibility |
69
+ |-------|---------------|
70
  | **DataFetcher** | Downloads OHLCV (yfinance) + 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
+ | **QuantResearcher** | Synthesises fundamental + macro context |
74
+ | **Backtester** | Back-tests signal combinations against historical OHLCV data |
75
+ | **RiskAnalyst** | Sizes positions, sets stop-loss / take-profit, checks portfolio heat |
76
+ | **QuantStrategist** | Produces final paper-trade proposals (direction, size, entry, target, stop) |
77
+ | **VizAgent** 📊 | Generates candlestick, RSI/MACD, backtest, risk heatmap, and P&L PNG charts |
78
+ | **PortfolioMonitorAgent** 🔔 | Polls open positions on a schedule; fires threshold alerts with action templates |
79
 
80
  ---
81
 
 
178
  /poly watchlist add <TICKER>
179
  /poly watchlist remove <TICKER>
180
  /poly watchlist show
181
+ /poly quant ← run full quant pipeline on watchlist
182
+ /poly portfolio ← summary of open paper positions
183
+ /poly trade approve|reject|revise <id> ← act on a trade proposal
184
+ /poly trade close <id> ← close an open position (fetches live price)
185
+ /poly trade hold <id> ← suppress alerts for 1 hour
186
+ /poly monitor pause|resume ← pause / resume the background monitor
187
+ /poly monitor interval <minutes> ← change polling frequency
188
  ```
189
 
190
  All slash commands are also available as `@BotName <command> <args>`.
docs/polyhedraV4.2.md ADDED
@@ -0,0 +1,279 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Polyhedra V4.2 — Product Requirements Document
2
+
3
+ > Builds on V4.0 (quant team) and V4.1 (dynamic routing, per-agent artifacts). No changes to the research pipeline.
4
+
5
+ ---
6
+
7
+ ## Overview
8
+
9
+ V4.2 delivers three focused improvements to the quant team experience:
10
+
11
+ 1. **Coordinator Input Templates** — ranked, pre-filled message suggestions at every human touchpoint
12
+ 2. **Visualization Agent** — charts and visual summaries posted directly to Slack
13
+ 3. **Portfolio Monitor** — scheduled tracking of open paper positions with automated alerts
14
+
15
+ ---
16
+
17
+ ## 1. Coordinator Input Templates
18
+
19
+ ### Problem
20
+ At every human touchpoint — chain checkpoints, trade approvals, agent blocks, uncertainty states — the human must know the correct syntax, the right agent to mention, and the right command to issue. This creates friction and errors, especially for new users.
21
+
22
+ ### Solution
23
+ The Coordinator generates ranked, pre-filled input templates at every human touchpoint. Templates are ready-to-send messages the human can copy, send as-is, or edit.
24
+
25
+ ### Requirements
26
+
27
+ **FR-1.1** The Coordinator must generate templates at the following touchpoints:
28
+ - Chain-limit checkpoint (depth 3 reached)
29
+ - Trade proposals ready for review
30
+ - Agent blocked due to missing data
31
+ - Agent routes to `@human` due to uncertainty
32
+ - `/poly resume` after manual stop
33
+
34
+ **FR-1.2** Each template block must contain 2–4 ranked options. Option 1 is always the recommended path. The final option is always a safe exit (`/poly stop` or equivalent).
35
+
36
+ **FR-1.3** Every template must be a complete, sendable message including bot mention (`@PolyTest`), agent or command target, and any required arguments. No unfilled placeholders unless unavoidable.
37
+
38
+ **FR-1.4** Templates must be rule-based, not LLM-generated. The Coordinator constructs them from `QuantState`, the last agent's routing JSON (`{"next": "<role>"}"`), and a static `_ALT_AGENT_MAP`.
39
+
40
+ **FR-1.5** The `_ALT_AGENT_MAP` defines a sensible skip-forward alternative per pipeline stage:
41
+ ```python
42
+ _ALT_AGENT_MAP = {
43
+ "trendanalyst": "sentimentanalyst",
44
+ "sentimentanalyst": "quantresearcher",
45
+ "quantresearcher": "backtester",
46
+ "backtester": "riskanalyst",
47
+ "riskanalyst": "quantstrategist",
48
+ "quantstrategist": "human",
49
+ }
50
+ ```
51
+
52
+ **FR-1.6** If the Coordinator cannot determine a meaningful alternative agent, it shows 2 options instead of 3. It never shows a nonsensical alternative.
53
+
54
+ **FR-1.7** Templates are never shown mid-chain — only at human touchpoints.
55
+
56
+ ### Non-requirements
57
+ - Templates are not personalised or learned from user behaviour — V4.x future
58
+ - No LLM call is made to generate templates
59
+
60
+ ---
61
+
62
+ ## 2. Visualization Agent (`@vizagent`)
63
+
64
+ ### Problem
65
+ Agent outputs are rich but text-heavy. Humans reviewing trend analysis, backtest results, and trade proposals must parse walls of markdown to make decisions. A visual layer would significantly reduce cognitive load at review points.
66
+
67
+ ### Solution
68
+ A new `VizAgent` that generates charts and posts them directly to Slack as image attachments. Triggered by other agents via routing or directly by the human.
69
+
70
+ ### Agent Definition
71
+
72
+ | Field | Value |
73
+ |---|---|
74
+ | Role key | `vizagent` |
75
+ | Class | `VizAgent` |
76
+ | Title | Visualization Agent |
77
+ | LLM use | Minimal — selects chart type, writes caption |
78
+ | Triggers | Routed to by TrendAnalyst, Backtester, Strategist — or called directly by human |
79
+
80
+ ### Chart Types
81
+
82
+ | Chart | Triggered by | Data source |
83
+ |---|---|---|
84
+ | Candlestick + volume | TrendAnalyst | `quant/raw/<ticker>_<date>.json` |
85
+ | RSI + MACD overlay | TrendAnalyst | `quant/raw/<ticker>_<date>.json` |
86
+ | Signal backtest performance | Backtester | `quant/backtest_results_<date>.md` |
87
+ | Portfolio P&L over time | PortfolioMonitor | `QuantState.portfolio` |
88
+ | Risk heatmap (correlation) | RiskAnalyst | `quant/risk_assessment_<date>.md` |
89
+
90
+ ### Requirements
91
+
92
+ **FR-2.1** `VizAgent` must read artifact files via `FileWriter` — no direct data access.
93
+
94
+ **FR-2.2** Charts are generated using `matplotlib` or `plotly` (Python, server-side). Output is a PNG file uploaded to Slack via `files.upload`.
95
+
96
+ **FR-2.3** Each chart is saved to `quant/viz/<chart_type>_<ticker>_<date>.png` via `FileWriter`.
97
+
98
+ **FR-2.4** Every chart post includes a 2–3 sentence LLM-generated caption summarising the key visual insight.
99
+
100
+ **FR-2.5** `VizAgent` routing logic:
101
+ - After posting chart(s) → route to the agent that triggered it, or `@human` if triggered directly
102
+ - If data is insufficient to generate a meaningful chart → post a plain text summary instead, do not fail silently
103
+
104
+ **FR-2.6** `VizAgent` is available as a direct human invocation:
105
+ ```
106
+ @PolyTest @vizagent GLD candlestick
107
+ @PolyTest @vizagent GLD rsi
108
+ @PolyTest @vizagent portfolio
109
+ ```
110
+
111
+ **FR-2.7** TrendAnalyst and Backtester routing JSON may include `vizagent` as `next` when their outputs would benefit from visualization. This is optional — not every run requires charts.
112
+
113
+ ### Non-requirements
114
+ - Interactive charts — static PNG only in V4.2
115
+ - Real-time streaming charts — future
116
+ - Chart customisation by user — future
117
+
118
+ ---
119
+
120
+ ## 3. Portfolio Monitor (`@portfoliomonitor`)
121
+
122
+ ### Problem
123
+ Approved paper trades are written to `QuantState.portfolio` and then never watched. There is no mechanism to alert the human when a stop-loss or take-profit level is hit, or to track how positions are performing over time.
124
+
125
+ ### Solution
126
+ A scheduled `PortfolioMonitorAgent` that runs on a configurable interval, checks open positions against live prices, and posts alerts to Slack when thresholds are hit.
127
+
128
+ ### Agent Definition
129
+
130
+ | Field | Value |
131
+ |---|---|
132
+ | Role key | `portfoliomonitor` |
133
+ | Class | `PortfolioMonitorAgent` |
134
+ | Title | Portfolio Monitor |
135
+ | LLM use | Minimal — generates alert summaries |
136
+ | Triggers | Scheduled (configurable interval) or human-invoked via `/poly portfolio` |
137
+
138
+ ### Requirements
139
+
140
+ **FR-3.1** `PortfolioMonitorAgent` runs on a configurable schedule defined by `POLYHEDRA_MONITOR_INTERVAL` (default: every 30 minutes during market hours).
141
+
142
+ **FR-3.2** On each run, the monitor fetches the latest price for each ticker in `QuantState.portfolio` via Finnhub (real-time quote endpoint).
143
+
144
+ **FR-3.3** For each open position, the monitor evaluates:
145
+ - Has the take-profit level been reached?
146
+ - Has the stop-loss level been reached?
147
+ - Has the position moved more than X% since entry (configurable, default 2%)?
148
+
149
+ **FR-3.4** On threshold breach, the monitor posts an alert to Slack:
150
+ ```
151
+ 🚨 Portfolio Monitor — threshold breach
152
+
153
+ Position: GLD — Long @ 456.90
154
+ Current price: 465.10
155
+ Take-profit level: 463.77 ✅ reached
156
+
157
+ 💬 Suggested next messages:
158
+
159
+ 1. > /poly trade close <position_id> ← recommended
160
+ Close the position and lock in the paper gain.
161
+
162
+ 2. > /poly trade hold <position_id>
163
+ Keep the position open and monitor further.
164
+
165
+ 3. > @PolyTest @riskanalyst review <position_id>
166
+ Re-evaluate risk before deciding.
167
+ ```
168
+
169
+ **FR-3.5** The monitor does not close positions automatically. The human makes all close decisions.
170
+
171
+ **FR-3.6** `PortfolioMonitorAgent` writes a daily position summary to `quant/portfolio_log_<date>.md` via `FileWriter`.
172
+
173
+ **FR-3.7** `/poly portfolio` triggers an immediate monitor run outside the schedule and posts the current portfolio state to Slack.
174
+
175
+ **FR-3.8** Market hours awareness — the monitor does not run outside market hours (09:30–16:00 ET, Mon–Fri). Configurable via `POLYHEDRA_MARKET_TZ` (default: `America/New_York`).
176
+
177
+ **FR-3.9** New slash commands:
178
+
179
+ | Command | Action |
180
+ |---|---|
181
+ | `/poly trade close <id>` | Close a paper position |
182
+ | `/poly trade hold <id>` | Explicitly mark as hold, suppress further alerts for 1 hour |
183
+ | `/poly monitor pause` | Pause scheduled monitoring |
184
+ | `/poly monitor resume` | Resume scheduled monitoring |
185
+ | `/poly monitor interval <minutes>` | Change monitoring interval |
186
+
187
+ ### Non-requirements
188
+ - Automatic position closing — human decides always
189
+ - Portfolio optimisation suggestions — future (V4.x)
190
+ - Multi-session portfolio aggregation — future
191
+
192
+ ---
193
+
194
+ ## New Environment Variables
195
+
196
+ ```
197
+ POLYHEDRA_MONITOR_INTERVAL Monitor run interval in minutes (default: 30)
198
+ POLYHEDRA_MARKET_TZ Market timezone (default: America/New_York)
199
+ ```
200
+
201
+ ---
202
+
203
+ ## Session Filesystem Additions
204
+
205
+ ```
206
+ ~/.polyhedra/sessions/<session_id>/
207
+ quant/
208
+ viz/
209
+ <chart_type>_<ticker>_<date>.png VizAgent chart outputs
210
+ portfolio_log_<date>.md PortfolioMonitor daily summary
211
+ ```
212
+
213
+ ---
214
+
215
+ ## QuantState Additions
216
+
217
+ ```python
218
+ @dataclass
219
+ class PaperPosition:
220
+ position_id: str
221
+ ticker: str
222
+ direction: str # "long" or "short"
223
+ entry_price: float
224
+ entry_date: str # ISO date
225
+ take_profit: float
226
+ stop_loss: float
227
+ size_pct: float # % of paper portfolio
228
+ status: str # "open", "closed", "hold"
229
+ close_price: float | None
230
+ close_date: str | None
231
+
232
+ @dataclass
233
+ class QuantState:
234
+ ... # existing fields unchanged
235
+ portfolio: list[PaperPosition]
236
+ trade_log: list[TradeEvent]
237
+ monitor_paused: bool # controlled by /poly monitor pause|resume
238
+ last_monitor_run: str | None
239
+ ```
240
+
241
+ ---
242
+
243
+ ## Implementation Checklist
244
+
245
+ ### Coordinator Input Templates
246
+ - [ ] `_ALT_AGENT_MAP` defined in `coordinator.py`
247
+ - [ ] Template builder per touchpoint type (checkpoint, block, uncertainty, trade approval, resume)
248
+ - [ ] Template injected into every Coordinator human-facing post
249
+
250
+ ### VizAgent
251
+ - [ ] `VizAgent` class — `src/polyhedra/agents/vizagent.py`
252
+ - [ ] Chart generation per type (candlestick, RSI/MACD, backtest performance, P&L, risk heatmap)
253
+ - [ ] Slack `files.upload` integration in `slack.py`
254
+ - [ ] `quant/viz/` artifact directory
255
+ - [ ] Direct human invocation parsing (`@vizagent GLD candlestick`)
256
+ - [ ] Register in role registry and `_ROLE_DISPLAY`
257
+
258
+ ### Portfolio Monitor
259
+ - [ ] `PortfolioMonitorAgent` class — `src/polyhedra/agents/portfoliomonitor.py`
260
+ - [ ] Scheduled runner — APScheduler or equivalent, wired into `app.py`
261
+ - [ ] Market hours check (09:30–16:00 ET, Mon–Fri)
262
+ - [ ] Finnhub real-time quote fetch per position
263
+ - [ ] Threshold evaluation logic (take-profit, stop-loss, % move)
264
+ - [ ] Alert post with input templates
265
+ - [ ] `PaperPosition` dataclass + `QuantState` updates
266
+ - [ ] `/poly trade close|hold` commands
267
+ - [ ] `/poly monitor pause|resume|interval` commands
268
+ - [ ] `portfolio_log_<date>.md` artifact write
269
+ - [ ] `POLYHEDRA_MONITOR_INTERVAL` + `POLYHEDRA_MARKET_TZ` env vars
270
+
271
+ ---
272
+
273
+ ## Out of Scope for V4.2
274
+ - Research pipeline dynamic routing — postponed indefinitely
275
+ - Cross-team bridging — future
276
+ - Interactive / real-time charts — future
277
+ - Portfolio optimisation agent — future
278
+ - Multi-session portfolio aggregation — future
279
+ - User behaviour-based template personalisation — future
pyproject.toml CHANGED
@@ -1,6 +1,6 @@
1
  [project]
2
  name = "polyhedra"
3
- version = "4.0.0"
4
  description = "Collaborative multi-agent research team with Slack/Teams/CLI, MCP server, and quant paper-trading simulation"
5
  readme = "README.md"
6
  requires-python = ">=3.11"
 
1
  [project]
2
  name = "polyhedra"
3
+ version = "4.2.0"
4
  description = "Collaborative multi-agent research team with Slack/Teams/CLI, MCP server, and quant paper-trading simulation"
5
  readme = "README.md"
6
  requires-python = ">=3.11"
src/polyhedra/agents/coordinator.py CHANGED
@@ -40,8 +40,20 @@ _QUANT_ROLES: frozenset[str] = frozenset({
40
  "backtester",
41
  "riskanalyst",
42
  "quantstrategist",
 
 
43
  })
44
 
 
 
 
 
 
 
 
 
 
 
45
 
46
  class _CostRejected(Exception):
47
  """Sentinel raised when the user declines a cost-gated operation."""
@@ -55,6 +67,103 @@ class CheckpointResult:
55
  response: str = "" # "yes" | "adjust" | "stop" | free-text
56
 
57
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
58
  class CoordinatorAgent(Agent):
59
  """
60
  Orchestration agent — always active, never deselected.
@@ -171,14 +280,16 @@ class CoordinatorService:
171
  if depth >= _MAX_MENTION_DEPTH:
172
  if is_quant:
173
  # Mid-chain quant checkpoint — pause and reset, don't hard-stop
 
 
 
174
  await self._post(
175
  "coordinator",
176
  f"⏸ **Coordinator** — quant pipeline mid-chain checkpoint "
177
  f"(depth {_MAX_MENTION_DEPTH} reached).\n\n"
178
  f"Analysis so far is complete and has been saved. "
179
- f"To continue to **@{mention.mentioned_role}**, reply with:\n"
180
- f"`@PolyTest @{mention.mentioned_role} continue`\n\n"
181
- "This is a natural human review point — check the quant artifacts before proceeding.",
182
  )
183
  depth_dict[origin_id] = 0 # reset for next segment
184
  else:
@@ -244,9 +355,11 @@ class CoordinatorService:
244
 
245
  if entry.is_human:
246
  # Forward to the human via a highlighted thread message
 
247
  await self._post(
248
  "coordinator",
249
- f"📨 **Coordinator** → @human (holding role *{entry.role}*): {mention.content}",
 
250
  )
251
  return
252
 
 
40
  "backtester",
41
  "riskanalyst",
42
  "quantstrategist",
43
+ "vizagent",
44
+ "portfoliomonitor",
45
  })
46
 
47
+ # V4.2 — sensible skip-forward alternative per pipeline stage (FR-1.5)
48
+ _ALT_AGENT_MAP: dict[str, str] = {
49
+ "trendanalyst": "sentimentanalyst",
50
+ "sentimentanalyst": "quantresearcher",
51
+ "quantresearcher": "backtester",
52
+ "backtester": "riskanalyst",
53
+ "riskanalyst": "quantstrategist",
54
+ "quantstrategist": "human",
55
+ }
56
+
57
 
58
  class _CostRejected(Exception):
59
  """Sentinel raised when the user declines a cost-gated operation."""
 
67
  response: str = "" # "yes" | "adjust" | "stop" | free-text
68
 
69
 
70
+ # --------------------------------------------------------------------------- #
71
+ # Input template builder (V4.2 FR-1.x)
72
+ # --------------------------------------------------------------------------- #
73
+
74
+ def _build_input_templates(
75
+ touchpoint: str,
76
+ *,
77
+ next_role: str | None = None,
78
+ proposal_id: str | None = None,
79
+ session_id: str | None = None,
80
+ ) -> str:
81
+ """
82
+ Build ranked, pre-filled input templates for a given human touchpoint.
83
+ Rule-based — no LLM call (FR-1.4).
84
+ """
85
+ options = _template_options(touchpoint, next_role=next_role, proposal_id=proposal_id, session_id=session_id)
86
+ if not options:
87
+ return ""
88
+ lines = ["\n💬 *Suggested next messages:*\n"]
89
+ for i, (msg, desc) in enumerate(options, 1):
90
+ lines.append(f"{i}. > `{msg}`")
91
+ lines.append(f" _{desc}_")
92
+ lines.append("")
93
+ return "\n".join(lines)
94
+
95
+
96
+ _STOP = "/poly stop"
97
+ _QUANT_REPORT = "/poly quant report"
98
+
99
+
100
+ def _template_options(
101
+ touchpoint: str,
102
+ *,
103
+ next_role: str | None,
104
+ proposal_id: str | None,
105
+ session_id: str | None,
106
+ ) -> list[tuple[str, str]]:
107
+ """Return the ordered (message, description) pairs for a touchpoint."""
108
+ builders = {
109
+ "checkpoint": _opts_checkpoint,
110
+ "trade_proposals": _opts_trade_proposals,
111
+ "agent_blocked": _opts_agent_blocked,
112
+ "uncertainty": _opts_uncertainty,
113
+ "resume": _opts_resume,
114
+ }
115
+ builder = builders.get(touchpoint)
116
+ if builder is None:
117
+ return [(_STOP, "Stop the pipeline.")]
118
+ return builder(next_role=next_role, proposal_id=proposal_id, session_id=session_id)
119
+
120
+
121
+ def _opts_checkpoint(*, next_role: str | None, **_: Any) -> list[tuple[str, str]]:
122
+ alt = _ALT_AGENT_MAP.get(next_role or "") if next_role else None
123
+ opts: list[tuple[str, str]] = []
124
+ if next_role:
125
+ opts.append((f"@PolyTest @{next_role} continue", f"Recommended — continue to @{next_role}."))
126
+ if alt and alt != next_role and alt != "human":
127
+ opts.append((f"@PolyTest @{alt} continue", f"Skip to @{alt} if you've already reviewed."))
128
+ opts.append((_STOP, "Stop and review artifacts before continuing."))
129
+ return opts
130
+
131
+
132
+ def _opts_trade_proposals(*, proposal_id: str | None, **_: Any) -> list[tuple[str, str]]:
133
+ pid = proposal_id or "<proposal_id>"
134
+ return [
135
+ (f"/poly trade approve {pid}", "Approve and add to the paper portfolio."),
136
+ (f"/poly trade reject {pid} <reason>", "Reject the proposal with an optional reason."),
137
+ (f"/poly trade revise {pid}", "Send back to QuantStrategist for revision."),
138
+ (_STOP, "Stop and review before deciding."),
139
+ ]
140
+
141
+
142
+ def _opts_agent_blocked(*, next_role: str | None, **_: Any) -> list[tuple[str, str]]:
143
+ opts: list[tuple[str, str]] = []
144
+ if next_role:
145
+ opts.append((f"@PolyTest @{next_role} continue", f"Dispatch @{next_role} to produce missing data."))
146
+ opts += [(_QUANT_REPORT, "Check which artifacts are available."), (_STOP, "Stop and investigate manually.")]
147
+ return opts
148
+
149
+
150
+ def _opts_uncertainty(*, next_role: str | None, **_: Any) -> list[tuple[str, str]]:
151
+ opts: list[tuple[str, str]] = []
152
+ if next_role:
153
+ opts.append((f"@PolyTest @{next_role} continue", "Proceed — agent flagged uncertainty, not a hard block."))
154
+ opts += [(_QUANT_REPORT, "Review current state before proceeding."), (_STOP, "Stop and reassess.")]
155
+ return opts
156
+
157
+
158
+ def _opts_resume(*, session_id: str | None, **_: Any) -> list[tuple[str, str]]:
159
+ sid = session_id or "<session_id>"
160
+ return [
161
+ (f"/poly resume {sid}", "Resume the session from where it left off."),
162
+ (_QUANT_REPORT, "See a summary of the last quant run before resuming."),
163
+ (_STOP, "Do not resume — end the pipeline here."),
164
+ ]
165
+
166
+
167
  class CoordinatorAgent(Agent):
168
  """
169
  Orchestration agent — always active, never deselected.
 
280
  if depth >= _MAX_MENTION_DEPTH:
281
  if is_quant:
282
  # Mid-chain quant checkpoint — pause and reset, don't hard-stop
283
+ templates = _build_input_templates(
284
+ "checkpoint", next_role=mention.mentioned_role
285
+ )
286
  await self._post(
287
  "coordinator",
288
  f"⏸ **Coordinator** — quant pipeline mid-chain checkpoint "
289
  f"(depth {_MAX_MENTION_DEPTH} reached).\n\n"
290
  f"Analysis so far is complete and has been saved. "
291
+ f"This is a natural human review point — check the quant artifacts before proceeding."
292
+ f"{templates}",
 
293
  )
294
  depth_dict[origin_id] = 0 # reset for next segment
295
  else:
 
355
 
356
  if entry.is_human:
357
  # Forward to the human via a highlighted thread message
358
+ templates = _build_input_templates("uncertainty", next_role=entry.role)
359
  await self._post(
360
  "coordinator",
361
+ f"📨 **Coordinator** → @human (holding role *{entry.role}*): {mention.content}"
362
+ f"{templates}",
363
  )
364
  return
365
 
src/polyhedra/agents/quant/__init__.py CHANGED
@@ -1,4 +1,4 @@
1
- """Polyhedra V4.0 quant agent package."""
2
 
3
  from polyhedra.agents.quant.datafetcher import DataFetcherAgent
4
  from polyhedra.agents.quant.trendanalyst import TrendAnalystAgent
@@ -7,6 +7,8 @@ from polyhedra.agents.quant.quantresearcher import QuantResearcherAgent
7
  from polyhedra.agents.quant.backtester import BacktesterAgent
8
  from polyhedra.agents.quant.riskanalyst import RiskAnalystAgent
9
  from polyhedra.agents.quant.quantstrategist import QuantStrategistAgent
 
 
10
 
11
  __all__ = [
12
  "DataFetcherAgent",
@@ -16,4 +18,6 @@ __all__ = [
16
  "BacktesterAgent",
17
  "RiskAnalystAgent",
18
  "QuantStrategistAgent",
 
 
19
  ]
 
1
+ """Polyhedra V4.0/V4.2 quant agent package."""
2
 
3
  from polyhedra.agents.quant.datafetcher import DataFetcherAgent
4
  from polyhedra.agents.quant.trendanalyst import TrendAnalystAgent
 
7
  from polyhedra.agents.quant.backtester import BacktesterAgent
8
  from polyhedra.agents.quant.riskanalyst import RiskAnalystAgent
9
  from polyhedra.agents.quant.quantstrategist import QuantStrategistAgent
10
+ from polyhedra.agents.quant.vizagent import VizAgent
11
+ from polyhedra.agents.quant.portfoliomonitor import PortfolioMonitorAgent
12
 
13
  __all__ = [
14
  "DataFetcherAgent",
 
18
  "BacktesterAgent",
19
  "RiskAnalystAgent",
20
  "QuantStrategistAgent",
21
+ "VizAgent",
22
+ "PortfolioMonitorAgent",
23
  ]
src/polyhedra/agents/quant/portfoliomonitor.py ADDED
@@ -0,0 +1,275 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """PortfolioMonitorAgent — Portfolio Monitor for Polyhedra V4.2.
2
+
3
+ Runs on a configurable schedule (default 30 min) during market hours
4
+ (09:30-16:00 ET, Mon-Fri). On each run:
5
+
6
+ 1. Fetches the latest price for each open position via Finnhub.
7
+ 2. Evaluates take-profit, stop-loss, and ±X% move thresholds.
8
+ 3. Posts a Slack alert when any threshold is breached.
9
+ 4. Writes a daily position summary to quant/portfolio_log_<date>.md.
10
+
11
+ DISCLAIMER: Paper trading simulation only. No real capital.
12
+ Not financial advice. All decisions belong to the human.
13
+
14
+ Environment variables:
15
+ POLYHEDRA_MONITOR_INTERVAL Interval in minutes between monitor runs (default: 30)
16
+ POLYHEDRA_MARKET_TZ Market timezone (default: America/New_York)
17
+ POLYHEDRA_ALERT_MOVE_PCT Alert threshold for position moves (default: 2.0)
18
+ FINNHUB_API_KEY Finnhub API key
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ import logging
24
+ import os
25
+ from datetime import date, datetime, timezone
26
+ from typing import Any
27
+
28
+ from polyhedra.agents.base import Agent, AgentResponse, Mention
29
+ from polyhedra.services.llm_service import LLMService
30
+
31
+ logger = logging.getLogger(__name__)
32
+
33
+ _DEFAULT_INTERVAL_MINUTES = 30
34
+ _DEFAULT_ALERT_MOVE_PCT = 2.0
35
+ _MARKET_OPEN_HOUR = 9
36
+ _MARKET_OPEN_MIN = 30
37
+ _MARKET_CLOSE_HOUR = 16
38
+ _MARKET_CLOSE_MIN = 0
39
+
40
+
41
+ def _is_market_hours(tz_name: str = "America/New_York") -> bool:
42
+ """Return True if the current time is within market hours (Mon-Fri 09:30-16:00 ET)."""
43
+ try:
44
+ import zoneinfo
45
+ tz = zoneinfo.ZoneInfo(tz_name)
46
+ except Exception:
47
+ try:
48
+ from datetime import timezone as _tz
49
+ import importlib
50
+ zi = importlib.import_module("zoneinfo")
51
+ tz = zi.ZoneInfo(tz_name)
52
+ except Exception:
53
+ # Fallback: assume market hours if we cannot determine timezone
54
+ return True
55
+
56
+ now = datetime.now(tz=tz)
57
+ if now.weekday() >= 5: # Saturday=5, Sunday=6
58
+ return False
59
+ open_time = now.replace(hour=_MARKET_OPEN_HOUR, minute=_MARKET_OPEN_MIN, second=0, microsecond=0)
60
+ close_time = now.replace(hour=_MARKET_CLOSE_HOUR, minute=_MARKET_CLOSE_MIN, second=0, microsecond=0)
61
+ return open_time <= now < close_time
62
+
63
+
64
+ class PortfolioMonitorAgent(Agent):
65
+ """
66
+ Portfolio Monitor — checks open paper positions against live prices
67
+ and posts alerts when thresholds are breached.
68
+
69
+ The agent does NOT close positions. Human makes all close decisions.
70
+ """
71
+
72
+ name = "PortfolioMonitor"
73
+ role = "portfoliomonitor"
74
+ role_title = "Portfolio Monitor"
75
+ system_prompt = (
76
+ "You are PortfolioMonitor, the Portfolio Monitor for a paper trading research team. "
77
+ "IMPORTANT: This is a paper trading simulation only. No real capital is involved. "
78
+ "This output does not constitute financial advice of any kind. "
79
+ "Your job is to monitor open paper positions, detect threshold breaches, "
80
+ "and alert the human so they can make an informed decision. "
81
+ "You NEVER close positions — the human decides."
82
+ )
83
+
84
+ def __init__(self, llm_service: LLMService | None = None) -> None:
85
+ super().__init__()
86
+ self._llm = llm_service or LLMService()
87
+ self._alert_move_pct: float = float(os.environ.get("POLYHEDRA_ALERT_MOVE_PCT", _DEFAULT_ALERT_MOVE_PCT))
88
+ self._market_tz: str = os.environ.get("POLYHEDRA_MARKET_TZ", "America/New_York")
89
+
90
+ async def can_handle(self, mention: Mention) -> bool:
91
+ return mention.mentioned_role == self.role
92
+
93
+ async def handle(
94
+ self,
95
+ mention: Mention,
96
+ thread_context: list[dict[str, Any]],
97
+ research_state: dict[str, Any],
98
+ ) -> AgentResponse:
99
+ today = date.today().isoformat()
100
+ qs = research_state.get("quant_state") or {}
101
+
102
+ # Respect pause flag (FR-3.1 / monitor pause command)
103
+ if qs.get("monitor_paused", False):
104
+ return AgentResponse(
105
+ agent_role=self.role,
106
+ content=(
107
+ "⏸ **PortfolioMonitor** — monitoring is paused. "
108
+ "Use `/poly monitor resume` to re-enable."
109
+ ),
110
+ mentions=[],
111
+ )
112
+
113
+ # Check market hours unless explicitly invoked by a human command
114
+ is_direct_invoke = "portfolio" in mention.content.lower() or mention.from_role == "human"
115
+ if not is_direct_invoke and not _is_market_hours(self._market_tz):
116
+ return AgentResponse(
117
+ agent_role=self.role,
118
+ content="⏸ **PortfolioMonitor** — outside market hours. Next run at market open.",
119
+ mentions=[],
120
+ )
121
+
122
+ portfolio: list[dict] = qs.get("portfolio", [])
123
+ open_positions = [p for p in portfolio if p.get("status") == "open"]
124
+
125
+ if not open_positions:
126
+ content = (
127
+ "📈 **PortfolioMonitor** — no open paper positions to monitor.\n\n"
128
+ "_⚠️ Paper trading simulation only. Not financial advice._"
129
+ )
130
+ self._write_daily_log(today, content, [])
131
+ return AgentResponse(agent_role=self.role, content=content, mentions=[])
132
+
133
+ # Fetch live prices
134
+ prices = await self._fetch_prices([p["ticker"] for p in open_positions])
135
+
136
+ # Evaluate thresholds
137
+ alerts: list[dict] = []
138
+ position_lines: list[str] = []
139
+
140
+ for pos in open_positions:
141
+ ticker = pos.get("ticker", "?")
142
+ entry = float(pos.get("entry_price", 0))
143
+ direction = pos.get("direction", "long").lower()
144
+ tp = pos.get("take_profit")
145
+ sl = pos.get("stop_loss")
146
+ current = prices.get(ticker)
147
+
148
+ if current is None or current <= 0:
149
+ position_lines.append(f"• {ticker} — price unavailable")
150
+ continue
151
+
152
+ pct_move = ((current - entry) / entry * 100) if entry > 0 else 0
153
+ if direction == "short":
154
+ pct_move = -pct_move
155
+
156
+ breaches: list[str] = []
157
+ if tp and self._tp_breached(direction, current, float(tp)):
158
+ breaches.append(f"Take-profit level: {tp} ✅ reached")
159
+ if sl and self._sl_breached(direction, current, float(sl)):
160
+ breaches.append(f"Stop-loss level: {sl} 🚨 hit")
161
+ if abs(pct_move) >= self._alert_move_pct:
162
+ sign = "+" if pct_move >= 0 else ""
163
+ breaches.append(f"Moved {sign}{pct_move:.1f}% since entry")
164
+
165
+ if breaches:
166
+ alerts.append({
167
+ "position_id": pos.get("position_id", ticker),
168
+ "ticker": ticker,
169
+ "direction": direction,
170
+ "entry": entry,
171
+ "current": current,
172
+ "breaches": breaches,
173
+ })
174
+
175
+ sign = "+" if pct_move >= 0 else ""
176
+ position_lines.append(
177
+ f"• {ticker} {direction.upper()} @ {entry:.2f} → {current:.2f} ({sign}{pct_move:.1f}%)"
178
+ )
179
+
180
+ # Build response
181
+ content_parts = [
182
+ "📈 **PortfolioMonitor** — portfolio check",
183
+ "_⚠️ Paper trading simulation only. Not financial advice._\n",
184
+ f"**Open positions ({len(open_positions)}):**",
185
+ *position_lines,
186
+ ]
187
+
188
+ if alerts:
189
+ content_parts.append("\n---")
190
+ for alert in alerts:
191
+ pid = alert["position_id"]
192
+ breach_text = "\n".join(alert["breaches"])
193
+ content_parts.append(
194
+ f"\n🚨 **Portfolio Monitor — threshold breach**\n\n"
195
+ f"Position: {alert['ticker']} — {alert['direction'].title()} @ {alert['entry']}\n"
196
+ f"Current price: {alert['current']:.2f}\n"
197
+ f"{breach_text}\n\n"
198
+ f"💬 *Suggested next messages:*\n\n"
199
+ f"1. > `/poly trade close {pid}` ← recommended\n"
200
+ f" _Close the position and lock in the paper result._\n\n"
201
+ f"2. > `/poly trade hold {pid}`\n"
202
+ f" _Keep the position open and suppress alerts for 1 hour._\n\n"
203
+ f"3. > `@PolyTest @riskanalyst review {pid}`\n"
204
+ f" _Re-evaluate risk before deciding._"
205
+ )
206
+
207
+ ts = datetime.now(tz=timezone.utc).strftime("%H%M UTC")
208
+ content_parts.append(f"\n_Last checked: {today} {ts}_")
209
+
210
+ content = "\n".join(content_parts)
211
+
212
+ # Write daily log (FR-3.6)
213
+ self._write_daily_log(today, content, alerts)
214
+
215
+ # Update last_monitor_run in state
216
+ return AgentResponse(
217
+ agent_role=self.role,
218
+ content=content,
219
+ mentions=[],
220
+ artifact_path=f"quant/portfolio_log_{today}.md",
221
+ artifact_mode="append",
222
+ updates_state=True,
223
+ state_patch={"quant_state": {"last_monitor_run": datetime.now(tz=timezone.utc).isoformat()}},
224
+ )
225
+
226
+ # ------------------------------------------------------------------ #
227
+ # Threshold helpers
228
+ # ------------------------------------------------------------------ #
229
+
230
+ def _tp_breached(self, direction: str, current: float, tp: float) -> bool:
231
+ return current >= tp if direction == "long" else current <= tp
232
+
233
+ def _sl_breached(self, direction: str, current: float, sl: float) -> bool:
234
+ return current <= sl if direction == "long" else current >= sl
235
+
236
+ # ------------------------------------------------------------------ #
237
+ # Price fetching via Finnhub
238
+ # ------------------------------------------------------------------ #
239
+
240
+ async def _fetch_prices(self, tickers: list[str]) -> dict[str, float | None]:
241
+ """Fetch latest quote for each ticker. Returns {ticker: price}."""
242
+ from polyhedra.services.finnhub import FinnhubService
243
+ service = FinnhubService()
244
+ prices: dict[str, float | None] = {}
245
+ seen: set[str] = set()
246
+ for ticker in tickers:
247
+ ticker = ticker.upper()
248
+ if ticker in seen:
249
+ continue
250
+ seen.add(ticker)
251
+ try:
252
+ quote = await service.get_quote(ticker)
253
+ prices[ticker] = quote.get("c") # current price
254
+ except Exception as exc:
255
+ logger.warning("PortfolioMonitor: price fetch failed for %s: %s", ticker, exc)
256
+ prices[ticker] = None
257
+ return prices
258
+
259
+ # ------------------------------------------------------------------ #
260
+ # Daily log
261
+ # ------------------------------------------------------------------ #
262
+
263
+ def _write_daily_log(self, today: str, content: str, alerts: list[dict]) -> None:
264
+ ts = datetime.now(tz=timezone.utc).strftime("%H:%M UTC")
265
+ log_path = f"quant/portfolio_log_{today}.md"
266
+ entry = (
267
+ f"\n## Monitor run — {today} {ts}\n\n"
268
+ f"{content}\n\n"
269
+ f"**Alerts this run:** {len(alerts)}\n"
270
+ "---\n"
271
+ )
272
+ try:
273
+ self.files.write(log_path, entry, mode="append")
274
+ except Exception as exc:
275
+ logger.warning("PortfolioMonitor: could not write daily log: %s", exc)
src/polyhedra/agents/quant/routing.py CHANGED
@@ -22,6 +22,8 @@ QUANT_ROLES: frozenset[str] = frozenset({
22
  "backtester",
23
  "riskanalyst",
24
  "quantstrategist",
 
 
25
  "human",
26
  })
27
 
 
22
  "backtester",
23
  "riskanalyst",
24
  "quantstrategist",
25
+ "vizagent",
26
+ "portfoliomonitor",
27
  "human",
28
  })
29
 
src/polyhedra/agents/quant/vizagent.py ADDED
@@ -0,0 +1,432 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """VizAgent — Visualization Agent for Polyhedra V4.2.
2
+
3
+ Generates charts (candlestick+volume, RSI/MACD, backtest performance,
4
+ risk heatmap, portfolio P&L) and posts them to Slack as static PNG files.
5
+
6
+ Triggered by TrendAnalyst, Backtester, RiskAnalyst, or directly by the human.
7
+
8
+ All file I/O uses FileWriter (FR-2.1).
9
+ Charts saved to quant/viz/<chart_type>_<ticker>_<date>.png (FR-2.3).
10
+
11
+ Non-requirements: interactive charts, real-time streaming, chart customisation.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import io
17
+ import json
18
+ import logging
19
+ import re
20
+ from datetime import date, datetime, timezone
21
+ from typing import Any
22
+
23
+ from polyhedra.agents.base import Agent, AgentResponse, Mention
24
+ from polyhedra.agents.quant.routing import LLM_ROUTING_PROMPT, parse_llm_routing
25
+ from polyhedra.services.llm_service import LLMService
26
+
27
+ logger = logging.getLogger(__name__)
28
+
29
+ # Map of chart-type keywords the human can specify in a direct mention
30
+ _CHART_KEYWORDS: dict[str, str] = {
31
+ "candlestick": "candlestick",
32
+ "candle": "candlestick",
33
+ "rsi": "rsi_macd",
34
+ "macd": "rsi_macd",
35
+ "backtest": "backtest",
36
+ "risk": "risk_heatmap",
37
+ "heatmap": "risk_heatmap",
38
+ "portfolio": "portfolio_pnl",
39
+ "pnl": "portfolio_pnl",
40
+ "p&l": "portfolio_pnl",
41
+ }
42
+
43
+
44
+ class VizAgent(Agent):
45
+ """Visualization Agent — generates and posts charts to Slack."""
46
+
47
+ name = "VizAgent"
48
+ role = "vizagent"
49
+ role_title = "Visualization Agent"
50
+ system_prompt = (
51
+ "You are VizAgent, the Visualization Agent for a paper trading research team. "
52
+ "Your job is to select the most useful chart type for the available data, "
53
+ "generate it, and write a concise 2-3 sentence caption explaining the key insight. "
54
+ "IMPORTANT: This is a paper trading simulation only. Not financial advice."
55
+ )
56
+
57
+ def __init__(self, llm_service: LLMService | None = None) -> None:
58
+ super().__init__()
59
+ self._llm = llm_service or LLMService()
60
+ # Injected by the Slack layer after chart generation for file upload
61
+ self._pending_chart_bytes: dict[str, bytes] = {}
62
+
63
+ async def can_handle(self, mention: Mention) -> bool:
64
+ return mention.mentioned_role == self.role
65
+
66
+ async def handle(
67
+ self,
68
+ mention: Mention,
69
+ thread_context: list[dict[str, Any]],
70
+ research_state: dict[str, Any],
71
+ ) -> AgentResponse:
72
+ today = date.today().isoformat()
73
+ content_lower = mention.content.lower()
74
+
75
+ # --- Determine chart type(s) and optional ticker from the mention ---
76
+ chart_type = self._detect_chart_type(content_lower)
77
+ ticker = self._detect_ticker(mention.content)
78
+
79
+ # --- Detect who triggered us to route back correctly (FR-2.5) ---
80
+ trigger_role = mention.from_role if mention.from_role != "human" else None
81
+
82
+ artifacts: list[str] = []
83
+ errors: list[str] = []
84
+
85
+ try:
86
+ import matplotlib # type: ignore[import-untyped]
87
+ matplotlib.use("Agg") # non-interactive backend
88
+ import matplotlib.pyplot as plt # type: ignore[import-untyped]
89
+ except ImportError:
90
+ return AgentResponse(
91
+ agent_role=self.role,
92
+ content=(
93
+ "📊 **VizAgent** — `matplotlib` is not installed. "
94
+ "Install it with `pip install matplotlib` to enable charting."
95
+ ),
96
+ mentions=[trigger_role] if trigger_role else [],
97
+ )
98
+
99
+ if chart_type in ("candlestick", None):
100
+ t = ticker or self._latest_ticker(today)
101
+ if t:
102
+ path, err = self._chart_candlestick(t, today, plt)
103
+ if path:
104
+ artifacts.append(path)
105
+ elif err:
106
+ errors.append(err)
107
+
108
+ if chart_type in ("rsi_macd", None):
109
+ t = ticker or self._latest_ticker(today)
110
+ if t:
111
+ path, err = self._chart_rsi_macd(t, today, plt)
112
+ if path:
113
+ artifacts.append(path)
114
+ elif err:
115
+ errors.append(err)
116
+
117
+ if chart_type in ("backtest", None):
118
+ path, err = self._chart_backtest(today, plt)
119
+ if path:
120
+ artifacts.append(path)
121
+ elif err:
122
+ errors.append(err)
123
+
124
+ if chart_type in ("risk_heatmap", None):
125
+ path, err = self._chart_risk_heatmap(today, plt)
126
+ if path:
127
+ artifacts.append(path)
128
+ elif err:
129
+ errors.append(err)
130
+
131
+ if chart_type in ("portfolio_pnl", None):
132
+ path, err = self._chart_portfolio_pnl(research_state, today, plt)
133
+ if path:
134
+ artifacts.append(path)
135
+ elif err:
136
+ errors.append(err)
137
+
138
+ # --- Generate captions via LLM (FR-2.4) ---
139
+ caption = await self._generate_caption(chart_type, ticker, artifacts, errors)
140
+
141
+ # --- Build Slack response ---
142
+ if artifacts:
143
+ artifact_list = "\n".join(f" • `{a}`" for a in artifacts)
144
+ content = (
145
+ f"📊 **VizAgent** — chart(s) generated:\n{artifact_list}\n\n"
146
+ f"{caption}\n\n"
147
+ "_⚠️ Paper trading simulation only. Not financial advice._"
148
+ )
149
+ elif errors:
150
+ content = (
151
+ f"📊 **VizAgent** — unable to generate chart(s):\n"
152
+ + "\n".join(f" • {e}" for e in errors)
153
+ + f"\n\n{caption}"
154
+ )
155
+ else:
156
+ content = (
157
+ "📊 **VizAgent** — no data available to generate charts. "
158
+ "Run the quant pipeline first to produce artifacts."
159
+ )
160
+
161
+ # Route back to trigger or human (FR-2.5)
162
+ next_mentions = [trigger_role] if trigger_role else []
163
+
164
+ return AgentResponse(
165
+ agent_role=self.role,
166
+ content=content,
167
+ mentions=next_mentions,
168
+ artifact_path=artifacts[0] if artifacts else None,
169
+ artifact_mode="overwrite",
170
+ )
171
+
172
+ # ------------------------------------------------------------------ #
173
+ # Chart generators
174
+ # ------------------------------------------------------------------ #
175
+
176
+ def _chart_candlestick(self, ticker: str, today: str, plt: Any) -> tuple[str | None, str | None]:
177
+ """Candlestick + volume chart from raw JSON."""
178
+ raw = self.files.read(f"quant/raw/{ticker}_{today}.json")
179
+ if not raw:
180
+ return None, f"Missing raw data for {ticker} ({today})"
181
+
182
+ try:
183
+ data = json.loads(raw)
184
+ except Exception:
185
+ return None, f"Could not parse raw data for {ticker}"
186
+
187
+ ts_series = data.get("Time Series (Daily)", {})
188
+ if not ts_series:
189
+ return None, f"No OHLCV data found for {ticker}"
190
+
191
+ dates_sorted = sorted(ts_series.keys())[-60:] # last 60 trading days
192
+ opens = [float(ts_series[d].get("1. open", 0)) for d in dates_sorted]
193
+ highs = [float(ts_series[d].get("2. high", 0)) for d in dates_sorted]
194
+ lows = [float(ts_series[d].get("3. low", 0)) for d in dates_sorted]
195
+ closes = [float(ts_series[d].get("5. adjusted close", ts_series[d].get("4. close", 0))) for d in dates_sorted]
196
+ vols = [float(ts_series[d].get("6. volume", ts_series[d].get("5. volume", 0))) for d in dates_sorted]
197
+
198
+ fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(12, 7), gridspec_kw={"height_ratios": [3, 1]})
199
+ fig.suptitle(f"{ticker} — Price & Volume ({today})", fontsize=13)
200
+
201
+ xs = list(range(len(dates_sorted)))
202
+ for i, (o, h, l, c) in enumerate(zip(opens, highs, lows, closes)):
203
+ color = "#2ca02c" if c >= o else "#d62728"
204
+ ax1.plot([i, i], [l, h], color=color, linewidth=1)
205
+ ax1.bar(i, abs(c - o), bottom=min(o, c), color=color, width=0.6)
206
+
207
+ # 20-day SMA overlay
208
+ if len(closes) >= 20:
209
+ sma20 = [sum(closes[max(0, j - 19):j + 1]) / min(20, j + 1) for j in range(len(closes))]
210
+ ax1.plot(xs, sma20, color="#ff7f0e", linewidth=1.2, label="SMA-20")
211
+ ax1.legend(fontsize=8)
212
+
213
+ ax1.set_ylabel("Price (USD)")
214
+ ax1.set_xticks([])
215
+
216
+ ax2.bar(xs, vols, color="#1f77b4", alpha=0.6)
217
+ ax2.set_ylabel("Volume")
218
+ n = len(dates_sorted)
219
+ tick_idx = [0, n // 4, n // 2, 3 * n // 4, n - 1]
220
+ ax2.set_xticks(tick_idx)
221
+ ax2.set_xticklabels([dates_sorted[i] for i in tick_idx], rotation=30, fontsize=7)
222
+
223
+ path = f"quant/viz/candlestick_{ticker}_{today}.png"
224
+ self._save_fig(fig, path, plt)
225
+ return path, None
226
+
227
+ def _chart_rsi_macd(self, ticker: str, today: str, plt: Any) -> tuple[str | None, str | None]:
228
+ """RSI + MACD overlay chart."""
229
+ raw = self.files.read(f"quant/raw/{ticker}_{today}.json")
230
+ if not raw:
231
+ return None, f"Missing raw data for {ticker} for RSI/MACD chart"
232
+
233
+ try:
234
+ data = json.loads(raw)
235
+ except Exception:
236
+ return None, f"Could not parse raw data for {ticker}"
237
+
238
+ rsi_series = data.get("Technical Analysis: RSI", {})
239
+ macd_series = data.get("Technical Analysis: MACD", {})
240
+
241
+ if not rsi_series and not macd_series:
242
+ return None, f"No RSI/MACD data found for {ticker}"
243
+
244
+ fig, axes = plt.subplots(2, 1, figsize=(12, 6))
245
+ fig.suptitle(f"{ticker} — RSI & MACD ({today})", fontsize=13)
246
+
247
+ # RSI
248
+ ax_rsi = axes[0]
249
+ if rsi_series:
250
+ dates = sorted(rsi_series.keys())[-60:]
251
+ rsi_vals = [float(rsi_series[d].get("RSI", 50)) for d in dates]
252
+ ax_rsi.plot(rsi_vals, color="#1f77b4", linewidth=1.2)
253
+ ax_rsi.axhline(70, color="#d62728", linestyle="--", linewidth=0.8, label="Overbought (70)")
254
+ ax_rsi.axhline(30, color="#2ca02c", linestyle="--", linewidth=0.8, label="Oversold (30)")
255
+ ax_rsi.set_ylim(0, 100)
256
+ ax_rsi.set_ylabel("RSI-14")
257
+ ax_rsi.legend(fontsize=7)
258
+ else:
259
+ ax_rsi.text(0.5, 0.5, "RSI data unavailable", ha="center", va="center", transform=ax_rsi.transAxes)
260
+
261
+ # MACD
262
+ ax_macd = axes[1]
263
+ if macd_series:
264
+ dates = sorted(macd_series.keys())[-60:]
265
+ macd_vals = [float(macd_series[d].get("MACD", 0)) for d in dates]
266
+ signal_vals = [float(macd_series[d].get("MACD_Signal", 0)) for d in dates]
267
+ hist_vals = [float(macd_series[d].get("MACD_Hist", 0)) for d in dates]
268
+ xs = list(range(len(dates)))
269
+ colors = ["#2ca02c" if v >= 0 else "#d62728" for v in hist_vals]
270
+ ax_macd.bar(xs, hist_vals, color=colors, alpha=0.5, label="Histogram")
271
+ ax_macd.plot(xs, macd_vals, color="#1f77b4", linewidth=1.2, label="MACD")
272
+ ax_macd.plot(xs, signal_vals, color="#ff7f0e", linewidth=1.0, label="Signal")
273
+ ax_macd.axhline(0, color="gray", linewidth=0.8)
274
+ ax_macd.set_ylabel("MACD")
275
+ ax_macd.legend(fontsize=7)
276
+ else:
277
+ ax_macd.text(0.5, 0.5, "MACD data unavailable", ha="center", va="center", transform=ax_macd.transAxes)
278
+
279
+ path = f"quant/viz/rsi_macd_{ticker}_{today}.png"
280
+ self._save_fig(fig, path, plt)
281
+ return path, None
282
+
283
+ def _chart_backtest(self, today: str, plt: Any) -> tuple[str | None, str | None]:
284
+ """Signal backtest performance bar chart."""
285
+ bt_md = self.files.read(f"quant/backtest_results_{today}.md")
286
+ if not bt_md:
287
+ return None, f"Missing backtest results for {today}"
288
+
289
+ # Extract win_rate and signal names via simple regex
290
+ entries = re.findall(
291
+ r"###?\s+(.+?)\n.*?win.?rate[:\s]+([0-9.]+)",
292
+ bt_md, re.IGNORECASE | re.DOTALL,
293
+ )
294
+ if not entries:
295
+ return None, "No parseable signal metrics found in backtest results"
296
+
297
+ names = [e[0].strip()[:30] for e in entries]
298
+ rates = [min(float(e[1]), 100.0) for e in entries]
299
+
300
+ fig, ax = plt.subplots(figsize=(10, max(4, len(names) * 0.7)))
301
+ colors = ["#2ca02c" if r >= 50 else "#d62728" for r in rates]
302
+ ax.barh(names, rates, color=colors)
303
+ ax.axvline(50, color="gray", linestyle="--", linewidth=0.8)
304
+ ax.set_xlabel("Win Rate (%)")
305
+ ax.set_title(f"Signal Backtest Performance — {today}")
306
+ ax.set_xlim(0, 100)
307
+ plt.tight_layout()
308
+
309
+ path = f"quant/viz/backtest_{today}.png"
310
+ self._save_fig(fig, path, plt)
311
+ return path, None
312
+
313
+ def _chart_risk_heatmap(self, today: str, plt: Any) -> tuple[str | None, str | None]:
314
+ """Risk rating heatmap from risk assessment markdown."""
315
+ risk_md = self.files.read(f"quant/risk_assessment_{today}.md")
316
+ if not risk_md:
317
+ return None, f"Missing risk assessment for {today}"
318
+
319
+ entries = re.findall(
320
+ r"###?\s+(.+?)\n.*?risk.?verdict[:\s]+(Acceptable|Elevated|Reject)",
321
+ risk_md, re.IGNORECASE | re.DOTALL,
322
+ )
323
+ if not entries:
324
+ return None, "No parseable risk ratings found in risk assessment"
325
+
326
+ rating_map = {"acceptable": 1, "elevated": 2, "reject": 3}
327
+ names = [e[0].strip()[:30] for e in entries]
328
+ ratings = [rating_map.get(e[1].lower(), 2) for e in entries]
329
+ colors = {1: "#2ca02c", 2: "#ff7f0e", 3: "#d62728"}
330
+
331
+ fig, ax = plt.subplots(figsize=(10, max(3, len(names) * 0.6)))
332
+ for i, (name, rating) in enumerate(zip(names, ratings)):
333
+ ax.barh([i], [1], color=colors[rating])
334
+ ax.text(0.5, i, ["", "Acceptable", "Elevated", "Reject"][rating],
335
+ ha="center", va="center", color="white", fontsize=10, fontweight="bold")
336
+ ax.set_yticks(range(len(names)))
337
+ ax.set_yticklabels(names)
338
+ ax.set_xticks([])
339
+ ax.set_title(f"Signal Risk Ratings — {today}")
340
+ plt.tight_layout()
341
+
342
+ path = f"quant/viz/risk_heatmap_{today}.png"
343
+ self._save_fig(fig, path, plt)
344
+ return path, None
345
+
346
+ def _chart_portfolio_pnl(self, research_state: dict, today: str, plt: Any) -> tuple[str | None, str | None]:
347
+ """Portfolio P&L bar chart from QuantState."""
348
+ qs = research_state.get("quant_state") or {}
349
+ portfolio = qs.get("portfolio", [])
350
+ if not portfolio:
351
+ return None, "No open positions in paper portfolio"
352
+
353
+ names = [f"{p.get('ticker','?')} ({p.get('direction','?')[:1].upper()})" for p in portfolio]
354
+ entries = [float(p.get("entry_price", 0)) for p in portfolio]
355
+ sizes = [float(p.get("size_pct", 0)) for p in portfolio]
356
+
357
+ fig, ax = plt.subplots(figsize=(10, max(3, len(names) * 0.6)))
358
+ xs = list(range(len(names)))
359
+ ax.bar(xs, sizes, color="#1f77b4")
360
+ ax2 = ax.twinx()
361
+ ax2.plot(xs, entries, color="#ff7f0e", marker="o", linewidth=1.5, label="Entry price")
362
+ ax.set_xticks(xs)
363
+ ax.set_xticklabels(names, rotation=30, fontsize=8)
364
+ ax.set_ylabel("Position size (%)")
365
+ ax2.set_ylabel("Entry price (USD)")
366
+ ax2.legend(fontsize=8)
367
+ ax.set_title(f"Paper Portfolio — {today}")
368
+ plt.tight_layout()
369
+
370
+ path = f"quant/viz/portfolio_pnl_{today}.png"
371
+ self._save_fig(fig, path, plt)
372
+ return path, None
373
+
374
+ # ------------------------------------------------------------------ #
375
+ # Helpers
376
+ # ------------------------------------------------------------------ #
377
+
378
+ def _save_fig(self, fig: Any, path: str, plt: Any) -> None:
379
+ """Render figure to PNG and save via FileWriter."""
380
+ buf = io.BytesIO()
381
+ fig.savefig(buf, format="png", dpi=120, bbox_inches="tight")
382
+ plt.close(fig)
383
+ buf.seek(0)
384
+ png_bytes = buf.read()
385
+ # Store bytes for Slack upload (keyed by path)
386
+ self._pending_chart_bytes[path] = png_bytes
387
+ # Also write to session filesystem via FileWriter
388
+ self.files.write(path, png_bytes.decode("latin-1"))
389
+
390
+ def _detect_chart_type(self, text: str) -> str | None:
391
+ for keyword, chart in _CHART_KEYWORDS.items():
392
+ if keyword in text:
393
+ return chart
394
+ return None
395
+
396
+ def _detect_ticker(self, text: str) -> str | None:
397
+ m = re.search(r"\b([A-Z]{1,5})\b", text)
398
+ return m.group(1) if m else None
399
+
400
+ def _latest_ticker(self, today: str) -> str | None:
401
+ """Return the first ticker with a raw data file for today."""
402
+ files = self.files.list("quant/raw/")
403
+ for f in files:
404
+ if today in f and f.endswith(".json"):
405
+ ticker = f.split("/")[-1].replace(f"_{today}.json", "")
406
+ return ticker.upper()
407
+ return None
408
+
409
+ async def _generate_caption(
410
+ self,
411
+ chart_type: str | None,
412
+ ticker: str | None,
413
+ artifacts: list[str],
414
+ errors: list[str],
415
+ ) -> str:
416
+ """Generate a 2-3 sentence caption for the generated charts (FR-2.4)."""
417
+ if not artifacts:
418
+ return ""
419
+ subject = ticker or "the portfolio"
420
+ ct = chart_type or "multiple charts"
421
+ prompt = (
422
+ f"Write a 2-3 sentence caption for a {ct} chart for {subject}. "
423
+ "Describe what a data analyst should look for in this type of chart "
424
+ "and what an interesting insight might look like. "
425
+ "Be concise and practical. Do not invent specific numbers."
426
+ )
427
+ try:
428
+ result = await self._llm.complete(prompt)
429
+ text = result[0] if isinstance(result, tuple) else result
430
+ return text.strip()
431
+ except Exception:
432
+ return f"Chart generated for {subject} ({ct})."
src/polyhedra/core/research_state.py CHANGED
@@ -130,7 +130,11 @@ class PaperPosition:
130
  size_pct: float # % of paper portfolio
131
  opened_at: str
132
  proposal_id: str
133
- status: str = "open" # open / closed
 
 
 
 
134
 
135
 
136
  @dataclass
@@ -166,6 +170,9 @@ class QuantState:
166
  portfolio: list[PaperPosition] = dc_field(default_factory=list)
167
  trade_log: list[TradeEvent] = dc_field(default_factory=list)
168
  alerts: list[str] = dc_field(default_factory=list)
 
 
 
169
 
170
  def to_dict(self) -> dict:
171
  from dataclasses import asdict as _asdict
@@ -179,6 +186,8 @@ class QuantState:
179
  qs.last_run = data.get("last_run")
180
  qs.alerts = data.get("alerts", [])
181
  qs.risk_ratings = data.get("risk_ratings", {})
 
 
182
 
183
  qs.signals = [
184
  Signal(**{k: v for k, v in s.items() if k in Signal.__dataclass_fields__})
 
130
  size_pct: float # % of paper portfolio
131
  opened_at: str
132
  proposal_id: str
133
+ status: str = "open" # open / closed / hold
134
+ take_profit: float | None = None # V4.2 — monitor threshold
135
+ stop_loss: float | None = None # V4.2 — monitor threshold
136
+ close_price: float | None = None
137
+ close_date: str | None = None
138
 
139
 
140
  @dataclass
 
170
  portfolio: list[PaperPosition] = dc_field(default_factory=list)
171
  trade_log: list[TradeEvent] = dc_field(default_factory=list)
172
  alerts: list[str] = dc_field(default_factory=list)
173
+ # V4.2 portfolio monitor fields
174
+ monitor_paused: bool = False
175
+ last_monitor_run: str | None = None
176
 
177
  def to_dict(self) -> dict:
178
  from dataclasses import asdict as _asdict
 
186
  qs.last_run = data.get("last_run")
187
  qs.alerts = data.get("alerts", [])
188
  qs.risk_ratings = data.get("risk_ratings", {})
189
+ qs.monitor_paused = data.get("monitor_paused", False)
190
+ qs.last_monitor_run = data.get("last_monitor_run")
191
 
192
  qs.signals = [
193
  Signal(**{k: v for k, v in s.items() if k in Signal.__dataclass_fields__})
src/polyhedra/messaging/slack.py CHANGED
@@ -42,6 +42,9 @@ _ROLE_DISPLAY: dict[str, str] = {
42
  "backtester": "Backtester 📉",
43
  "riskanalyst": "RiskAnalyst ⚖️",
44
  "quantstrategist": "QuantStrategist 📋",
 
 
 
45
  }
46
 
47
 
@@ -113,6 +116,11 @@ class SlackIntegration:
113
  fastapi_app.add_api_route("/slack/events", slack_events, methods=["POST"])
114
  logger.info("Slack events handler mounted at /slack/events")
115
 
 
 
 
 
 
116
  # ------------------------------------------------------------------ #
117
  # Slash command handlers
118
  # ------------------------------------------------------------------ #
@@ -161,11 +169,13 @@ class SlackIntegration:
161
  await self._cmd_trade(client, channel_id, args)
162
  elif sub == "watchlist":
163
  await self._cmd_watchlist(client, channel_id, args)
 
 
164
  else:
165
  await client.chat_postMessage(
166
  channel=channel_id,
167
  text=(
168
- "*Polyhedra v4.0* — available commands:\n"
169
  "• `/poly init <goal>` — start a new research session\n"
170
  "• `/poly state` — show the current Research State\n"
171
  "• `/poly export` — export all artifacts as a zip\n"
@@ -174,8 +184,9 @@ class SlackIntegration:
174
  "• `/poly quant [ticker]` — run full quant analysis on watchlist\n"
175
  "• `/poly quant report` — post most recent quant findings\n"
176
  "• `/poly portfolio` — show paper portfolio + P&L\n"
177
- "• `/poly trade approve|reject|revise <id>` — act on a trade proposal\n"
178
- "• `/poly watchlist [add|remove] <tickers>` — manage ticker watchlist\n\n"
 
179
  "_⚠️ Quant features are paper trading simulations only. "
180
  "Not financial advice. No real capital._"
181
  ),
@@ -278,6 +289,7 @@ class SlackIntegration:
278
  from polyhedra.agents.quant import (
279
  DataFetcherAgent, TrendAnalystAgent, SentimentAnalystAgent,
280
  QuantResearcherAgent, BacktesterAgent, RiskAnalystAgent, QuantStrategistAgent,
 
281
  )
282
  from polyhedra.core.role_registry import RoleEntry
283
  from polyhedra.core.session import SessionManager
@@ -298,6 +310,8 @@ class SlackIntegration:
298
  (BacktesterAgent, "backtester"),
299
  (RiskAnalystAgent, "riskanalyst"),
300
  (QuantStrategistAgent, "quantstrategist"),
 
 
301
  ]:
302
  session.registry.register(RoleEntry(role=role, agent=agent_cls()))
303
 
@@ -317,6 +331,7 @@ class SlackIntegration:
317
  "scout", "strategist", "critic", "scribe",
318
  "datafetcher", "trendanalyst", "sentimentanalyst",
319
  "quantresearcher", "backtester", "riskanalyst", "quantstrategist",
 
320
  ]
321
  await service.initialize_session(goal=goal, selected_roles=selected_roles, human_roles=[])
322
 
@@ -333,6 +348,7 @@ class SlackIntegration:
333
  from polyhedra.agents.quant import (
334
  DataFetcherAgent, TrendAnalystAgent, SentimentAnalystAgent,
335
  QuantResearcherAgent, BacktesterAgent, RiskAnalystAgent, QuantStrategistAgent,
 
336
  )
337
  from polyhedra.core.role_registry import RoleEntry
338
  from polyhedra.core.session import SessionManager
@@ -354,6 +370,8 @@ class SlackIntegration:
354
  (BacktesterAgent, "backtester"),
355
  (RiskAnalystAgent, "riskanalyst"),
356
  (QuantStrategistAgent, "quantstrategist"),
 
 
357
  ]:
358
  session.registry.register(RoleEntry(role=role, agent=agent_cls()))
359
 
@@ -377,6 +395,7 @@ class SlackIntegration:
377
  "scout", "strategist", "critic", "scribe",
378
  "datafetcher", "trendanalyst", "sentimentanalyst",
379
  "quantresearcher", "backtester", "riskanalyst", "quantstrategist",
 
380
  ]
381
  await service.initialize_session(goal=goal, selected_roles=selected_roles, human_roles=[])
382
 
@@ -681,10 +700,11 @@ class SlackIntegration:
681
  action, proposal_id = parts[0].lower(), parts[1]
682
  reason = parts[2] if len(parts) > 2 else ""
683
 
684
- if action not in ("approve", "reject", "revise"):
 
685
  await client.chat_postMessage(
686
  channel=channel_id,
687
- text="Action must be `approve`, `reject`, or `revise`.",
688
  )
689
  return
690
 
@@ -766,7 +786,7 @@ class SlackIntegration:
766
  channel=channel_id,
767
  text=f"❌ Paper trade **rejected**: `{proposal_id}`{f' — {reason}' if reason else ''}",
768
  )
769
- else: # revise
770
  qs_dict = rs.quant_state.to_dict() if rs.quant_state else {}
771
  qs_dict.setdefault("trade_log", []).append(event)
772
  for p in qs_dict.get("trade_proposals", []):
@@ -786,6 +806,10 @@ class SlackIntegration:
786
  from_role="human",
787
  text=f"@quantstrategist please revise proposal {proposal_id}: {reason}",
788
  )
 
 
 
 
789
 
790
  def _find_proposal_in_md(self, session_dir: Any, proposal_id: str) -> Any:
791
  """Parse a lightweight proposal stub from the trade_proposals MD file."""
@@ -808,6 +832,194 @@ class SlackIntegration:
808
  return _parse_proposal_block(block, proposal_id)
809
  return None
810
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
811
  async def _cmd_watchlist(self, client: Any, channel_id: str, args: str) -> None:
812
  """Manage the quant watchlist: show / add / remove tickers."""
813
  from polyhedra.core.research_state import ResearchStateManager, QuantState
 
42
  "backtester": "Backtester 📉",
43
  "riskanalyst": "RiskAnalyst ⚖️",
44
  "quantstrategist": "QuantStrategist 📋",
45
+ # V4.2 additions
46
+ "vizagent": "VizAgent 📊",
47
+ "portfoliomonitor": "PortfolioMonitor 🔔",
48
  }
49
 
50
 
 
116
  fastapi_app.add_api_route("/slack/events", slack_events, methods=["POST"])
117
  logger.info("Slack events handler mounted at /slack/events")
118
 
119
+ # Launch background portfolio monitor loop.
120
+ task = asyncio.ensure_future(self._monitor_loop())
121
+ self._tasks.add(task)
122
+ task.add_done_callback(self._tasks.discard)
123
+
124
  # ------------------------------------------------------------------ #
125
  # Slash command handlers
126
  # ------------------------------------------------------------------ #
 
169
  await self._cmd_trade(client, channel_id, args)
170
  elif sub == "watchlist":
171
  await self._cmd_watchlist(client, channel_id, args)
172
+ elif sub == "monitor":
173
+ await self._cmd_monitor(client, channel_id, args)
174
  else:
175
  await client.chat_postMessage(
176
  channel=channel_id,
177
  text=(
178
+ "*Polyhedra v4.2* — available commands:\n"
179
  "• `/poly init <goal>` — start a new research session\n"
180
  "• `/poly state` — show the current Research State\n"
181
  "• `/poly export` — export all artifacts as a zip\n"
 
184
  "• `/poly quant [ticker]` — run full quant analysis on watchlist\n"
185
  "• `/poly quant report` — post most recent quant findings\n"
186
  "• `/poly portfolio` — show paper portfolio + P&L\n"
187
+ "• `/poly trade approve|reject|revise|close|hold <id>` — act on trades\n"
188
+ "• `/poly watchlist [add|remove] <tickers>` — manage ticker watchlist\n"
189
+ "• `/poly monitor pause|resume|interval <min>` — control portfolio monitoring\n\n"
190
  "_⚠️ Quant features are paper trading simulations only. "
191
  "Not financial advice. No real capital._"
192
  ),
 
289
  from polyhedra.agents.quant import (
290
  DataFetcherAgent, TrendAnalystAgent, SentimentAnalystAgent,
291
  QuantResearcherAgent, BacktesterAgent, RiskAnalystAgent, QuantStrategistAgent,
292
+ VizAgent, PortfolioMonitorAgent,
293
  )
294
  from polyhedra.core.role_registry import RoleEntry
295
  from polyhedra.core.session import SessionManager
 
310
  (BacktesterAgent, "backtester"),
311
  (RiskAnalystAgent, "riskanalyst"),
312
  (QuantStrategistAgent, "quantstrategist"),
313
+ (VizAgent, "vizagent"),
314
+ (PortfolioMonitorAgent, "portfoliomonitor"),
315
  ]:
316
  session.registry.register(RoleEntry(role=role, agent=agent_cls()))
317
 
 
331
  "scout", "strategist", "critic", "scribe",
332
  "datafetcher", "trendanalyst", "sentimentanalyst",
333
  "quantresearcher", "backtester", "riskanalyst", "quantstrategist",
334
+ "vizagent", "portfoliomonitor",
335
  ]
336
  await service.initialize_session(goal=goal, selected_roles=selected_roles, human_roles=[])
337
 
 
348
  from polyhedra.agents.quant import (
349
  DataFetcherAgent, TrendAnalystAgent, SentimentAnalystAgent,
350
  QuantResearcherAgent, BacktesterAgent, RiskAnalystAgent, QuantStrategistAgent,
351
+ VizAgent, PortfolioMonitorAgent,
352
  )
353
  from polyhedra.core.role_registry import RoleEntry
354
  from polyhedra.core.session import SessionManager
 
370
  (BacktesterAgent, "backtester"),
371
  (RiskAnalystAgent, "riskanalyst"),
372
  (QuantStrategistAgent, "quantstrategist"),
373
+ (VizAgent, "vizagent"),
374
+ (PortfolioMonitorAgent, "portfoliomonitor"),
375
  ]:
376
  session.registry.register(RoleEntry(role=role, agent=agent_cls()))
377
 
 
395
  "scout", "strategist", "critic", "scribe",
396
  "datafetcher", "trendanalyst", "sentimentanalyst",
397
  "quantresearcher", "backtester", "riskanalyst", "quantstrategist",
398
+ "vizagent", "portfoliomonitor",
399
  ]
400
  await service.initialize_session(goal=goal, selected_roles=selected_roles, human_roles=[])
401
 
 
700
  action, proposal_id = parts[0].lower(), parts[1]
701
  reason = parts[2] if len(parts) > 2 else ""
702
 
703
+ _VALID_ACTIONS = ("approve", "reject", "revise", "close", "hold")
704
+ if action not in _VALID_ACTIONS:
705
  await client.chat_postMessage(
706
  channel=channel_id,
707
+ text="Action must be `approve`, `reject`, `revise`, `close`, or `hold`.",
708
  )
709
  return
710
 
 
786
  channel=channel_id,
787
  text=f"❌ Paper trade **rejected**: `{proposal_id}`{f' — {reason}' if reason else ''}",
788
  )
789
+ elif action == "revise":
790
  qs_dict = rs.quant_state.to_dict() if rs.quant_state else {}
791
  qs_dict.setdefault("trade_log", []).append(event)
792
  for p in qs_dict.get("trade_proposals", []):
 
806
  from_role="human",
807
  text=f"@quantstrategist please revise proposal {proposal_id}: {reason}",
808
  )
809
+ elif action == "close":
810
+ await self._trade_close(client, channel_id, qs, rs, rsm, proposal_id, event)
811
+ elif action == "hold":
812
+ await self._trade_hold(client, channel_id, qs, rs, rsm, proposal_id, event)
813
 
814
  def _find_proposal_in_md(self, session_dir: Any, proposal_id: str) -> Any:
815
  """Parse a lightweight proposal stub from the trade_proposals MD file."""
 
832
  return _parse_proposal_block(block, proposal_id)
833
  return None
834
 
835
+ async def _trade_close(
836
+ self,
837
+ client: Any,
838
+ channel_id: str,
839
+ qs: Any,
840
+ rs: Any,
841
+ rsm: Any,
842
+ position_id: str,
843
+ event: dict,
844
+ ) -> None:
845
+ """Close an open paper position (FR-3.9)."""
846
+ from datetime import date
847
+ from polyhedra.core.research_state import QuantState
848
+ from polyhedra.services.finnhub import FinnhubService
849
+
850
+ pos = next((p for p in qs.portfolio if p.position_id == position_id), None)
851
+ if pos is None:
852
+ await client.chat_postMessage(
853
+ channel=channel_id,
854
+ text=f"❌ Position `{position_id}` not found in portfolio.",
855
+ )
856
+ return
857
+
858
+ close_price: float = pos.entry_price # fallback
859
+ try:
860
+ quote = await FinnhubService().get_quote(pos.ticker)
861
+ close_price = float(quote.get("c", pos.entry_price))
862
+ except Exception:
863
+ pass
864
+
865
+ pnl_pct = (
866
+ (close_price - pos.entry_price) / pos.entry_price * 100
867
+ if pos.direction.lower() == "long"
868
+ else (pos.entry_price - close_price) / pos.entry_price * 100
869
+ )
870
+
871
+ qs_dict = rs.quant_state.to_dict() if rs.quant_state else {}
872
+ for p in qs_dict.get("portfolio", []):
873
+ if p.get("position_id") == position_id:
874
+ p["status"] = "closed"
875
+ p["close_price"] = close_price
876
+ p["close_date"] = date.today().isoformat()
877
+ event["action"] = "close"
878
+ event["close_price"] = close_price
879
+ event["pnl_pct"] = round(pnl_pct, 2)
880
+ qs_dict.setdefault("trade_log", []).append(event)
881
+ rs.quant_state = QuantState.from_dict(qs_dict)
882
+ rsm.save(rs)
883
+
884
+ sign = "+" if pnl_pct >= 0 else ""
885
+ await client.chat_postMessage(
886
+ channel=channel_id,
887
+ text=(
888
+ f"🔴 Position *closed*: `{position_id}` — {pos.ticker} "
889
+ f"@ {close_price:.2f} (P&L {sign}{pnl_pct:.2f}%)\n\n"
890
+ "_⚠️ Paper trading only. No real capital involved._"
891
+ ),
892
+ )
893
+
894
+ async def _trade_hold(
895
+ self,
896
+ client: Any,
897
+ channel_id: str,
898
+ qs: Any,
899
+ rs: Any,
900
+ rsm: Any,
901
+ position_id: str,
902
+ event: dict,
903
+ ) -> None:
904
+ """Suppress monitor alerts for a position for 1 hour (FR-3.9)."""
905
+ from datetime import datetime, timedelta, timezone
906
+ from polyhedra.core.research_state import QuantState
907
+
908
+ pos = next((p for p in qs.portfolio if p.position_id == position_id), None)
909
+ if pos is None:
910
+ await client.chat_postMessage(
911
+ channel=channel_id,
912
+ text=f"❌ Position `{position_id}` not found in portfolio.",
913
+ )
914
+ return
915
+
916
+ hold_until = (datetime.now(tz=timezone.utc) + timedelta(hours=1)).isoformat()
917
+ qs_dict = rs.quant_state.to_dict() if rs.quant_state else {}
918
+ for p in qs_dict.get("portfolio", []):
919
+ if p.get("position_id") == position_id:
920
+ p["hold_alerts_until"] = hold_until
921
+ event["action"] = "hold"
922
+ qs_dict.setdefault("trade_log", []).append(event)
923
+ rs.quant_state = QuantState.from_dict(qs_dict)
924
+ rsm.save(rs)
925
+
926
+ await client.chat_postMessage(
927
+ channel=channel_id,
928
+ text=(
929
+ f"⏸ Alert hold set for position `{position_id}` — "
930
+ f"monitor alerts suppressed for 1 hour."
931
+ ),
932
+ )
933
+
934
+ async def _cmd_monitor(self, client: Any, channel_id: str, args: str) -> None:
935
+ """Handle /poly monitor pause|resume|interval <minutes>."""
936
+ from polyhedra.core.research_state import ResearchStateManager, QuantState
937
+
938
+ service = self._sessions.get(channel_id)
939
+ if not service:
940
+ await client.chat_postMessage(channel=channel_id, text="No active session.")
941
+ return
942
+
943
+ parts = args.strip().split()
944
+ sub = parts[0].lower() if parts else ""
945
+
946
+ try:
947
+ rsm = ResearchStateManager(service.session.session_dir)
948
+ rs = rsm.load()
949
+ if rs.quant_state is None:
950
+ rs.quant_state = QuantState()
951
+ except Exception:
952
+ await client.chat_postMessage(channel=channel_id, text="❌ Could not load quant state.")
953
+ return
954
+
955
+ if sub == "pause":
956
+ rs.quant_state.monitor_paused = True
957
+ rsm.save(rs)
958
+ await client.chat_postMessage(
959
+ channel=channel_id, text="⏸ Portfolio monitor *paused*."
960
+ )
961
+ elif sub == "resume":
962
+ rs.quant_state.monitor_paused = False
963
+ rsm.save(rs)
964
+ await client.chat_postMessage(
965
+ channel=channel_id, text="▶️ Portfolio monitor *resumed*."
966
+ )
967
+ elif sub == "interval" and len(parts) > 1:
968
+ try:
969
+ minutes = max(1, int(parts[1]))
970
+ except ValueError:
971
+ await client.chat_postMessage(
972
+ channel=channel_id,
973
+ text="Usage: `/poly monitor interval <minutes>` (integer >= 1)",
974
+ )
975
+ return
976
+ # Store interval in session env so the background loop picks it up.
977
+ service.session.monitor_interval_minutes = minutes
978
+ rsm.save(rs)
979
+ await client.chat_postMessage(
980
+ channel=channel_id,
981
+ text=f"⏱ Monitor interval set to *{minutes} min*.",
982
+ )
983
+ else:
984
+ paused = rs.quant_state.monitor_paused
985
+ last = rs.quant_state.last_monitor_run or "_never_"
986
+ interval = getattr(
987
+ service.session, "monitor_interval_minutes",
988
+ int(os.environ.get("POLYHEDRA_MONITOR_INTERVAL", "30")),
989
+ )
990
+ await client.chat_postMessage(
991
+ channel=channel_id,
992
+ text=(
993
+ f"🔔 *Portfolio Monitor*\n"
994
+ f"• Status: {'⏸ paused' if paused else '▶️ running'}\n"
995
+ f"• Interval: {interval} min\n"
996
+ f"• Last run: {last}\n\n"
997
+ "Controls:\n"
998
+ "• `/poly monitor pause` — pause alerts\n"
999
+ "• `/poly monitor resume` — resume alerts\n"
1000
+ "• `/poly monitor interval <min>` — change check frequency"
1001
+ ),
1002
+ )
1003
+
1004
+ async def _monitor_loop(self) -> None:
1005
+ """Background loop: dispatch @portfoliomonitor for every active session."""
1006
+ _DEFAULT_INTERVAL = int(os.environ.get("POLYHEDRA_MONITOR_INTERVAL", "30"))
1007
+ while True:
1008
+ interval_min = _DEFAULT_INTERVAL
1009
+ try:
1010
+ for channel_id, service in [*self._sessions.items()]:
1011
+ # Per-session interval override (set via /poly monitor interval)
1012
+ interval_min = getattr(
1013
+ service.session, "monitor_interval_minutes", _DEFAULT_INTERVAL
1014
+ )
1015
+ await service.dispatch(
1016
+ from_role="scheduler",
1017
+ text="@portfoliomonitor run portfolio check",
1018
+ )
1019
+ except Exception as exc: # noqa: BLE001
1020
+ logger.warning("_monitor_loop error: %s", exc)
1021
+ await asyncio.sleep(interval_min * 60)
1022
+
1023
  async def _cmd_watchlist(self, client: Any, channel_id: str, args: str) -> None:
1024
  """Manage the quant watchlist: show / add / remove tickers."""
1025
  from polyhedra.core.research_state import ResearchStateManager, QuantState
src/polyhedra/services/finnhub.py CHANGED
@@ -56,6 +56,19 @@ class FinnhubService:
56
  # Public API
57
  # ------------------------------------------------------------------ #
58
 
 
 
 
 
 
 
 
 
 
 
 
 
 
59
  async def fetch_ticker_data(self, ticker: str, session_dir: Path) -> dict[str, Any]:
60
  """
61
  Fetch Finnhub data for *ticker* and persist in AV-compatible format.
 
56
  # Public API
57
  # ------------------------------------------------------------------ #
58
 
59
+ async def get_quote(self, ticker: str) -> dict[str, Any]:
60
+ """Return the latest real-time quote for *ticker*.
61
+
62
+ Finnhub ``/quote`` fields:
63
+ c — current price
64
+ h — high of the day
65
+ l — low of the day
66
+ o — open price
67
+ pc — previous close
68
+ t — UNIX timestamp
69
+ """
70
+ return await self._call("/quote", {"symbol": ticker.upper()})
71
+
72
  async def fetch_ticker_data(self, ticker: str, session_dir: Path) -> dict[str, Any]:
73
  """
74
  Fetch Finnhub data for *ticker* and persist in AV-compatible format.