yf176 commited on
Commit
2fd6704
·
1 Parent(s): e84d1e1

feat: add typed TrendAnalyst execution

Browse files
src/polyhedra/agents/quant/io_registry.py CHANGED
@@ -38,7 +38,12 @@ from polyhedra.core.template_builder import AgentIOTemplate
38
  _TASKS: dict[AgentName, str] = {
39
  "DataFetcher": "Organize fetched provider evidence and data-quality status without inventing values.",
40
  "OptionsFlowWatcher": "Interpret the bounded options sample within recorded provider capabilities.",
41
- "TrendAnalyst": "Interpret technical price, volume, and indicator evidence for each scoped ticker.",
 
 
 
 
 
42
  "SentimentAnalyst": "Assess available news and earnings sentiment, preserving insufficient evidence.",
43
  "MarketEventWatcher": "Describe evidence-backed market changes and catalysts already present in input.",
44
  "MacroContextWatcher": "Identify the current macro main line, drivers, uncertainty, and contradictions.",
 
38
  _TASKS: dict[AgentName, str] = {
39
  "DataFetcher": "Organize fetched provider evidence and data-quality status without inventing values.",
40
  "OptionsFlowWatcher": "Interpret the bounded options sample within recorded provider capabilities.",
41
+ "TrendAnalyst": (
42
+ "Interpret price direction, magnitude and duration, support and resistance, volume, "
43
+ "SMA-20, EMA-20, moving-average crossover, RSI-14, and MACD evidence for each scoped "
44
+ "ticker. Compare approved prior trend context in delta mode. Describe technical state "
45
+ "only; do not make a trading recommendation."
46
+ ),
47
  "SentimentAnalyst": "Assess available news and earnings sentiment, preserving insufficient evidence.",
48
  "MarketEventWatcher": "Describe evidence-backed market changes and catalysts already present in input.",
49
  "MacroContextWatcher": "Identify the current macro main line, drivers, uncertainty, and contradictions.",
src/polyhedra/agents/quant/trendanalyst.py CHANGED
@@ -10,14 +10,39 @@ from __future__ import annotations
10
 
11
  import logging
12
  from datetime import date, datetime, timezone
13
- from typing import TYPE_CHECKING, 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.market_scope import split_v5_v6_markets
18
  from polyhedra.agents.quant.routing import LLM_ROUTING_PROMPT, parse_llm_routing
19
  from polyhedra.agents.quant.yolo_prompt_context import build_yolo_prompt_context
 
 
 
 
 
 
 
 
 
20
  from polyhedra.core.token_budget import TokenBudget
 
 
 
21
 
22
  if TYPE_CHECKING:
23
  from polyhedra.services.llm_service import LLMService
@@ -67,6 +92,85 @@ class TrendAnalystAgent(Agent):
67
  async def can_handle(self, mention: Mention) -> bool:
68
  return mention.mentioned_role == self.role
69
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
70
  async def handle(
71
  self,
72
  mention: Mention,
@@ -203,3 +307,148 @@ Format each ticker as a `## <TICKER>` section header. Be specific with numbers.
203
  ## [5] ROUTING
204
  {LLM_ROUTING_PROMPT}"""
205
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10
 
11
  import logging
12
  from datetime import date, datetime, timezone
13
+ from typing import TYPE_CHECKING, Any, Callable
14
 
15
  from polyhedra.agents.base import Agent, AgentResponse, Mention
16
+ from polyhedra.agents.quant.analysis_contracts import (
17
+ CrossoverState,
18
+ MACDState,
19
+ RSIState,
20
+ RelativeState,
21
+ TrendAnalysis,
22
+ TrendAnalystInput,
23
+ TrendAnalystOutput,
24
+ TrendPayload,
25
+ VolumeState,
26
+ )
27
+ from polyhedra.agents.quant.io_registry import quant_io_binding
28
  from polyhedra.agents.quant.llm_errors import format_llm_failure
29
+ from polyhedra.agents.quant.market_data_contracts import MarketDataArtifact
30
  from polyhedra.agents.quant.market_scope import split_v5_v6_markets
31
  from polyhedra.agents.quant.routing import LLM_ROUTING_PROMPT, parse_llm_routing
32
  from polyhedra.agents.quant.yolo_prompt_context import build_yolo_prompt_context
33
+ from polyhedra.core.artifacts import (
34
+ Availability,
35
+ ConfidenceLevel,
36
+ DataIssue,
37
+ DeltaState,
38
+ Direction,
39
+ JsonArtifactRef,
40
+ )
41
+ from polyhedra.core.dependency_executor import AgentCompletion
42
  from polyhedra.core.token_budget import TokenBudget
43
+ from polyhedra.services.artifact_publisher import ArtifactPublisher
44
+ from polyhedra.services.evidence_verifier import EvidenceSource, verify_evidence
45
+ from polyhedra.services.file_writer import ScopedFileWriter
46
 
47
  if TYPE_CHECKING:
48
  from polyhedra.services.llm_service import LLMService
 
92
  async def can_handle(self, mention: Mention) -> bool:
93
  return mention.mentioned_role == self.role
94
 
95
+ async def execute_typed(
96
+ self,
97
+ inputs: TrendAnalystInput,
98
+ *,
99
+ files: ScopedFileWriter,
100
+ publisher: ArtifactPublisher,
101
+ now: Callable[[], datetime] | None = None,
102
+ research_state: dict[str, Any] | None = None,
103
+ ) -> AgentCompletion:
104
+ """Run the existing technical-analysis role through the V8 boundary."""
105
+ if type(inputs) is not TrendAnalystInput:
106
+ raise TypeError("TrendAnalyst typed execution requires its registered input")
107
+ if (files.agent, files.run_id, files.ticker_scope) != (
108
+ "TrendAnalyst",
109
+ inputs.run_id,
110
+ tuple(inputs.ticker_scope),
111
+ ):
112
+ raise ValueError("TrendAnalyst input contradicts scoped activation")
113
+ if (publisher.run_id, publisher.session_id) != (inputs.run_id, inputs.session_id):
114
+ raise ValueError("TrendAnalyst publisher contradicts activation identity")
115
+
116
+ clock = now or (lambda: datetime.now(tz=timezone.utc))
117
+ sources, input_refs = _trend_sources(inputs, files)
118
+ publisher.record_input("TrendAnalyst", inputs)
119
+
120
+ if all(not market.ohlcv for market in inputs.dependencies.market_data):
121
+ payload = TrendPayload(ticker_analyses=[
122
+ _unavailable_analysis(market)
123
+ for market in inputs.dependencies.market_data
124
+ ])
125
+ else:
126
+ binding = quant_io_binding("TrendAnalyst")
127
+ completion = await self._llm.complete_structured(
128
+ binding.build_prompt(inputs),
129
+ binding.output_schema,
130
+ )
131
+ payload = completion.output
132
+ if research_state is not None:
133
+ self._log_token_usage(
134
+ research_state,
135
+ completion.input_tokens,
136
+ completion.output_tokens,
137
+ cache_hit=False,
138
+ )
139
+ _validate_trend_payload(inputs, payload)
140
+ verify_evidence(payload, sources)
141
+
142
+ data_gaps = [
143
+ gap
144
+ for analysis in payload.ticker_analyses
145
+ for gap in analysis.data_gaps
146
+ ]
147
+ status = _trend_status(inputs, payload)
148
+ output = TrendAnalystOutput(
149
+ schema_version="8.0",
150
+ artifact_id=f"{inputs.run_id}-trend-analysis",
151
+ run_id=inputs.run_id,
152
+ session_id=inputs.session_id,
153
+ producer="TrendAnalyst",
154
+ ticker_scope=inputs.ticker_scope,
155
+ created_at=clock(),
156
+ status=status,
157
+ input_refs=input_refs,
158
+ baseline_refs=inputs.baseline_refs,
159
+ data_gaps=data_gaps,
160
+ render_ref=None,
161
+ payload=payload,
162
+ )
163
+ published = publisher.publish(
164
+ files,
165
+ output,
166
+ json_path=f"quant/runs/{inputs.run_id}/trend_analysis.json",
167
+ markdown_path=f"quant/runs/{inputs.run_id}/trend_analysis.md",
168
+ )
169
+ return AgentCompletion(
170
+ artifact_ref=published.artifact_ref,
171
+ result_status=output.status,
172
+ )
173
+
174
  async def handle(
175
  self,
176
  mention: Mention,
 
307
  ## [5] ROUTING
308
  {LLM_ROUTING_PROMPT}"""
309
 
310
+
311
+ def _trend_sources(
312
+ inputs: TrendAnalystInput,
313
+ files: ScopedFileWriter,
314
+ ) -> tuple[list[EvidenceSource], list[JsonArtifactRef]]:
315
+ manifest = inputs.dependencies.data_fetch
316
+ manifest_ref = JsonArtifactRef(
317
+ schema_version=manifest.schema_version,
318
+ artifact_id=manifest.artifact_id,
319
+ run_id=manifest.run_id,
320
+ session_id=manifest.session_id,
321
+ producer="DataFetcher",
322
+ path=f"quant/runs/{manifest.run_id}/data_fetch.json",
323
+ )
324
+ sources = [EvidenceSource(manifest_ref, manifest)]
325
+ refs = [manifest_ref]
326
+ result_by_ticker = {item.ticker: item for item in manifest.ticker_results}
327
+ for market in inputs.dependencies.market_data:
328
+ result = result_by_ticker[market.ticker]
329
+ reference = result.market_data_ref
330
+ if reference is None:
331
+ raise ValueError("TrendAnalyst requires each market-data artifact reference")
332
+ if (
333
+ reference.schema_version,
334
+ reference.artifact_id,
335
+ reference.run_id,
336
+ reference.session_id,
337
+ reference.producer,
338
+ ) != (
339
+ market.schema_version,
340
+ market.artifact_id,
341
+ market.run_id,
342
+ market.session_id,
343
+ market.producer,
344
+ ):
345
+ raise ValueError("market-data contents contradict the DataFetcher reference")
346
+ sources.append(EvidenceSource(reference, market))
347
+ refs.append(reference)
348
+ for source in sources:
349
+ if files.published_reference(source.reference.path) != source.reference:
350
+ raise ValueError("TrendAnalyst input was not published through its scoped runtime")
351
+
352
+ prior = inputs.optional_context.prior_trend
353
+ if prior is not None:
354
+ matching = [
355
+ reference
356
+ for reference in inputs.baseline_refs
357
+ if (
358
+ reference.producer,
359
+ reference.artifact_id,
360
+ reference.run_id,
361
+ reference.session_id,
362
+ ) == (
363
+ "TrendAnalyst",
364
+ prior.artifact_id,
365
+ prior.run_id,
366
+ prior.session_id,
367
+ )
368
+ ]
369
+ if len(matching) != 1:
370
+ raise ValueError("prior trend context requires its exact baseline reference")
371
+ if files.published_reference(matching[0].path) != matching[0]:
372
+ raise ValueError("prior trend context is not an approved published baseline")
373
+ sources.append(EvidenceSource(matching[0], prior))
374
+ return sources, refs
375
+
376
+
377
+ def _unavailable_analysis(market: MarketDataArtifact) -> TrendAnalysis:
378
+ gaps = list(market.quality_issues)
379
+ if not gaps:
380
+ gaps = [DataIssue(
381
+ component="OHLCV",
382
+ code="OHLCV_UNAVAILABLE",
383
+ message="No valid OHLCV bars are available for technical analysis.",
384
+ ticker=market.ticker,
385
+ )]
386
+ return TrendAnalysis(
387
+ ticker=market.ticker,
388
+ price_direction=Direction.UNKNOWN,
389
+ price_change_percentage=None,
390
+ measurement_days=None,
391
+ support_levels=[],
392
+ resistance_levels=[],
393
+ volume_state=VolumeState.UNKNOWN,
394
+ sma_20_state=RelativeState.UNKNOWN,
395
+ ema_20_state=RelativeState.UNKNOWN,
396
+ moving_average_crossover=CrossoverState.UNKNOWN,
397
+ rsi_14_state=RSIState.UNKNOWN,
398
+ macd_state=MACDState.UNKNOWN,
399
+ confidence=ConfidenceLevel.UNKNOWN,
400
+ evidence_refs=[],
401
+ delta_state=DeltaState.NOT_COMPARED,
402
+ data_gaps=gaps,
403
+ )
404
+
405
+
406
+ def _validate_trend_payload(inputs: TrendAnalystInput, payload: TrendPayload) -> None:
407
+ by_ticker = {analysis.ticker: analysis for analysis in payload.ticker_analyses}
408
+ if len(by_ticker) != len(payload.ticker_analyses) or set(by_ticker) != set(inputs.ticker_scope):
409
+ raise ValueError("TrendAnalyst output must contain exactly one analysis per ticker")
410
+ if inputs.run_mode == "BASELINE" and any(
411
+ analysis.delta_state != DeltaState.NOT_COMPARED
412
+ for analysis in payload.ticker_analyses
413
+ ):
414
+ raise ValueError("baseline trend analysis cannot claim a prior-run delta")
415
+ prior = inputs.optional_context.prior_trend
416
+ if prior is not None and any(
417
+ analysis.ticker in prior.ticker_scope
418
+ and analysis.delta_state == DeltaState.NOT_COMPARED
419
+ for analysis in payload.ticker_analyses
420
+ ):
421
+ raise ValueError("delta trend analysis must compare overlapping prior context")
422
+ market_by_ticker = {
423
+ market.ticker: market
424
+ for market in inputs.dependencies.market_data
425
+ }
426
+ for ticker, analysis in by_ticker.items():
427
+ source_gaps = {
428
+ (issue.component, issue.code)
429
+ for issue in market_by_ticker[ticker].quality_issues
430
+ }
431
+ output_gaps = {
432
+ (issue.component, issue.code)
433
+ for issue in analysis.data_gaps
434
+ }
435
+ if not source_gaps.issubset(output_gaps):
436
+ raise ValueError("TrendAnalyst output omitted a source data-quality issue")
437
+ if not analysis.evidence_refs and not analysis.data_gaps:
438
+ raise ValueError("trend analysis without evidence requires an explicit data gap")
439
+
440
+
441
+ def _trend_status(inputs: TrendAnalystInput, payload: TrendPayload) -> Availability:
442
+ analyses = payload.ticker_analyses
443
+ if all(
444
+ analysis.confidence == ConfidenceLevel.UNKNOWN and not analysis.evidence_refs
445
+ for analysis in analyses
446
+ ):
447
+ return Availability.UNAVAILABLE
448
+ source_partial = inputs.dependencies.data_fetch.overall_status != Availability.COMPLETE
449
+ analysis_partial = any(
450
+ analysis.confidence == ConfidenceLevel.UNKNOWN or analysis.data_gaps
451
+ for analysis in analyses
452
+ )
453
+ return Availability.PARTIAL if source_partial or analysis_partial else Availability.COMPLETE
454
+
tests/test_trend_typed.py ADDED
@@ -0,0 +1,388 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """TrendAnalyst preserves LLM-first analysis behind the V8 typed boundary."""
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.analysis_contracts import (
10
+ TrendAnalystInput,
11
+ TrendAnalystOutput,
12
+ TrendContext,
13
+ TrendDependencies,
14
+ TrendPayload,
15
+ )
16
+ from polyhedra.agents.quant.market_data_contracts import (
17
+ DataFetcherOutput,
18
+ MarketDataArtifact,
19
+ TickerFetchResult,
20
+ )
21
+ from polyhedra.agents.quant.trendanalyst import TrendAnalystAgent
22
+ from polyhedra.core.artifacts import JsonArtifactRef
23
+ from polyhedra.services.artifact_publisher import ArtifactPublisher
24
+ from polyhedra.services.file_writer import FileWriter, PublicationRegistry, ScopedFileWriter
25
+ from polyhedra.services.llm_service import LLMService, StructuredCompletion
26
+
27
+ AT = datetime(2026, 9, 12, 12, tzinfo=timezone.utc)
28
+
29
+
30
+ class ControlledLLM:
31
+ def __init__(self, payload: TrendPayload) -> None:
32
+ self.payload = payload
33
+ self.calls = []
34
+
35
+ async def complete_structured(self, prompt, output_schema):
36
+ self.calls.append((prompt, output_schema))
37
+ return StructuredCompletion(self.payload, 12, 18, 1)
38
+
39
+
40
+ def market_data(*, available: bool = True) -> MarketDataArtifact:
41
+ issues = [] if available else [{
42
+ "component": "OHLCV",
43
+ "code": "PROVIDER_UNAVAILABLE",
44
+ "message": "No valid price bars returned.",
45
+ "ticker": "SPY",
46
+ }, {
47
+ "component": "INDICATORS",
48
+ "code": "SOURCE_OHLCV_UNAVAILABLE",
49
+ "message": "Indicators cannot be computed without prices.",
50
+ "ticker": "SPY",
51
+ }]
52
+ return MarketDataArtifact.model_validate({
53
+ "schema_version": "8.0",
54
+ "artifact_id": "run1-market-SPY",
55
+ "session_id": "session1",
56
+ "run_id": "run1",
57
+ "producer": "DataFetcher",
58
+ "ticker": "SPY",
59
+ "retrieved_at": AT,
60
+ "market_date": "2026-09-11" if available else None,
61
+ "status": "COMPLETE" if available else "PARTIAL",
62
+ "ohlcv": [{
63
+ "market_date": "2026-09-11",
64
+ "open": 650.0,
65
+ "high": 656.0,
66
+ "low": 648.0,
67
+ "close": 655.0,
68
+ "adjusted_close": 655.0,
69
+ "volume": 42000000.0,
70
+ }] if available else [],
71
+ "indicators": {"points": [{
72
+ "market_date": "2026-09-11",
73
+ "sma_20": 645.0,
74
+ "ema_20": 647.0,
75
+ "rsi_14": 58.0,
76
+ "macd": 1.2,
77
+ "macd_signal": 0.9,
78
+ "macd_histogram": 0.3,
79
+ }] if available else []},
80
+ "news": [],
81
+ "earnings": [],
82
+ "provenance": [
83
+ {
84
+ "component": "OHLCV",
85
+ "provider": "controlled" if available else None,
86
+ "retrieved_at": AT,
87
+ "source_observed_at": AT if available else None,
88
+ "freshness": "FRESH" if available else "UNKNOWN",
89
+ "availability": "AVAILABLE" if available else "UNAVAILABLE",
90
+ "record_count": 1 if available else 0,
91
+ },
92
+ {
93
+ "component": "INDICATORS",
94
+ "provider": "computed" if available else None,
95
+ "retrieved_at": AT,
96
+ "source_observed_at": AT if available else None,
97
+ "freshness": "FRESH" if available else "UNKNOWN",
98
+ "availability": "AVAILABLE" if available else "UNAVAILABLE",
99
+ "record_count": 1 if available else 0,
100
+ },
101
+ {
102
+ "component": "NEWS",
103
+ "provider": "controlled",
104
+ "retrieved_at": AT,
105
+ "source_observed_at": None,
106
+ "freshness": "UNKNOWN",
107
+ "availability": "AVAILABLE",
108
+ "record_count": 0,
109
+ },
110
+ {
111
+ "component": "EARNINGS",
112
+ "provider": None,
113
+ "retrieved_at": AT,
114
+ "source_observed_at": None,
115
+ "freshness": "UNKNOWN",
116
+ "availability": "NOT_APPLICABLE",
117
+ "record_count": 0,
118
+ },
119
+ ],
120
+ "quality_issues": issues,
121
+ "baseline_ref": None,
122
+ })
123
+
124
+
125
+ def publish_dependencies(tmp_path: Path, *, available: bool = True):
126
+ session = tmp_path / "session1"
127
+ session.mkdir()
128
+ writer = FileWriter(session, session_id="session1")
129
+ publications = PublicationRegistry()
130
+ data_files = ScopedFileWriter(
131
+ writer,
132
+ agent="DataFetcher",
133
+ run_id="run1",
134
+ ticker_scope=["SPY"],
135
+ publications=publications,
136
+ )
137
+ publisher = ArtifactPublisher(writer, session_id="session1", run_id="run1")
138
+ market = market_data(available=available)
139
+ raw = publisher.publish_auxiliary(
140
+ data_files,
141
+ market,
142
+ schema=MarketDataArtifact,
143
+ json_path="quant/runs/run1/raw/SPY.json",
144
+ markdown_path="quant/runs/run1/raw/SPY_summary.md",
145
+ render_markdown=lambda _: "# SPY market data\n",
146
+ )
147
+ result = TickerFetchResult.from_artifact(market, raw.artifact_ref, raw.rendering_ref)
148
+ manifest = DataFetcherOutput(
149
+ schema_version="8.0",
150
+ artifact_id="run1-data-fetch",
151
+ run_id="run1",
152
+ session_id="session1",
153
+ completed_at=AT,
154
+ ticker_scope=["SPY"],
155
+ overall_status=result.status,
156
+ ticker_results=[result],
157
+ )
158
+ publisher.publish(
159
+ data_files,
160
+ manifest,
161
+ json_path="quant/runs/run1/data_fetch.json",
162
+ markdown_path="quant/runs/run1/data_fetch.md",
163
+ )
164
+ trend_files = ScopedFileWriter(
165
+ writer,
166
+ agent="TrendAnalyst",
167
+ run_id="run1",
168
+ ticker_scope=["SPY"],
169
+ publications=publications,
170
+ )
171
+ inputs = TrendAnalystInput(
172
+ run_id="run1",
173
+ session_id="session1",
174
+ run_mode="BASELINE",
175
+ as_of=AT,
176
+ ticker_scope=["SPY"],
177
+ dependencies=TrendDependencies(data_fetch=manifest, market_data=[market]),
178
+ optional_context=TrendContext(prior_trend=None),
179
+ baseline_refs=[],
180
+ )
181
+ return session, writer, publications, trend_files, publisher, inputs, raw.artifact_ref
182
+
183
+
184
+ def analyzed_payload(
185
+ raw_ref,
186
+ *,
187
+ artifact_id: str | None = None,
188
+ prior_ref: JsonArtifactRef | None = None,
189
+ delta_state: str = "NOT_COMPARED",
190
+ ) -> TrendPayload:
191
+ evidence_ref = raw_ref.model_copy(
192
+ update={"artifact_id": artifact_id},
193
+ ) if artifact_id else raw_ref
194
+ evidence = [{
195
+ "artifact": evidence_ref,
196
+ "field_path": "/ohlcv/0/close",
197
+ }]
198
+ if prior_ref is not None:
199
+ evidence.append({
200
+ "artifact": prior_ref,
201
+ "field_path": "/payload/ticker_analyses/0/price_direction",
202
+ })
203
+ return TrendPayload.model_validate({
204
+ "ticker_analyses": [{
205
+ "ticker": "SPY",
206
+ "price_direction": "BULLISH",
207
+ "price_change_percentage": 0.77,
208
+ "measurement_days": 1,
209
+ "support_levels": [],
210
+ "resistance_levels": [],
211
+ "volume_state": "NORMAL",
212
+ "sma_20_state": "ABOVE",
213
+ "ema_20_state": "ABOVE",
214
+ "moving_average_crossover": "NONE",
215
+ "rsi_14_state": "NEUTRAL",
216
+ "macd_state": "BULLISH",
217
+ "confidence": "MEDIUM",
218
+ "evidence_refs": evidence,
219
+ "delta_state": delta_state,
220
+ "data_gaps": [],
221
+ }],
222
+ })
223
+
224
+
225
+ @pytest.mark.asyncio
226
+ async def test_typed_trend_calls_llm_verifies_evidence_and_publishes(tmp_path: Path):
227
+ session, _, _, files, publisher, inputs, raw_ref = publish_dependencies(tmp_path)
228
+ llm = LLMService(provider="openai", api_key="test-only")
229
+ llm.complete = AsyncMock(return_value=(analyzed_payload(raw_ref).model_dump_json(), 12, 18))
230
+ research_state = {"quant_state": {}}
231
+
232
+ completion = await TrendAnalystAgent(llm).execute_typed(
233
+ inputs,
234
+ files=files,
235
+ publisher=publisher,
236
+ now=lambda: AT,
237
+ research_state=research_state,
238
+ )
239
+
240
+ assert completion.result_status == "COMPLETE"
241
+ assert llm.complete.await_count == 1
242
+ request = llm.complete.call_args.args[0]
243
+ assert "do not make a trading recommendation" in request
244
+ assert "next_role" not in request
245
+ assert research_state["quant_state"]["token_log"][0]["prompt_tokens"] == 12
246
+ output = TrendAnalystOutput.model_validate_json(
247
+ (session / "quant/runs/run1/trend_analysis.json").read_text(),
248
+ strict=True,
249
+ )
250
+ assert [reference.path for reference in output.input_refs] == [
251
+ "quant/runs/run1/data_fetch.json",
252
+ "quant/runs/run1/raw/SPY.json",
253
+ ]
254
+ assert output.payload.ticker_analyses[0].price_direction == "BULLISH"
255
+ assert (session / "quant/runs/run1/trend_analysis.md").is_file()
256
+
257
+
258
+ @pytest.mark.asyncio
259
+ async def test_typed_trend_rejects_invented_llm_citation(tmp_path: Path):
260
+ session, _, _, files, publisher, inputs, raw_ref = publish_dependencies(tmp_path)
261
+ llm = ControlledLLM(analyzed_payload(raw_ref, artifact_id="invented"))
262
+
263
+ with pytest.raises(ValueError, match="outside the frozen input"):
264
+ await TrendAnalystAgent(llm).execute_typed(
265
+ inputs,
266
+ files=files,
267
+ publisher=publisher,
268
+ now=lambda: AT,
269
+ )
270
+ assert not (session / "quant/runs/run1/trend_analysis.json").exists()
271
+
272
+
273
+ @pytest.mark.asyncio
274
+ async def test_missing_ohlcv_publishes_unavailable_without_llm_reasoning(tmp_path: Path):
275
+ session, _, _, files, publisher, inputs, raw_ref = publish_dependencies(
276
+ tmp_path,
277
+ available=False,
278
+ )
279
+ llm = ControlledLLM(analyzed_payload(raw_ref))
280
+
281
+ completion = await TrendAnalystAgent(llm).execute_typed(
282
+ inputs,
283
+ files=files,
284
+ publisher=publisher,
285
+ now=lambda: AT,
286
+ )
287
+
288
+ assert completion.result_status == "UNAVAILABLE"
289
+ assert llm.calls == []
290
+ output = TrendAnalystOutput.model_validate_json(
291
+ (session / "quant/runs/run1/trend_analysis.json").read_text(),
292
+ strict=True,
293
+ )
294
+ analysis = output.payload.ticker_analyses[0]
295
+ assert analysis.price_direction == "UNKNOWN"
296
+ assert analysis.evidence_refs == []
297
+ assert {gap.code for gap in analysis.data_gaps} == {
298
+ "PROVIDER_UNAVAILABLE",
299
+ "SOURCE_OHLCV_UNAVAILABLE",
300
+ }
301
+
302
+
303
+ @pytest.mark.asyncio
304
+ async def test_delta_trend_consumes_published_prior_analysis(tmp_path: Path):
305
+ session, writer, publications, _, publisher, baseline_inputs, raw_ref = (
306
+ publish_dependencies(tmp_path)
307
+ )
308
+ prior_data_ref = JsonArtifactRef(
309
+ schema_version="8.0",
310
+ artifact_id="base-data-fetch",
311
+ run_id="base",
312
+ session_id="session1",
313
+ producer="DataFetcher",
314
+ path="quant/runs/base/data_fetch.json",
315
+ )
316
+ prior_payload = analyzed_payload(
317
+ prior_data_ref.model_copy(update={
318
+ "artifact_id": "base-market-SPY",
319
+ "path": "quant/runs/base/raw/SPY.json",
320
+ }),
321
+ )
322
+ prior_output = TrendAnalystOutput(
323
+ schema_version="8.0",
324
+ artifact_id="base-trend-analysis",
325
+ run_id="base",
326
+ session_id="session1",
327
+ producer="TrendAnalyst",
328
+ ticker_scope=["SPY"],
329
+ created_at=AT,
330
+ status="COMPLETE",
331
+ input_refs=[prior_data_ref],
332
+ baseline_refs=[],
333
+ data_gaps=[],
334
+ render_ref=None,
335
+ payload=prior_payload,
336
+ )
337
+ prior_files = ScopedFileWriter(
338
+ writer,
339
+ agent="TrendAnalyst",
340
+ run_id="base",
341
+ ticker_scope=["SPY"],
342
+ publications=publications,
343
+ )
344
+ prior_publisher = ArtifactPublisher(writer, session_id="session1", run_id="base")
345
+ prior_publication = prior_publisher.publish(
346
+ prior_files,
347
+ prior_output,
348
+ json_path="quant/runs/base/trend_analysis.json",
349
+ markdown_path="quant/runs/base/trend_analysis.md",
350
+ )
351
+ inputs = TrendAnalystInput(
352
+ run_id="run1",
353
+ session_id="session1",
354
+ run_mode="DELTA",
355
+ as_of=AT,
356
+ ticker_scope=["SPY"],
357
+ dependencies=baseline_inputs.dependencies,
358
+ optional_context=TrendContext(prior_trend=prior_output),
359
+ baseline_refs=[prior_publication.artifact_ref],
360
+ )
361
+ files = ScopedFileWriter(
362
+ writer,
363
+ agent="TrendAnalyst",
364
+ run_id="run1",
365
+ ticker_scope=["SPY"],
366
+ baseline_run_id="base",
367
+ publications=publications,
368
+ )
369
+ llm = ControlledLLM(analyzed_payload(
370
+ raw_ref,
371
+ prior_ref=prior_publication.artifact_ref,
372
+ delta_state="CHANGED",
373
+ ))
374
+
375
+ completion = await TrendAnalystAgent(llm).execute_typed(
376
+ inputs,
377
+ files=files,
378
+ publisher=publisher,
379
+ now=lambda: AT,
380
+ )
381
+
382
+ assert completion.result_status == "COMPLETE"
383
+ output = TrendAnalystOutput.model_validate_json(
384
+ (session / "quant/runs/run1/trend_analysis.json").read_text(),
385
+ strict=True,
386
+ )
387
+ assert output.baseline_refs == [prior_publication.artifact_ref]
388
+ assert output.payload.ticker_analyses[0].delta_state == "CHANGED"