yf176 commited on
Commit
c4fb7d7
·
1 Parent(s): 5e1208a

feat: add typed RiskAnalyst execution

Browse files
src/polyhedra/agents/quant/decision_contracts.py CHANGED
@@ -259,10 +259,28 @@ class RiskAnalystDependencies(TypedModel):
259
  backtests: BacktesterOutput
260
 
261
 
 
 
 
 
 
 
 
 
262
  class RiskAnalystContext(TypedModel):
263
  trend: TrendAnalystOutput | None = None
264
  asset_analyses: AssetAnalysisCollection | None = None
265
  macro_context: MacroContextWatcherOutput | None = None
 
 
 
 
 
 
 
 
 
 
266
 
267
 
268
  class RiskAnalystInput(AgentInput[RiskAnalystDependencies, RiskAnalystContext]):
@@ -277,6 +295,11 @@ class RiskAnalystInput(AgentInput[RiskAnalystDependencies, RiskAnalystContext]):
277
  _current_output(value, producer, self)
278
  if self.optional_context.asset_analyses is not None:
279
  _current_collection(self.optional_context.asset_analyses, self)
 
 
 
 
 
280
  return self
281
 
282
 
 
259
  backtests: BacktesterOutput
260
 
261
 
262
+ class RiskPortfolioPosition(TypedModel):
263
+ position_id: Identifier
264
+ ticker: Ticker
265
+ direction: TradeDirection
266
+ entry_price: Annotated[float, Field(strict=True, gt=0)]
267
+ portfolio_fraction: Ratio
268
+
269
+
270
  class RiskAnalystContext(TypedModel):
271
  trend: TrendAnalystOutput | None = None
272
  asset_analyses: AssetAnalysisCollection | None = None
273
  macro_context: MacroContextWatcherOutput | None = None
274
+ open_positions: list[RiskPortfolioPosition] = Field(default_factory=list)
275
+
276
+ @model_validator(mode="after")
277
+ def portfolio_identity(self) -> Self:
278
+ ids = [item.position_id for item in self.open_positions]
279
+ if len(ids) != len(set(ids)):
280
+ raise ValueError("open paper position IDs must be unique")
281
+ if sum(item.portfolio_fraction for item in self.open_positions) > 1:
282
+ raise ValueError("open paper portfolio fractions cannot exceed one")
283
+ return self
284
 
285
 
286
  class RiskAnalystInput(AgentInput[RiskAnalystDependencies, RiskAnalystContext]):
 
295
  _current_output(value, producer, self)
296
  if self.optional_context.asset_analyses is not None:
297
  _current_collection(self.optional_context.asset_analyses, self)
298
+ outside = {
299
+ item.ticker for item in self.optional_context.open_positions
300
+ } - set(self.ticker_scope)
301
+ if outside:
302
+ raise ValueError("open paper position lies outside RiskAnalyst scope")
303
  return self
304
 
305
 
src/polyhedra/agents/quant/io_registry.py CHANGED
@@ -117,7 +117,15 @@ _TASKS: dict[AgentName, str] = {
117
  "explicit data gap explaining why it was not simulated. Preserve supplied upstream gaps. "
118
  "Do not recommend signals, claim a simulation, or emit routing fields."
119
  ),
120
- "RiskAnalyst": "Assess signal and portfolio risk, rejecting unsupported exposure and naming mitigations.",
 
 
 
 
 
 
 
 
121
  "QuantStrategist": "Vote through the committee and choose a PRD-valid paper-trading outcome.",
122
  "Publisher": "Write Finley's concise Slack-ready result from the validated strategy decision.",
123
  "VizAgent": "Describe requested charts only from the supplied typed source fields.",
 
117
  "explicit data gap explaining why it was not simulated. Preserve supplied upstream gaps. "
118
  "Do not recommend signals, claim a simulation, or emit routing fields."
119
  ),
120
+ "RiskAnalyst": (
121
+ "Assess every current backtest result and the supplied open paper portfolio. Cite the "
122
+ "exact backtest result behind each signal verdict. Reject NOT_TESTABLE signals with zero "
123
+ "suggested paper position, name a mitigation for every ELEVATED verdict, preserve upstream "
124
+ "gaps, and "
125
+ "report portfolio heat as the exact sum of supplied position fractions. Keep unsupported "
126
+ "loss estimates null and state assumptions for stress scenarios. A valid result may reject "
127
+ "every signal; do not force exposure, make a strategy decision, or emit routing fields."
128
+ ),
129
  "QuantStrategist": "Vote through the committee and choose a PRD-valid paper-trading outcome.",
130
  "Publisher": "Write Finley's concise Slack-ready result from the validated strategy decision.",
131
  "VizAgent": "Describe requested charts only from the supplied typed source fields.",
