PolyHedra / src /polyhedra /agents /quant /analysis_contracts.py
yf176
feat: define typed analysis and event contracts
8b01e73
Raw History Blame Contribute Delete
23.7 kB
"""Typed contracts for quant interpretation, event detection, and event assignment."""
from enum import StrEnum
from typing import Annotated, Literal, Self
from pydantic import AwareDatetime, Field, model_validator
from polyhedra.agents.quant.market_data_contracts import (
DataFetcherOutput, MarketDataArtifact, MarketDataComponent,
)
from polyhedra.agents.quant.options_contracts import OptionsFlowWatcherOutput
from polyhedra.core.artifacts import (
AgentArtifact, AgentInput, AnalysisOutcome, Availability, ConfidenceLevel,
DataIssue, DeltaState, Direction, EvidenceRef, NonEmptyText, Ticker,
TickerScope, TypedModel,
)
ConfidenceScore = Annotated[float, Field(strict=True, ge=0, le=1)]
SignedPercentage = Annotated[float, Field(strict=True, description="Signed percentage points.")]
PositiveDays = Annotated[int, Field(strict=True, gt=0)]
PositivePrice = Annotated[float, Field(strict=True, gt=0)]
class RelativeState(StrEnum):
ABOVE = "ABOVE"
BELOW = "BELOW"
AT = "AT"
UNKNOWN = "UNKNOWN"
class CrossoverState(StrEnum):
BULLISH = "BULLISH"
BEARISH = "BEARISH"
NONE = "NONE"
UNKNOWN = "UNKNOWN"
class RSIState(StrEnum):
OVERSOLD = "OVERSOLD"
NEUTRAL = "NEUTRAL"
OVERBOUGHT = "OVERBOUGHT"
UNKNOWN = "UNKNOWN"
class MACDState(StrEnum):
BULLISH = "BULLISH"
BEARISH = "BEARISH"
NEUTRAL = "NEUTRAL"
UNKNOWN = "UNKNOWN"
class VolumeState(StrEnum):
INCREASING = "INCREASING"
DECREASING = "DECREASING"
NORMAL = "NORMAL"
UNUSUAL = "UNUSUAL"
UNKNOWN = "UNKNOWN"
class PriceLevel(TypedModel):
price: PositivePrice
basis: NonEmptyText
evidence_refs: Annotated[list[EvidenceRef], Field(min_length=1)]
class TrendAnalysis(TypedModel):
ticker: Ticker
price_direction: Direction
price_change_percentage: SignedPercentage | None
measurement_days: PositiveDays | None
support_levels: list[PriceLevel]
resistance_levels: list[PriceLevel]
volume_state: VolumeState
sma_20_state: RelativeState
ema_20_state: RelativeState
moving_average_crossover: CrossoverState
rsi_14_state: RSIState
macd_state: MACDState
confidence: ConfidenceLevel
evidence_refs: list[EvidenceRef]
delta_state: DeltaState
data_gaps: list[DataIssue]
@model_validator(mode="after")
def evidence_and_measurement(self) -> Self:
if (self.price_change_percentage is None) != (self.measurement_days is None):
raise ValueError("price magnitude and duration must be present together")
if self.confidence != ConfidenceLevel.UNKNOWN and not self.evidence_refs:
raise ValueError("known-confidence trend requires evidence")
return self
class TrendPayload(TypedModel):
ticker_analyses: list[TrendAnalysis]
class TrendAnalystOutput(AgentArtifact[TrendPayload]):
producer: Literal["TrendAnalyst"] = "TrendAnalyst"
@model_validator(mode="after")
def analyses_match_scope(self) -> Self:
_exact_ticker_records(self.ticker_scope, [item.ticker for item in self.payload.ticker_analyses])
_require_input_producers(self.input_refs, {"DataFetcher"})
_unavailable_has_gaps(self.status, self.data_gaps)
return self
class TrendDependencies(TypedModel):
data_fetch: DataFetcherOutput
market_data: list[MarketDataArtifact]
class TrendContext(TypedModel):
prior_trend: TrendAnalystOutput | None = None
class TrendAnalystInput(AgentInput[TrendDependencies, TrendContext]):
@model_validator(mode="after")
def dependency_scope(self) -> Self:
_fetch_dependencies(self.run_id, self.session_id, self.ticker_scope,
self.dependencies.data_fetch, self.dependencies.market_data)
if self.optional_context.prior_trend:
_prior_output(self, self.optional_context.prior_trend, "TrendAnalyst")
return self
class EvidenceSufficiency(StrEnum):
SUFFICIENT = "SUFFICIENT"
THIN = "THIN"
MOSTLY_UNSCORED = "MOSTLY_UNSCORED"
UNAVAILABLE = "UNAVAILABLE"
class TrendAlignment(StrEnum):
CONFIRMS = "CONFIRMS"
CONTRADICTS = "CONTRADICTS"
MIXED = "MIXED"
NOT_ASSESSED = "NOT_ASSESSED"
class SourceCoverage(TypedModel):
source: NonEmptyText
article_count: Annotated[int, Field(strict=True, ge=0)]
scored_count: Annotated[int, Field(strict=True, ge=0)]
@model_validator(mode="after")
def scored_subset(self) -> Self:
if self.scored_count > self.article_count:
raise ValueError("scored articles exceed source coverage")
return self
class SentimentTheme(TypedModel):
theme: NonEmptyText
direction: Direction
evidence_refs: Annotated[list[EvidenceRef], Field(min_length=1)]
class SentimentAnalysis(TypedModel):
ticker: Ticker
source_coverage: list[SourceCoverage]
article_count: Annotated[int, Field(strict=True, ge=0)]
scored_count: Annotated[int, Field(strict=True, ge=0)]
unscored_count: Annotated[int, Field(strict=True, ge=0)]
evidence_sufficiency: EvidenceSufficiency
aggregate_sentiment: Direction
themes: list[SentimentTheme]
earnings_sentiment: Direction | None
trend_alignment: TrendAlignment
incremental_signal_value: bool
confidence: ConfidenceLevel
evidence_refs: list[EvidenceRef]
delta_state: DeltaState
data_gaps: list[DataIssue]
@model_validator(mode="after")
def counts_and_evidence(self) -> Self:
if sum(item.article_count for item in self.source_coverage) != self.article_count:
raise ValueError("source coverage contradicts article count")
if self.scored_count + self.unscored_count != self.article_count:
raise ValueError("scored and unscored counts contradict article count")
if sum(item.scored_count for item in self.source_coverage) != self.scored_count:
raise ValueError("source coverage contradicts scored count")
if self.evidence_sufficiency != EvidenceSufficiency.SUFFICIENT:
if self.aggregate_sentiment != Direction.UNKNOWN:
raise ValueError("insufficient evidence cannot be labeled neutral or directional")
if self.confidence != ConfidenceLevel.UNKNOWN or self.incremental_signal_value:
raise ValueError("insufficient sentiment evidence cannot claim confidence or signal value")
elif not self.evidence_refs:
raise ValueError("sufficient sentiment assessment requires evidence")
return self
class SentimentPayload(TypedModel):
ticker_analyses: list[SentimentAnalysis]
class SentimentAnalystOutput(AgentArtifact[SentimentPayload]):
producer: Literal["SentimentAnalyst"] = "SentimentAnalyst"
@model_validator(mode="after")
def analyses_match_scope(self) -> Self:
_exact_ticker_records(self.ticker_scope, [item.ticker for item in self.payload.ticker_analyses])
if set(self.ticker_scope) & {"BTC", "SPY", "QQQ", "GLD"}:
raise ValueError("SentimentAnalyst is limited to GENERAL scope")
_require_input_producers(self.input_refs, {"DataFetcher"})
_unavailable_has_gaps(self.status, self.data_gaps)
return self
class SentimentDependencies(TypedModel):
data_fetch: DataFetcherOutput
market_data: list[MarketDataArtifact]
class SentimentContext(TypedModel):
current_trend: TrendAnalystOutput | None = None
prior_sentiment: SentimentAnalystOutput | None = None
class SentimentAnalystInput(AgentInput[SentimentDependencies, SentimentContext]):
@model_validator(mode="after")
def dependency_scope(self) -> Self:
if set(self.ticker_scope) & {"BTC", "SPY", "QQQ", "GLD"}:
raise ValueError("SentimentAnalyst input is limited to GENERAL scope")
_fetch_dependencies(self.run_id, self.session_id, self.ticker_scope,
self.dependencies.data_fetch, self.dependencies.market_data)
if self.optional_context.current_trend:
_current_output(self, self.optional_context.current_trend, "TrendAnalyst")
if self.optional_context.prior_sentiment:
_prior_output(self, self.optional_context.prior_sentiment, "SentimentAnalyst")
return self
class ExternalEventFeedStatus(StrEnum):
NOT_CONFIGURED = "NOT_CONFIGURED"
AVAILABLE = "AVAILABLE"
UNAVAILABLE = "UNAVAILABLE"
class ObservedMarketChange(TypedModel):
component: MarketDataComponent
description: NonEmptyText
direction: Direction
magnitude_percentage: SignedPercentage | None
evidence_refs: Annotated[list[EvidenceRef], Field(min_length=1)]
class CatalystRecord(TypedModel):
headline: NonEmptyText
source: NonEmptyText
published_at: AwareDatetime
evidence_ref: EvidenceRef
class MarketEventContext(TypedModel):
ticker: Ticker
observed_changes: list[ObservedMarketChange]
relevant_catalysts: list[CatalystRecord]
source_refs: list[EvidenceRef]
checked_at: AwareDatetime
external_event_feed_status: ExternalEventFeedStatus
external_event_feed_provider: NonEmptyText | None
delta_state: DeltaState
data_gaps: list[DataIssue]
@model_validator(mode="after")
def external_feed(self) -> Self:
if (self.external_event_feed_status == ExternalEventFeedStatus.AVAILABLE) != (
self.external_event_feed_provider is not None
):
raise ValueError("available external event feed requires its provider")
if self.external_event_feed_status == ExternalEventFeedStatus.NOT_CONFIGURED:
if not any(issue.code == "EXTERNAL_EVENT_FEED_NOT_CONFIGURED" for issue in self.data_gaps):
raise ValueError("unconfigured event feed must remain an explicit data gap")
return self
class MarketEventPayload(TypedModel):
ticker_contexts: list[MarketEventContext]
class MarketEventWatcherOutput(AgentArtifact[MarketEventPayload]):
producer: Literal["MarketEventWatcher"] = "MarketEventWatcher"
@model_validator(mode="after")
def contexts_match_scope(self) -> Self:
_specialized_scope(self.ticker_scope)
_exact_ticker_records(self.ticker_scope, [item.ticker for item in self.payload.ticker_contexts])
_require_input_producers(self.input_refs, {"DataFetcher"})
_unavailable_has_gaps(self.status, self.data_gaps)
return self
class MarketEventDependencies(TypedModel):
data_fetch: DataFetcherOutput
market_data: list[MarketDataArtifact]
class MarketEventOptionalContext(TypedModel):
current_trend: TrendAnalystOutput | None = None
prior_market_events: MarketEventWatcherOutput | None = None
class MarketEventWatcherInput(AgentInput[MarketEventDependencies, MarketEventOptionalContext]):
@model_validator(mode="after")
def dependency_scope(self) -> Self:
_specialized_scope(self.ticker_scope)
_fetch_dependencies(self.run_id, self.session_id, self.ticker_scope,
self.dependencies.data_fetch, self.dependencies.market_data)
if self.optional_context.current_trend:
_current_output(self, self.optional_context.current_trend, "TrendAnalyst")
if self.optional_context.prior_market_events:
_prior_output(self, self.optional_context.prior_market_events, "MarketEventWatcher")
return self
class MacroDriver(TypedModel):
driver_id: NonEmptyText
description: NonEmptyText
direction: Direction
relevance_weight: ConfidenceScore
affected_tickers: TickerScope
evidence_refs: Annotated[list[EvidenceRef], Field(min_length=1)]
class MacroPayload(TypedModel):
main_line: NonEmptyText
drivers: list[MacroDriver]
affected_tickers: TickerScope
confidence: ConfidenceLevel
uncertainties: list[NonEmptyText]
contradictions: list[NonEmptyText]
delta_state: DeltaState
data_gaps: list[DataIssue]
@model_validator(mode="after")
def driver_scope(self) -> Self:
if any(not set(driver.affected_tickers).issubset(self.affected_tickers) for driver in self.drivers):
raise ValueError("macro driver expands affected ticker scope")
if not self.drivers and self.main_line != "UNCLEAR":
raise ValueError("macro main line without evidence must be UNCLEAR")
return self
class MacroContextWatcherOutput(AgentArtifact[MacroPayload]):
producer: Literal["MacroContextWatcher"] = "MacroContextWatcher"
@model_validator(mode="after")
def macro_scope(self) -> Self:
_specialized_scope(self.ticker_scope)
if set(self.payload.affected_tickers) != set(self.ticker_scope):
raise ValueError("macro affected tickers must equal output scope")
required = {"MarketEventWatcher"}
if set(self.ticker_scope) & {"SPY", "QQQ", "GLD"}:
required.add("OptionsFlowWatcher")
_require_input_producers(self.input_refs, required)
_unavailable_has_gaps(self.status, self.data_gaps)
return self
class MacroDependencies(TypedModel):
market_events: MarketEventWatcherOutput
options_flow: OptionsFlowWatcherOutput | None
class MacroOptionalContext(TypedModel):
prior_macro: MacroContextWatcherOutput | None = None
class MacroContextWatcherInput(AgentInput[MacroDependencies, MacroOptionalContext]):
@model_validator(mode="after")
def dependency_scope(self) -> Self:
_specialized_scope(self.ticker_scope)
_current_output(self, self.dependencies.market_events, "MarketEventWatcher")
_options_overlap(self, self.dependencies.options_flow)
if self.optional_context.prior_macro:
_prior_output(self, self.optional_context.prior_macro, "MacroContextWatcher")
return self
class EventType(StrEnum):
PRICE = "PRICE"
NEWS = "NEWS"
MACRO = "MACRO"
OPTIONS = "OPTIONS"
CROSS_MARKET = "CROSS_MARKET"
class EventCandidate(TypedModel):
event_id: NonEmptyText
event_type: EventType
affected_tickers: TickerScope
significance: ConfidenceScore
confidence: ConfidenceLevel
evidence_refs: list[EvidenceRef]
missing_evidence: list[DataIssue]
delta_state: DeltaState
@model_validator(mode="after")
def support(self) -> Self:
if not self.evidence_refs:
raise ValueError("meaningful event requires evidence")
return self
class SuppressionReason(StrEnum):
STALE = "STALE"
DUPLICATE = "DUPLICATE"
UNCHANGED = "UNCHANGED"
LOW_SIGNIFICANCE = "LOW_SIGNIFICANCE"
CONTRADICTED = "CONTRADICTED"
UNSUPPORTED = "UNSUPPORTED"
class SuppressedEvent(TypedModel):
event_id: NonEmptyText
affected_tickers: TickerScope
reason: SuppressionReason
rationale: NonEmptyText
evidence_refs: list[EvidenceRef]
class MonitoringCondition(TypedModel):
condition_id: NonEmptyText
affected_tickers: TickerScope
condition: NonEmptyText
evidence_refs: list[EvidenceRef]
class UnusualEventPayload(TypedModel):
meaningful_events: list[EventCandidate]
suppressed_events: list[SuppressedEvent]
monitoring_conditions: list[MonitoringCondition]
@model_validator(mode="after")
def event_ids(self) -> Self:
meaningful = [item.event_id for item in self.meaningful_events]
suppressed = [item.event_id for item in self.suppressed_events]
if len(meaningful) != len(set(meaningful)) or len(suppressed) != len(set(suppressed)):
raise ValueError("event IDs must be unique")
if set(meaningful) & set(suppressed):
raise ValueError("event cannot be meaningful and suppressed")
return self
class UnusualEventDetectorOutput(AgentArtifact[UnusualEventPayload]):
producer: Literal["UnusualEventDetector"] = "UnusualEventDetector"
@model_validator(mode="after")
def events_match_scope(self) -> Self:
_specialized_scope(self.ticker_scope)
records = [*self.payload.meaningful_events, *self.payload.suppressed_events,
*self.payload.monitoring_conditions]
if any(not set(item.affected_tickers).issubset(self.ticker_scope) for item in records):
raise ValueError("event record expands ticker scope")
required = {"MarketEventWatcher", "MacroContextWatcher"}
if set(self.ticker_scope) & {"SPY", "QQQ", "GLD"}:
required.add("OptionsFlowWatcher")
_require_input_producers(self.input_refs, required)
_unavailable_has_gaps(self.status, self.data_gaps)
return self
class UnusualEventDependencies(TypedModel):
market_events: MarketEventWatcherOutput
macro_context: MacroContextWatcherOutput
options_flow: OptionsFlowWatcherOutput | None
class UnusualEventOptionalContext(TypedModel):
prior_events: UnusualEventDetectorOutput | None = None
class UnusualEventDetectorInput(AgentInput[UnusualEventDependencies, UnusualEventOptionalContext]):
@model_validator(mode="after")
def dependency_scope(self) -> Self:
_specialized_scope(self.ticker_scope)
_current_output(self, self.dependencies.market_events, "MarketEventWatcher")
_current_output(self, self.dependencies.macro_context, "MacroContextWatcher")
_options_overlap(self, self.dependencies.options_flow)
if self.optional_context.prior_events:
_prior_output(self, self.optional_context.prior_events, "UnusualEventDetector")
return self
class EventAssignment(TypedModel):
event_id: NonEmptyText
ticker: Ticker
relevance: ConfidenceScore
evidence_refs: Annotated[list[EvidenceRef], Field(min_length=1)]
rationale: NonEmptyText
class EventRoutePayload(TypedModel):
assignments: list[EventAssignment]
unassigned_event_ids: list[NonEmptyText]
@model_validator(mode="after")
def distinct_routes(self) -> Self:
pairs = [(item.event_id, item.ticker) for item in self.assignments]
if len(pairs) != len(set(pairs)) or len(self.unassigned_event_ids) != len(set(self.unassigned_event_ids)):
raise ValueError("event assignments and unassigned IDs must be unique")
if {item.event_id for item in self.assignments} & set(self.unassigned_event_ids):
raise ValueError("assigned event cannot be unassigned")
return self
class EventRouterOutput(AgentArtifact[EventRoutePayload]):
producer: Literal["EventRouter"] = "EventRouter"
@model_validator(mode="after")
def assignment_scope(self) -> Self:
_specialized_scope(self.ticker_scope)
if any(item.ticker not in self.ticker_scope for item in self.payload.assignments):
raise ValueError("event assignment expands ticker scope")
_require_input_producers(self.input_refs, {"UnusualEventDetector"})
_unavailable_has_gaps(self.status, self.data_gaps)
return self
def validate_for_input(self, inputs: "EventRouterInput") -> None:
if (self.run_id, self.session_id, set(self.ticker_scope)) != (
inputs.run_id, inputs.session_id, set(inputs.ticker_scope)
):
raise ValueError("event route does not match activation identity and scope")
known = {item.event_id for item in inputs.dependencies.unusual_events.payload.meaningful_events}
represented = ({item.event_id for item in self.payload.assignments}
| set(self.payload.unassigned_event_ids))
if represented != known:
raise ValueError("route must account for every and only meaningful event")
class EventRouterDependencies(TypedModel):
unusual_events: UnusualEventDetectorOutput
class EventRouterOptionalContext(TypedModel):
market_events: MarketEventWatcherOutput | None = None
options_flow: OptionsFlowWatcherOutput | None = None
prior_route: EventRouterOutput | None = None
class EventRouterInput(AgentInput[EventRouterDependencies, EventRouterOptionalContext]):
@model_validator(mode="after")
def dependency_scope(self) -> Self:
_specialized_scope(self.ticker_scope)
source = self.dependencies.unusual_events
_current_output(self, source, "UnusualEventDetector")
if self.optional_context.market_events:
_current_output(self, self.optional_context.market_events, "MarketEventWatcher")
_options_overlap(self, self.optional_context.options_flow)
if self.optional_context.prior_route:
_prior_output(self, self.optional_context.prior_route, "EventRouter")
return self
def _exact_ticker_records(scope: list[str], tickers: list[str]) -> None:
if len(tickers) != len(set(tickers)) or set(tickers) != set(scope):
raise ValueError("output must contain exactly one record per in-scope ticker")
def _specialized_scope(scope: list[str]) -> None:
if not set(scope).issubset({"BTC", "SPY", "QQQ", "GLD"}):
raise ValueError("agent is limited to SPECIALIZED scope")
def _unavailable_has_gaps(status: Availability, gaps: list[DataIssue]) -> None:
if status == Availability.UNAVAILABLE and not gaps:
raise ValueError("unavailable artifact requires an explicit data gap")
def _require_input_producers(refs, required: set[str]) -> None:
if not required.issubset({ref.producer for ref in refs}):
raise ValueError("artifact is missing required dependency references")
def _current_output(inputs, output, producer: str) -> None:
if output.producer != producer:
raise ValueError("dependency producer mismatch")
if (output.run_id, output.session_id) != (inputs.run_id, inputs.session_id):
raise ValueError("dependency belongs to another run or session")
if not set(inputs.ticker_scope).issubset(output.ticker_scope):
raise ValueError("dependency does not cover effective scope")
def _prior_output(inputs, output, producer: str) -> None:
if output.producer != producer or output.session_id != inputs.session_id or output.run_id == inputs.run_id:
raise ValueError("prior output has invalid identity")
if not set(output.ticker_scope).intersection(inputs.ticker_scope):
raise ValueError("prior output has no scope overlap")
def _fetch_dependencies(run_id: str, session_id: str, scope: list[str], manifest: DataFetcherOutput,
artifacts: list[MarketDataArtifact]) -> None:
if (manifest.run_id, manifest.session_id) != (run_id, session_id):
raise ValueError("DataFetcher manifest belongs to another run or session")
if not set(scope).issubset(manifest.ticker_scope):
raise ValueError("DataFetcher manifest does not cover effective scope")
tickers = [item.ticker for item in artifacts]
_exact_ticker_records(scope, tickers)
if any((item.run_id, item.session_id) != (run_id, session_id) for item in artifacts):
raise ValueError("market-data artifact belongs to another run or session")
def _options_overlap(inputs, output: OptionsFlowWatcherOutput | None) -> None:
overlap = set(inputs.ticker_scope) & {"SPY", "QQQ", "GLD"}
if not overlap:
if output is not None:
raise ValueError("options output has no effective-scope overlap")
return
if output is None:
raise ValueError("ETF specialized scope requires OptionsFlowWatcher output")
if output.producer != "OptionsFlowWatcher":
raise ValueError("dependency producer mismatch")
if (output.run_id, output.session_id) != (inputs.run_id, inputs.session_id):
raise ValueError("dependency belongs to another run or session")
if set(output.ticker_scope) != overlap:
raise ValueError("options output does not match ETF scope overlap")