File size: 5,975 Bytes
d1a28b0 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 | """Support contexts use the governed routing, ACL, trace, and record runtime."""
from datetime import datetime, timezone
from pathlib import Path
import pytest
from polyhedra.agents.quant.market_data_contracts import MarketDataArtifact
from polyhedra.agents.quant.portfoliomonitor import PortfolioMonitorAgent
from polyhedra.agents.quant.product_contracts import PaperPosition
from polyhedra.agents.quant.vizagent import VizAgent
from polyhedra.core.research_state import ResearchStateManager
from polyhedra.core.trace_logger import TraceLogger
from polyhedra.services.artifact_publisher import ArtifactPublisher
from polyhedra.services.file_writer import FileWriter, PublicationRegistry, ScopedFileWriter
from polyhedra.services.llm_service import StructuredCompletion
from polyhedra.services.quant_support_runtime import QuantSupportRuntime
AT = datetime(2026, 9, 20, 16, tzinfo=timezone.utc)
class _CaptionLLM:
async def complete_structured(self, _prompt, output_schema):
return StructuredCompletion(
output_schema.model_validate({"caption": "SPY closed above its moving average."}),
8,
7,
1,
)
def _market_data() -> MarketDataArtifact:
return MarketDataArtifact.model_validate({
"schema_version": "8.0",
"artifact_id": "source-market-SPY",
"session_id": "session1",
"run_id": "source1",
"producer": "DataFetcher",
"ticker": "SPY",
"retrieved_at": AT,
"market_date": "2026-09-18",
"status": "COMPLETE",
"ohlcv": [{
"market_date": "2026-09-18", "open": 650.0, "high": 656.0,
"low": 648.0, "close": 655.0, "adjusted_close": 655.0,
"volume": 42_000_000.0,
}],
"indicators": {"points": [{
"market_date": "2026-09-18", "sma_20": 645.0, "ema_20": 647.0,
"rsi_14": 58.0, "macd": 1.2, "macd_signal": 0.9,
"macd_histogram": 0.3,
}]},
"news": [],
"earnings": [],
"provenance": [{
"component": component, "provider": provider, "retrieved_at": AT,
"source_observed_at": observed, "freshness": freshness,
"availability": availability, "record_count": count,
} for component, provider, observed, freshness, availability, count in (
("OHLCV", "controlled", AT, "FRESH", "AVAILABLE", 1),
("INDICATORS", "computed", AT, "FRESH", "AVAILABLE", 1),
("NEWS", "controlled", None, "UNKNOWN", "AVAILABLE", 0),
("EARNINGS", None, None, "UNKNOWN", "NOT_APPLICABLE", 0),
)],
"quality_issues": [],
"baseline_ref": None,
})
def _runtime(tmp_path: Path, agents):
session = tmp_path / "session1"
session.mkdir(exist_ok=True)
return session, FileWriter(session, session_id="session1"), QuantSupportRuntime(
session_dir=session,
session_id="session1",
agents=agents,
writer=FileWriter(session, session_id="session1"),
trace=TraceLogger(session),
)
@pytest.mark.asyncio
async def test_visualization_uses_one_frozen_source_run_and_records_png(tmp_path: Path):
session, writer, runtime = _runtime(tmp_path, {"VizAgent": VizAgent(_CaptionLLM())})
registry = PublicationRegistry()
source_files = ScopedFileWriter(
writer, agent="DataFetcher", run_id="source1", ticker_scope=["SPY"],
publications=registry,
)
source = ArtifactPublisher(
writer, session_id="session1", run_id="source1",
).publish_auxiliary(
source_files,
_market_data(),
schema=MarketDataArtifact,
json_path="quant/runs/source1/raw/SPY.json",
markdown_path="quant/runs/source1/raw/SPY_summary.md",
render_markdown=lambda _: "# SPY\n",
).artifact_ref
result = await runtime.run_visualization(
run_id="viz1",
ticker_scope=["SPY"],
source_run_id="source1",
source_artifacts=[source],
chart_type="CANDLESTICK",
ticker="SPY",
started_at=AT,
)
assert result.record.execution_context == "VISUALIZATION"
assert result.record.baseline_run_id == "source1"
assert result.output is not None, result.record.execution.for_agent("VizAgent").error
assert result.output.payload.charts[0].source_artifact_refs == [source]
assert (session / "quant/runs/viz1/viz/candlestick_SPY.png").read_bytes().startswith(
b"\x89PNG\r\n\x1a\n"
)
assert (session / "support_runs/viz1.json").exists()
assert (session / "quant/evidence_ledger_viz1.json").exists()
assert "source1" in result.record.permission_snapshots["VizAgent"]["read"][0]
@pytest.mark.asyncio
async def test_monitor_records_alert_and_updates_timestamp_without_mutating_position(tmp_path: Path):
session, _writer, runtime = _runtime(
tmp_path, {"PortfolioMonitor": PortfolioMonitorAgent()},
)
position = PaperPosition(
position_id="p1", ticker="SPY", direction="LONG",
entry_price=100.0, size_percentage=10.0,
)
async def quotes(_tickers):
return {"SPY": 106.0}
result = await runtime.run_portfolio_monitor(
run_id="monitor1",
ticker_scope=["SPY"],
positions=[position],
thresholds={"stop_loss_percentage": 5.0, "take_profit_percentage": 5.0},
paused=False,
market_hours="OPEN",
quote_provider={"provider": "finnhub", "configured": True},
quote_fetcher=quotes,
started_at=AT,
)
assert result.record.execution_context == "PORTFOLIO_MONITOR"
assert result.output.payload.alerts[0].alert_type == "TAKE_PROFIT"
assert position.size_percentage == 10.0
assert (session / "support_runs/monitor1.json").exists()
assert ResearchStateManager(session).load().quant_state.last_monitor_run is not None
assert (session / "trace.jsonl").read_text(encoding="utf-8").count("portfoliomonitor") >= 1
|