src/polyhedra/agents/quant/riskanalyst.py CHANGED
@@ -8,16 +8,30 @@ DISCLAIMER: Paper trading simulation only. Educational purposes.
8
 
9
  from __future__ import annotations
10
 
 
11
  import logging
12
- from datetime import date, datetime, timezone
13
- from typing import Any
14
 
15
  from polyhedra.agents.base import Agent, AgentResponse, Mention
 
 
 
 
 
 
 
16
  from polyhedra.agents.quant.llm_errors import format_llm_failure
17
  from polyhedra.agents.quant.routing import LLM_ROUTING_PROMPT, parse_llm_routing
18
  from polyhedra.agents.quant.yolo_prompt_context import build_yolo_prompt_context
 
 
19
  from polyhedra.core.token_budget import TokenBudget
 
 
 
20
  from polyhedra.services.llm_service import LLMService
 
21
 
22
  logger = logging.getLogger(__name__)
23
 
@@ -54,6 +68,91 @@ class RiskAnalystAgent(Agent):
54
  async def can_handle(self, mention: Mention) -> bool:
55
  return mention.mentioned_role == self.role
56
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
57
  async def handle(
58
  self,
59
  mention: Mention,
@@ -223,3 +322,179 @@ class RiskAnalystAgent(Agent):
223
  )
224
  return "\n".join(lines)
225
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
 
9
  from __future__ import annotations
10
 
11
+ import json
12
  import logging
13
+ from datetime import UTC, date, datetime, timezone
14
+ from typing import Any, Callable
15
 
16
  from polyhedra.agents.base import Agent, AgentResponse, Mention
17
+ from polyhedra.agents.quant.decision_contracts import (
18
+ EvidenceStrength,
19
+ RiskAnalystInput,
20
+ RiskAnalystOutput,
21
+ RiskPayload,
22
+ )
23
+ from polyhedra.agents.quant.io_registry import quant_io_binding
24
  from polyhedra.agents.quant.llm_errors import format_llm_failure
25
  from polyhedra.agents.quant.routing import LLM_ROUTING_PROMPT, parse_llm_routing
26
  from polyhedra.agents.quant.yolo_prompt_context import build_yolo_prompt_context
27
+ from polyhedra.core.artifacts import Availability, DataIssue, JsonArtifactRef, RiskVerdict
28
+ from polyhedra.core.dependency_executor import AgentCompletion
29
  from polyhedra.core.token_budget import TokenBudget
30
+ from polyhedra.services.artifact_publisher import ArtifactPublisher
31
+ from polyhedra.services.evidence_verifier import EvidenceSource, verify_evidence
32
+ from polyhedra.services.file_writer import ScopedFileWriter
33
  from polyhedra.services.llm_service import LLMService
34
+ from polyhedra.services.published_inputs import PublishedInputResolver
35
 
36
  logger = logging.getLogger(__name__)
37
 
 
68
  async def can_handle(self, mention: Mention) -> bool:
69
  return mention.mentioned_role == self.role
70
 
71
+ async def execute_typed(
72
+ self,
73
+ inputs: RiskAnalystInput,
74
+ *,
75
+ files: ScopedFileWriter,
76
+ publisher: ArtifactPublisher,
77
+ now: Callable[[], datetime] | None = None,
78
+ research_state: dict[str, Any] | None = None,
79
+ ) -> AgentCompletion:
80
+ """Assess typed signal and paper-portfolio risk without choosing trades."""
81
+ if type(inputs) is not RiskAnalystInput:
82
+ raise TypeError("RiskAnalyst typed execution requires its registered input")
83
+ if (files.agent, files.run_id, files.ticker_scope) != (
84
+ "RiskAnalyst",
85
+ inputs.run_id,
86
+ tuple(inputs.ticker_scope),
87
+ ):
88
+ raise ValueError("RiskAnalyst input contradicts scoped activation")
89
+ if (publisher.run_id, publisher.session_id) != (
90
+ inputs.run_id,
91
+ inputs.session_id,
92
+ ):
93
+ raise ValueError("RiskAnalyst publisher contradicts activation identity")
94
+
95
+ clock = now or (lambda: datetime.now(tz=UTC))
96
+ sources, input_refs, baseline_sources = _risk_sources(inputs, files)
97
+ publisher.record_input("RiskAnalyst", inputs)
98
+ upstream_gaps = _risk_input_gaps(inputs)
99
+ backtest_results = inputs.dependencies.backtests.payload.results
100
+ open_positions = inputs.optional_context.open_positions
101
+
102
+ if backtest_results or open_positions:
103
+ binding = quant_io_binding("RiskAnalyst")
104
+ prompt = binding.build_prompt(inputs)
105
+ if baseline_sources:
106
+ prompt += _risk_baseline_context(baseline_sources)
107
+ completion = await self._llm.complete_structured(prompt, binding.output_schema)
108
+ payload = completion.output
109
+ if research_state is not None:
110
+ self._log_token_usage(
111
+ research_state,
112
+ completion.input_tokens,
113
+ completion.output_tokens,
114
+ cache_hit=False,
115
+ )
116
+ payload = RiskPayload.model_validate({
117
+ **payload.model_dump(mode="json"),
118
+ "data_gaps": [gap.model_dump(mode="json") for gap in _dedupe_risk_gaps([
119
+ *upstream_gaps,
120
+ *payload.data_gaps,
121
+ ])],
122
+ })
123
+ else:
124
+ payload = _empty_risk_payload(inputs, upstream_gaps)
125
+
126
+ _validate_risk_payload(inputs, payload, input_refs=input_refs)
127
+ verify_evidence(payload, sources)
128
+ output_gaps = _dedupe_risk_gaps([*upstream_gaps, *payload.data_gaps])
129
+ status = _risk_status(inputs, output_gaps)
130
+ output = RiskAnalystOutput(
131
+ schema_version="8.0",
132
+ artifact_id=f"{inputs.run_id}-risk-assessment",
133
+ run_id=inputs.run_id,
134
+ session_id=inputs.session_id,
135
+ producer="RiskAnalyst",
136
+ ticker_scope=inputs.ticker_scope,
137
+ created_at=clock(),
138
+ status=status,
139
+ input_refs=input_refs,
140
+ baseline_refs=inputs.baseline_refs,
141
+ data_gaps=output_gaps,
142
+ render_ref=None,
143
+ payload=payload,
144
+ )
145
+ published = publisher.publish(
146
+ files,
147
+ output,
148
+ json_path=f"quant/runs/{inputs.run_id}/risk_assessment.json",
149
+ markdown_path=f"quant/runs/{inputs.run_id}/risk_assessment.md",
150
+ )
151
+ return AgentCompletion(
152
+ artifact_ref=published.artifact_ref,
153
+ result_status=output.status,
154
+ )
155
+
156
  async def handle(
157
  self,
158
  mention: Mention,
 
322
  )
323
  return "\n".join(lines)
324
 
325
+
326
+ def _risk_sources(
327
+ inputs: RiskAnalystInput,
328
+ files: ScopedFileWriter,
329
+ ) -> tuple[list[EvidenceSource], list[JsonArtifactRef], list[EvidenceSource]]:
330
+ outputs = [inputs.dependencies.backtests]
331
+ filenames = {"Backtester": "backtest_results.json"}
332
+ for value, producer, filename in (
333
+ (inputs.optional_context.trend, "TrendAnalyst", "trend_analysis.json"),
334
+ (inputs.optional_context.asset_analyses, "Runtime", "asset_analysis.json"),
335
+ (inputs.optional_context.macro_context, "MacroContextWatcher", "macro_context.json"),
336
+ ):
337
+ if value is not None:
338
+ outputs.append(value)
339
+ filenames[producer] = filename
340
+ references = [JsonArtifactRef(
341
+ schema_version=output.schema_version,
342
+ artifact_id=output.artifact_id,
343
+ run_id=output.run_id,
344
+ session_id=output.session_id,
345
+ producer=output.producer,
346
+ path=f"quant/runs/{output.run_id}/{filenames[output.producer]}",
347
+ ) for output in outputs]
348
+ snapshot = PublishedInputResolver(files).capture(
349
+ required_refs=tuple(references),
350
+ baseline_refs=tuple(inputs.baseline_refs),
351
+ )
352
+ if len(snapshot.required) != len(outputs) or any(
353
+ loaded.value != expected
354
+ for loaded, expected in zip(snapshot.required, outputs)
355
+ ):
356
+ raise ValueError("RiskAnalyst input contradicts its published artifact")
357
+ current_sources = [
358
+ EvidenceSource(loaded.reference, loaded.value)
359
+ for loaded in snapshot.required
360
+ ]
361
+ baseline_sources = [
362
+ EvidenceSource(loaded.reference, loaded.value)
363
+ for loaded in snapshot.baseline
364
+ if loaded.reference in inputs.baseline_refs
365
+ ]
366
+ return [*current_sources, *baseline_sources], references, baseline_sources
367
+
368
+
369
+ def _risk_baseline_context(sources: list[EvidenceSource]) -> str:
370
+ values = [{
371
+ "reference": source.reference.model_dump(mode="json"),
372
+ "artifact": source.value.model_dump(mode="json"),
373
+ } for source in sources]
374
+ return (
375
+ "\n\nApproved prior-run artifacts resolved through the read-only ACL may inform "
376
+ "risk changes and limitations, but current verdicts must cite current evidence:\n"
377
+ + json.dumps(values, ensure_ascii=True)
378
+ )
379
+
380
+
381
+ def _risk_input_gaps(inputs: RiskAnalystInput) -> list[DataIssue]:
382
+ outputs = [inputs.dependencies.backtests]
383
+ if inputs.optional_context.trend is not None:
384
+ outputs.append(inputs.optional_context.trend)
385
+ if inputs.optional_context.macro_context is not None:
386
+ outputs.append(inputs.optional_context.macro_context)
387
+ gaps = [
388
+ gap
389
+ for output in outputs
390
+ for gap in output.data_gaps
391
+ if gap.ticker is None or gap.ticker in inputs.ticker_scope
392
+ ]
393
+ assets = inputs.optional_context.asset_analyses
394
+ if assets is not None:
395
+ gaps.extend(
396
+ gap
397
+ for contribution in assets.contributions
398
+ for gap in contribution.data_gaps
399
+ )
400
+ return _dedupe_risk_gaps(gaps)
401
+
402
+
403
+ def _dedupe_risk_gaps(gaps: list[DataIssue]) -> list[DataIssue]:
404
+ unique: dict[tuple[str, str, str | None], DataIssue] = {}
405
+ for gap in gaps:
406
+ unique[(gap.component, gap.code, gap.ticker)] = gap
407
+ return list(unique.values())
408
+
409
+
410
+ def _portfolio_heat(inputs: RiskAnalystInput) -> float:
411
+ return round(sum(
412
+ position.portfolio_fraction
413
+ for position in inputs.optional_context.open_positions
414
+ ), 10)
415
+
416
+
417
+ def _empty_risk_payload(
418
+ inputs: RiskAnalystInput,
419
+ gaps: list[DataIssue],
420
+ ) -> RiskPayload:
421
+ unavailable = inputs.dependencies.backtests.status == Availability.UNAVAILABLE
422
+ summary = (
423
+ "Risk assessment is unavailable because no current signal-validation evidence or open "
424
+ "paper position was supplied."
425
+ if unavailable else
426
+ "No current signal or open paper position requires a risk verdict."
427
+ )
428
+ return RiskPayload(
429
+ signal_assessments=[],
430
+ portfolio_heat=0.0,
431
+ concentration_assessment="No open paper positions are in scope.",
432
+ correlation_assessment="No candidate signals or open positions require comparison.",
433
+ maximum_loss_estimate=None,
434
+ stress_scenarios=[],
435
+ overall_risk_summary=summary,
436
+ data_gaps=gaps,
437
+ )
438
+
439
+
440
+ def _validate_risk_payload(
441
+ inputs: RiskAnalystInput,
442
+ payload: RiskPayload,
443
+ *,
444
+ input_refs: list[JsonArtifactRef],
445
+ ) -> None:
446
+ results = inputs.dependencies.backtests.payload.results
447
+ expected = {result.signal_id: (index, result) for index, result in enumerate(results)}
448
+ actual = {assessment.signal_id: assessment for assessment in payload.signal_assessments}
449
+ if set(actual) != set(expected):
450
+ raise ValueError("RiskAnalyst must assess every current backtest result exactly once")
451
+
452
+ backtest_ref = input_refs[0]
453
+ for signal_id, assessment in actual.items():
454
+ index, result = expected[signal_id]
455
+ if assessment.ticker != result.ticker:
456
+ raise ValueError("risk assessment ticker contradicts its backtest result")
457
+ if not any(
458
+ evidence.artifact == backtest_ref
459
+ and evidence.field_path == f"/payload/results/{index}"
460
+ for evidence in assessment.evidence_refs
461
+ ):
462
+ raise ValueError("risk verdict must cite the exact current backtest result")
463
+ if result.evidence_strength == EvidenceStrength.NOT_TESTABLE:
464
+ if (assessment.verdict != RiskVerdict.REJECT
465
+ or assessment.suggested_paper_position_limit != 0):
466
+ raise ValueError("not-testable signal must be rejected with zero exposure")
467
+
468
+ if payload.portfolio_heat is None:
469
+ raise ValueError("portfolio heat is required for the supplied paper portfolio")
470
+ if abs(payload.portfolio_heat - _portfolio_heat(inputs)) > 1e-9:
471
+ raise ValueError("portfolio heat must equal supplied open-position fractions")
472
+ if (results
473
+ and all(result.evidence_strength == EvidenceStrength.NOT_TESTABLE for result in results)
474
+ and not inputs.optional_context.open_positions
475
+ and (payload.maximum_loss_estimate is not None or any(
476
+ scenario.estimated_loss is not None for scenario in payload.stress_scenarios
477
+ ))):
478
+ raise ValueError("unvalidated signals cannot support numerical loss estimates")
479
+ required_gaps = {
480
+ (gap.component, gap.code, gap.ticker)
481
+ for gap in _risk_input_gaps(inputs)
482
+ }
483
+ payload_gaps = {
484
+ (gap.component, gap.code, gap.ticker)
485
+ for gap in payload.data_gaps
486
+ }
487
+ if not required_gaps.issubset(payload_gaps):
488
+ raise ValueError("RiskAnalyst output omitted an upstream data gap")
489
+
490
+
491
+ def _risk_status(inputs: RiskAnalystInput, gaps: list[DataIssue]) -> Availability:
492
+ backtests = inputs.dependencies.backtests
493
+ if (backtests.status == Availability.UNAVAILABLE
494
+ and not backtests.payload.results
495
+ and not inputs.optional_context.open_positions):
496
+ return Availability.UNAVAILABLE
497
+ if gaps or backtests.status != Availability.COMPLETE:
498
+ return Availability.PARTIAL
499
+ return Availability.COMPLETE
500
+
tests/test_decision_contracts.py CHANGED
@@ -282,6 +282,43 @@ def test_risk_requires_mitigation_and_zero_rejected_size():
282
  RiskAnalystOutput.model_validate(data)
283
 
284
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
285
  def test_strategy_trade_contract_and_maximum_three():
286
  assert strategy().payload.proposals[0].ticker == "SPY"
287
  with pytest.raises(ValidationError):
 
282
  RiskAnalystOutput.model_validate(data)
283
 
284
 
285
+ def test_risk_portfolio_context_is_unique_bounded_and_in_scope():
286
+ base = dict(
287
+ run_id="run1",
288
+ session_id="session1",
289
+ run_mode="BASELINE",
290
+ as_of=AT,
291
+ ticker_scope=["SPY"],
292
+ dependencies={"backtests": backtest()},
293
+ baseline_refs=[],
294
+ )
295
+ position = dict(
296
+ position_id="position-spy",
297
+ ticker="SPY",
298
+ direction="LONG",
299
+ entry_price=650.0,
300
+ portfolio_fraction=0.2,
301
+ )
302
+ RiskAnalystInput.model_validate({
303
+ **base,
304
+ "optional_context": {"open_positions": [position]},
305
+ })
306
+ for positions, match in (
307
+ ([position, position], "unique"),
308
+ ([{**position, "ticker": "QQQ"}], "outside"),
309
+ ([position, {
310
+ **position,
311
+ "position_id": "position-spy-2",
312
+ "portfolio_fraction": 0.9,
313
+ }], "cannot exceed"),
314
+ ):
315
+ with pytest.raises(ValidationError, match=match):
316
+ RiskAnalystInput.model_validate({
317
+ **base,
318
+ "optional_context": {"open_positions": positions},
319
+ })
320
+
321
+
322
  def test_strategy_trade_contract_and_maximum_three():
323
  assert strategy().payload.proposals[0].ticker == "SPY"
324
  with pytest.raises(ValidationError):
tests/test_riskanalyst_typed.py ADDED
@@ -0,0 +1,374 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """RiskAnalyst produces complete typed verdicts without forcing exposure."""
2
+
3
+ from datetime import datetime, timezone
4
+ from pathlib import Path
5
+ from unittest.mock import AsyncMock
6
+
7
+ import pytest
8
+
9
+ from polyhedra.agents.quant.decision_contracts import (
10
+ BacktestPayload,
11
+ BacktesterOutput,
12
+ RiskAnalystContext,
13
+ RiskAnalystDependencies,
14
+ RiskAnalystInput,
15
+ RiskAnalystOutput,
16
+ RiskPayload,
17
+ )
18
+ from polyhedra.agents.quant.riskanalyst import RiskAnalystAgent
19
+ from polyhedra.core.artifacts import JsonArtifactRef
20
+ from polyhedra.services.artifact_publisher import ArtifactPublisher
21
+ from polyhedra.services.file_writer import FileWriter, PublicationRegistry, ScopedFileWriter
22
+ from polyhedra.services.llm_service import LLMService, StructuredCompletion
23
+
24
+ AT = datetime(2026, 9, 18, 14, tzinfo=timezone.utc)
25
+
26
+
27
+ class ControlledLLM:
28
+ def __init__(self, payload: RiskPayload) -> None:
29
+ self.payload = payload
30
+ self.calls = []
31
+
32
+ async def complete_structured(self, prompt, output_schema):
33
+ self.calls.append((prompt, output_schema))
34
+ return StructuredCompletion(self.payload, 16, 24, 1)
35
+
36
+
37
+ def ref(producer: str, filename: str) -> JsonArtifactRef:
38
+ return JsonArtifactRef(
39
+ schema_version="8.0",
40
+ artifact_id=f"run1-{filename.removesuffix('.json').replace('/', '-')}",
41
+ run_id="run1",
42
+ session_id="session1",
43
+ producer=producer,
44
+ path=f"quant/runs/run1/{filename}",
45
+ )
46
+
47
+
48
+ def backtest_output(
49
+ *,
50
+ results: bool = True,
51
+ testable: bool = True,
52
+ status: str | None = None,
53
+ ) -> BacktesterOutput:
54
+ gaps = ([] if testable else [{
55
+ "component": "BACKTEST",
56
+ "code": "HISTORICAL_ENGINE_NOT_CONFIGURED",
57
+ "message": "No approved historical execution engine is configured.",
58
+ "ticker": None,
59
+ }])
60
+ result_items = []
61
+ if results:
62
+ result_items.append({
63
+ "signal_id": "spy-breakout",
64
+ "ticker": "SPY",
65
+ "observations": 90 if testable else None,
66
+ "occurrences": 8 if testable else None,
67
+ "win_rate": 0.625 if testable else None,
68
+ "average_return": 0.01 if testable else None,
69
+ "cumulative_return": 0.08 if testable else None,
70
+ "maximum_drawdown": -0.04 if testable else None,
71
+ "sharpe_ratio": 0.8 if testable else None,
72
+ "evidence_strength": "SUFFICIENT" if testable else "NOT_TESTABLE",
73
+ "evidence_refs": ([{
74
+ "artifact": ref("QuantResearcher", "signals.json"),
75
+ "field_path": "/payload/signals/0",
76
+ }] if testable else [{
77
+ "artifact": ref("QuantResearcher", "signals.json"),
78
+ "field_path": "/payload/signals/0",
79
+ }]),
80
+ "data_gaps": [] if testable else [{
81
+ "component": "BACKTEST",
82
+ "code": "SIGNAL_NOT_TESTED",
83
+ "message": "The signal was not simulated.",
84
+ "ticker": "SPY",
85
+ }],
86
+ })
87
+ payload = BacktestPayload.model_validate({
88
+ "method": "HISTORICAL_SIMULATION" if testable else "LLM_ASSESSMENT",
89
+ "tested_from": "2026-06-01" if testable else None,
90
+ "tested_through": "2026-09-01" if testable else None,
91
+ "results": result_items,
92
+ "assumptions": ["Daily close execution."] if testable else [],
93
+ "limitations": ["Paper research only."],
94
+ "data_gaps": gaps,
95
+ })
96
+ resolved_status = status or ("COMPLETE" if testable else "PARTIAL")
97
+ return BacktesterOutput(
98
+ schema_version="8.0",
99
+ artifact_id="run1-backtest-results",
100
+ run_id="run1",
101
+ session_id="session1",
102
+ producer="Backtester",
103
+ ticker_scope=["SPY"],
104
+ created_at=AT,
105
+ status=resolved_status,
106
+ input_refs=[ref("QuantResearcher", "signals.json")],
107
+ baseline_refs=[],
108
+ data_gaps=gaps,
109
+ render_ref=None,
110
+ payload=payload,
111
+ )
112
+
113
+
114
+ def risk_payload(
115
+ backtest_ref: JsonArtifactRef,
116
+ *,
117
+ verdict: str = "REJECT",
118
+ portfolio_heat: float = 0.0,
119
+ field_path: str = "/payload/results/0",
120
+ ) -> RiskPayload:
121
+ return RiskPayload.model_validate({
122
+ "signal_assessments": [{
123
+ "signal_id": "spy-breakout",
124
+ "ticker": "SPY",
125
+ "verdict": verdict,
126
+ "rationale": "The supplied validation evidence defines the risk boundary.",
127
+ "suggested_paper_position_limit": 0.0 if verdict == "REJECT" else 0.05,
128
+ "required_mitigation": "Limit exposure." if verdict == "ELEVATED" else None,
129
+ "evidence_refs": [{
130
+ "artifact": backtest_ref,
131
+ "field_path": field_path,
132
+ }],
133
+ }],
134
+ "portfolio_heat": portfolio_heat,
135
+ "concentration_assessment": "No concentrated open exposure is present.",
136
+ "correlation_assessment": "Only one candidate signal is in scope.",
137
+ "maximum_loss_estimate": None,
138
+ "stress_scenarios": [{
139
+ "name": "Broad market decline",
140
+ "estimated_loss": None,
141
+ "assumptions": ["No supported loss calculation is available."],
142
+ }],
143
+ "overall_risk_summary": "The candidate may be rejected without blocking strategy review.",
144
+ "data_gaps": [],
145
+ })
146
+
147
+
148
+ def setup_risk(
149
+ tmp_path: Path,
150
+ *,
151
+ results: bool = True,
152
+ testable: bool = True,
153
+ status: str | None = None,
154
+ portfolio_fraction: float | None = None,
155
+ ):
156
+ session = tmp_path / "session1"
157
+ session.mkdir()
158
+ writer = FileWriter(session, session_id="session1")
159
+ publications = PublicationRegistry()
160
+ publisher = ArtifactPublisher(writer, session_id="session1", run_id="run1")
161
+ backtests = backtest_output(results=results, testable=testable, status=status)
162
+ backtest_files = ScopedFileWriter(
163
+ writer,
164
+ agent="Backtester",
165
+ run_id="run1",
166
+ ticker_scope=["SPY"],
167
+ publications=publications,
168
+ )
169
+ published = publisher.publish(
170
+ backtest_files,
171
+ backtests,
172
+ json_path="quant/runs/run1/backtest_results.json",
173
+ markdown_path="quant/runs/run1/backtest_results.md",
174
+ )
175
+ positions = []
176
+ if portfolio_fraction is not None:
177
+ positions.append({
178
+ "position_id": "position-spy",
179
+ "ticker": "SPY",
180
+ "direction": "LONG",
181
+ "entry_price": 650.0,
182
+ "portfolio_fraction": portfolio_fraction,
183
+ })
184
+ inputs = RiskAnalystInput(
185
+ run_id="run1",
186
+ session_id="session1",
187
+ run_mode="BASELINE",
188
+ as_of=AT,
189
+ ticker_scope=["SPY"],
190
+ dependencies=RiskAnalystDependencies(backtests=backtests),
191
+ optional_context=RiskAnalystContext(open_positions=positions),
192
+ baseline_refs=[],
193
+ )
194
+ files = ScopedFileWriter(
195
+ writer,
196
+ agent="RiskAnalyst",
197
+ run_id="run1",
198
+ ticker_scope=["SPY"],
199
+ publications=publications,
200
+ )
201
+ return session, publisher, inputs, files, published.artifact_ref
202
+
203
+
204
+ @pytest.mark.asyncio
205
+ async def test_typed_risk_calls_llm_and_forwards_all_rejected_result(tmp_path: Path):
206
+ session, publisher, inputs, files, backtest_ref = setup_risk(tmp_path)
207
+ payload = risk_payload(backtest_ref)
208
+ llm = LLMService(provider="openai", api_key="test-only")
209
+ llm.complete = AsyncMock(return_value=(payload.model_dump_json(), 16, 24))
210
+ state = {"quant_state": {}}
211
+
212
+ completion = await RiskAnalystAgent(llm).execute_typed(
213
+ inputs,
214
+ files=files,
215
+ publisher=publisher,
216
+ now=lambda: AT,
217
+ research_state=state,
218
+ )
219
+
220
+ assert completion.result_status == "COMPLETE"
221
+ assert llm.complete.await_count == 1
222
+ prompt = llm.complete.call_args.args[0]
223
+ assert "valid result may reject every signal" in prompt
224
+ assert state["quant_state"]["token_log"][0]["prompt_tokens"] == 16
225
+ output = RiskAnalystOutput.model_validate_json(
226
+ (session / "quant/runs/run1/risk_assessment.json").read_text(),
227
+ strict=True,
228
+ )
229
+ assert output.payload.signal_assessments[0].verdict == "REJECT"
230
+
231
+
232
+ @pytest.mark.asyncio
233
+ async def test_not_testable_signal_requires_rejection(tmp_path: Path):
234
+ _, publisher, inputs, files, backtest_ref = setup_risk(tmp_path, testable=False)
235
+ payload = risk_payload(backtest_ref, verdict="ACCEPTABLE")
236
+
237
+ with pytest.raises(ValueError, match="not-testable signal"):
238
+ await RiskAnalystAgent(ControlledLLM(payload)).execute_typed(
239
+ inputs,
240
+ files=files,
241
+ publisher=publisher,
242
+ now=lambda: AT,
243
+ )
244
+
245
+
246
+ @pytest.mark.asyncio
247
+ async def test_risk_requires_exact_backtest_result_citation(tmp_path: Path):
248
+ _, publisher, inputs, files, backtest_ref = setup_risk(tmp_path)
249
+ payload = risk_payload(backtest_ref, field_path="/payload/limitations")
250
+
251
+ with pytest.raises(ValueError, match="exact current backtest"):
252
+ await RiskAnalystAgent(ControlledLLM(payload)).execute_typed(
253
+ inputs,
254
+ files=files,
255
+ publisher=publisher,
256
+ now=lambda: AT,
257
+ )
258
+
259
+
260
+ @pytest.mark.asyncio
261
+ async def test_risk_validates_runtime_owned_portfolio_heat(tmp_path: Path):
262
+ _, publisher, inputs, files, backtest_ref = setup_risk(
263
+ tmp_path,
264
+ portfolio_fraction=0.2,
265
+ )
266
+ payload = risk_payload(backtest_ref, portfolio_heat=0.1)
267
+
268
+ with pytest.raises(ValueError, match="portfolio heat"):
269
+ await RiskAnalystAgent(ControlledLLM(payload)).execute_typed(
270
+ inputs,
271
+ files=files,
272
+ publisher=publisher,
273
+ now=lambda: AT,
274
+ )
275
+
276
+
277
+ @pytest.mark.asyncio
278
+ async def test_unvalidated_signal_cannot_support_loss_estimate(tmp_path: Path):
279
+ _, publisher, inputs, files, backtest_ref = setup_risk(tmp_path, testable=False)
280
+ payload = risk_payload(backtest_ref).model_copy(update={"maximum_loss_estimate": 0.1})
281
+
282
+ with pytest.raises(ValueError, match="numerical loss estimates"):
283
+ await RiskAnalystAgent(ControlledLLM(payload)).execute_typed(
284
+ inputs,
285
+ files=files,
286
+ publisher=publisher,
287
+ now=lambda: AT,
288
+ )
289
+
290
+
291
+ @pytest.mark.asyncio
292
+ async def test_empty_backtests_publish_complete_result_without_llm(tmp_path: Path):
293
+ session, publisher, inputs, files, backtest_ref = setup_risk(
294
+ tmp_path,
295
+ results=False,
296
+ )
297
+ llm = ControlledLLM(risk_payload(backtest_ref))
298
+
299
+ completion = await RiskAnalystAgent(llm).execute_typed(
300
+ inputs,
301
+ files=files,
302
+ publisher=publisher,
303
+ now=lambda: AT,
304
+ )
305
+
306
+ assert completion.result_status == "COMPLETE"
307
+ assert llm.calls == []
308
+ output = RiskAnalystOutput.model_validate_json(
309
+ (session / "quant/runs/run1/risk_assessment.json").read_text(),
310
+ strict=True,
311
+ )
312
+ assert output.payload.signal_assessments == []
313
+ assert output.payload.portfolio_heat == 0.0
314
+
315
+
316
+ @pytest.mark.asyncio
317
+ async def test_open_portfolio_is_assessed_without_candidate_signals(tmp_path: Path):
318
+ session, publisher, inputs, files, _ = setup_risk(
319
+ tmp_path,
320
+ results=False,
321
+ portfolio_fraction=0.2,
322
+ )
323
+ payload = RiskPayload(
324
+ signal_assessments=[],
325
+ portfolio_heat=0.2,
326
+ concentration_assessment="The single SPY position is twenty percent of paper capital.",
327
+ correlation_assessment="Only one open paper position is in scope.",
328
+ maximum_loss_estimate=None,
329
+ stress_scenarios=[],
330
+ overall_risk_summary="Existing paper exposure was reviewed without a new signal.",
331
+ data_gaps=[],
332
+ )
333
+ llm = ControlledLLM(payload)
334
+
335
+ completion = await RiskAnalystAgent(llm).execute_typed(
336
+ inputs,
337
+ files=files,
338
+ publisher=publisher,
339
+ now=lambda: AT,
340
+ )
341
+
342
+ assert completion.result_status == "COMPLETE"
343
+ assert len(llm.calls) == 1
344
+ output = RiskAnalystOutput.model_validate_json(
345
+ (session / "quant/runs/run1/risk_assessment.json").read_text(),
346
+ strict=True,
347
+ )
348
+ assert output.payload.portfolio_heat == 0.2
349
+
350
+
351
+ @pytest.mark.asyncio
352
+ async def test_unavailable_empty_backtests_remain_unavailable(tmp_path: Path):
353
+ session, publisher, inputs, files, backtest_ref = setup_risk(
354
+ tmp_path,
355
+ results=False,
356
+ testable=False,
357
+ status="UNAVAILABLE",
358
+ )
359
+ llm = ControlledLLM(risk_payload(backtest_ref))
360
+
361
+ completion = await RiskAnalystAgent(llm).execute_typed(
362
+ inputs,
363
+ files=files,
364
+ publisher=publisher,
365
+ now=lambda: AT,
366
+ )
367
+
368
+ assert completion.result_status == "UNAVAILABLE"
369
+ assert llm.calls == []
370
+ output = RiskAnalystOutput.model_validate_json(
371
+ (session / "quant/runs/run1/risk_assessment.json").read_text(),
372
+ strict=True,
373
+ )
374
+ assert output.data_gaps[0].code == "HISTORICAL_ENGINE_NOT_CONFIGURED"