Download src/polyhedra/core/quant_contracts.py from polyHedra/PolyHedra: direct link, hf CLI and curl.
- Browser
- Download file 11.7 kB
-
https://huggingface.co/spaces/polyHedra/PolyHedra/resolve/main/src/polyhedra/core/quant_contracts.py
- Command line
-
hf download hf://spaces/polyHedra/PolyHedra/src/polyhedra/core/quant_contracts.py
-
curl -L -o quant_contracts.py https://huggingface.co/spaces/polyHedra/PolyHedra/resolve/main/src/polyhedra/core/quant_contracts.py
11.7 kB
| """Packaged quant routing and filename contracts, independent of agent imports. | |
| These declarations describe permissions; the scoped file interface enforces them. | |
| Loading this registry does not activate or migrate the existing runtime. | |
| """ | |
| from enum import StrEnum | |
| from graphlib import CycleError, TopologicalSorter | |
| from string import Formatter | |
| from typing import Literal, Self, get_args | |
| from pydantic import BaseModel, ConfigDict, field_validator, model_validator | |
| AgentName = Literal[ | |
| "DataFetcher", "OptionsFlowWatcher", "TrendAnalyst", "SentimentAnalyst", | |
| "MarketEventWatcher", "MacroContextWatcher", "UnusualEventDetector", "EventRouter", | |
| "BTCAnalyst", "SPYAnalyst", "QQQAnalyst", "GLDAnalyst", "QuantResearcher", | |
| "Backtester", "RiskAnalyst", "QuantStrategist", "Publisher", "VizAgent", | |
| "PortfolioMonitor", | |
| ] | |
| class Scope(StrEnum): | |
| QUANT = "QUANT" | |
| GENERAL = "GENERAL" | |
| SPECIALIZED = "SPECIALIZED" | |
| OPTIONS = "OPTIONS" | |
| class ExecutionContext(StrEnum): | |
| YOLO = "YOLO" | |
| VISUALIZATION = "VISUALIZATION" | |
| PORTFOLIO_MONITOR = "PORTFOLIO_MONITOR" | |
| class ContractModel(BaseModel): | |
| model_config = ConfigDict(extra="forbid", frozen=True) | |
| class FilePermissions(ContractModel): | |
| read: tuple[str, ...] = () | |
| create: tuple[str, ...] = () | |
| edit: tuple[str, ...] = () | |
| list: tuple[str, ...] = () | |
| baseline_read: tuple[str, ...] = () | |
| baseline_list: tuple[str, ...] = () | |
| def valid_templates(cls, paths: tuple[str, ...], info) -> tuple[str, ...]: | |
| if len(paths) != len(set(paths)): | |
| raise ValueError("duplicate filename permission") | |
| run_field = "baseline_run_id" if info.field_name.startswith("baseline_") else "run_id" | |
| for path in paths: | |
| if path == "quant/strategist_performance.json" and run_field == "run_id": | |
| continue | |
| if not path.startswith(f"quant/runs/{{{run_field}}}/"): | |
| raise ValueError("permission must bind to its declared run") | |
| if any(part in {"", ".", ".."} for part in path.split("/")): | |
| raise ValueError("permission must be a normalized session-relative filename") | |
| if any(char in path for char in "\\:*?[]"): | |
| raise ValueError("wildcards and platform-specific paths are forbidden") | |
| for _, field, spec, conversion in Formatter().parse(path): | |
| if field is not None and (field not in {run_field, "ticker"} or spec or conversion): | |
| raise ValueError("unknown filename placeholder") | |
| if not path.endswith((".json", ".md", ".png")): | |
| raise ValueError("permission must name an artifact file") | |
| return paths | |
| def edits_are_owned(self) -> Self: | |
| if not set(self.edit).issubset(self.create): | |
| raise ValueError("edit permission requires output ownership") | |
| return self | |
| class AgentContract(ContractModel): | |
| name: AgentName | |
| dependencies: tuple[AgentName, ...] | |
| scope: Scope | |
| context: ExecutionContext = ExecutionContext.YOLO | |
| symbol: Literal["BTC", "SPY", "QQQ", "GLD"] | None = None | |
| permissions: FilePermissions | |
| def identity(self) -> Self: | |
| fixed = {"BTCAnalyst": "BTC", "SPYAnalyst": "SPY", "QQQAnalyst": "QQQ", "GLDAnalyst": "GLD"} | |
| if self.symbol != fixed.get(self.name): | |
| raise ValueError("fixed analyst symbol must match registered identity") | |
| if self.symbol and self.scope != Scope.SPECIALIZED: | |
| raise ValueError("fixed analyst requires SPECIALIZED scope") | |
| expected = { | |
| "VizAgent": ExecutionContext.VISUALIZATION, | |
| "PortfolioMonitor": ExecutionContext.PORTFOLIO_MONITOR, | |
| }.get(self.name, ExecutionContext.YOLO) | |
| if self.context != expected: | |
| raise ValueError("agent has the wrong execution context") | |
| if len(self.dependencies) != len(set(self.dependencies)): | |
| raise ValueError("duplicate dependency") | |
| return self | |
| class QuantContracts(ContractModel): | |
| schema_version: Literal["8.0"] = "8.0" | |
| agents: tuple[AgentContract, ...] | |
| def complete_registry(self) -> Self: | |
| names = [agent.name for agent in self.agents] | |
| if len(names) != len(set(names)) or set(names) != set(get_args(AgentName)): | |
| raise ValueError("registry must contain each of the 19 quant agents exactly once") | |
| try: | |
| tuple(TopologicalSorter({a.name: a.dependencies for a in self.agents}).static_order()) | |
| except CycleError as exc: | |
| raise ValueError("quant dependency cycle") from exc | |
| owners: dict[str, str] = {} | |
| for agent in self.agents: | |
| for path in agent.permissions.create: | |
| if path in owners: | |
| raise ValueError(f"duplicate output owner: {path}") | |
| if path == "quant/strategist_performance.json" and agent.name != "QuantStrategist": | |
| raise ValueError("performance writes belong to the trusted strategist tool") | |
| owners[path] = agent.name | |
| return self | |
| def for_agent(self, name: AgentName) -> AgentContract: | |
| for agent in self.agents: | |
| if agent.name == name: | |
| return agent | |
| raise KeyError(name) | |
| def _files(names: tuple[str, ...], *, baseline: bool = False) -> tuple[str, ...]: | |
| run = "{baseline_run_id}" if baseline else "{run_id}" | |
| return tuple(f"quant/runs/{run}/{name}" for name in names) | |
| def _entry( | |
| name: AgentName, scope: Scope, dependencies: tuple[AgentName, ...], output: str, | |
| reads: tuple[str, ...] = (), baseline: tuple[str, ...] = (), | |
| *, listing: tuple[str, ...] = (), extra_outputs: tuple[str, ...] = (), | |
| baseline_listing: tuple[str, ...] = (), symbol=None, | |
| context: ExecutionContext = ExecutionContext.YOLO, | |
| ) -> AgentContract: | |
| outputs = _files((f"{output}.json", f"{output}.md", *extra_outputs)) | |
| read = _files(reads) | |
| if name == "QuantStrategist": | |
| read += ("quant/strategist_performance.json",) | |
| outputs += ("quant/strategist_performance.json",) | |
| return AgentContract( | |
| name=name, scope=scope, dependencies=dependencies, symbol=symbol, context=context, | |
| permissions=FilePermissions( | |
| read=read, create=outputs, edit=outputs, list=_files(listing), | |
| baseline_read=_files(baseline, baseline=True), | |
| baseline_list=_files(baseline_listing, baseline=True), | |
| ), | |
| ) | |
| def load_quant_contracts() -> QuantContracts: | |
| """Load a fresh immutable contract from declarations shipped in the package.""" | |
| raw = ("raw/{ticker}.json",) | |
| market = ("data_fetch.json", *raw, "trend_analysis.json") | |
| strategy = ("signals.json", "risk_assessment.json", "trade_proposals.json", "post.json") | |
| asset_reads = ("trend_analysis.json", "event_route.json", "market_events.json") | |
| asset_context = ("macro_context.json", "unusual_events.json", "sentiment_analysis.json") | |
| return QuantContracts(agents=( | |
| _entry("DataFetcher", Scope.QUANT, (), "data_fetch", ("data_fetch.json", *raw), raw, | |
| listing=raw, baseline_listing=raw, | |
| extra_outputs=("raw/{ticker}.json", "raw/{ticker}_summary.md")), | |
| _entry("OptionsFlowWatcher", Scope.OPTIONS, (), "options_flow", baseline=( | |
| "options_flow.json", "risk_assessment.json", "trade_proposals.json", "post.json")), | |
| _entry("TrendAnalyst", Scope.QUANT, ("DataFetcher",), "trend_analysis", | |
| ("data_fetch.json", *raw), ("trend_analysis.json", "post.json"), listing=raw), | |
| _entry("SentimentAnalyst", Scope.GENERAL, ("DataFetcher",), "sentiment_analysis", market, | |
| ("sentiment_analysis.json", "trend_analysis.json", "signals.json", "post.json"), listing=raw), | |
| _entry("MarketEventWatcher", Scope.SPECIALIZED, ("DataFetcher",), "market_events", market, | |
| ("market_events.json", "trend_analysis.json", *strategy), listing=raw), | |
| _entry("MacroContextWatcher", Scope.SPECIALIZED, ("MarketEventWatcher", "OptionsFlowWatcher"), | |
| "macro_context", ("market_events.json", "options_flow.json"), | |
| ("macro_context.json", "trend_analysis.json", *strategy)), | |
| _entry("UnusualEventDetector", Scope.SPECIALIZED, | |
| ("MarketEventWatcher", "MacroContextWatcher", "OptionsFlowWatcher"), "unusual_events", | |
| ("market_events.json", "options_flow.json", "macro_context.json"), | |
| ("unusual_events.json", *strategy)), | |
| _entry("EventRouter", Scope.SPECIALIZED, ("UnusualEventDetector",), "event_route", | |
| ("unusual_events.json", "market_events.json", "options_flow.json"), | |
| ("event_route.json", "risk_assessment.json", "trade_proposals.json", "post.json")), | |
| *(_entry(name, Scope.SPECIALIZED, ("TrendAnalyst", "EventRouter"), f"{symbol.lower()}_analysis", | |
| (*asset_reads, *(("options_flow.json",) if symbol != "BTC" else ()), *asset_context), | |
| (f"{symbol.lower()}_analysis.json", "trend_analysis.json", *strategy), symbol=symbol) | |
| for name, symbol in (("BTCAnalyst", "BTC"), ("SPYAnalyst", "SPY"), | |
| ("QQQAnalyst", "QQQ"), ("GLDAnalyst", "GLD"))), | |
| _entry("QuantResearcher", Scope.QUANT, | |
| ("TrendAnalyst", "SentimentAnalyst", "BTCAnalyst", "SPYAnalyst", "QQQAnalyst", "GLDAnalyst"), | |
| "signals", ("trend_analysis.json", "sentiment_analysis.json", "asset_analysis.json", | |
| "macro_context.json", "unusual_events.json"), | |
| ("signals.json", "backtest_results.json", "risk_assessment.json", "trade_proposals.json", "post.json")), | |
| _entry("Backtester", Scope.QUANT, ("QuantResearcher",), "backtest_results", | |
| ("signals.json", *raw), | |
| ("signals.json", "backtest_results.json", "risk_assessment.json", "trade_proposals.json"), listing=raw), | |
| _entry("RiskAnalyst", Scope.QUANT, ("Backtester",), "risk_assessment", | |
| ("backtest_results.json", "trend_analysis.json", "asset_analysis.json", "macro_context.json"), | |
| ("backtest_results.json", "risk_assessment.json", "trade_proposals.json", "post.json")), | |
| _entry("QuantStrategist", Scope.QUANT, ("RiskAnalyst",), "trade_proposals", | |
| ("risk_assessment.json", "backtest_results.json", "sentiment_analysis.json", | |
| "signals.json", "asset_analysis.json", "macro_context.json"), | |
| ("signals.json", "backtest_results.json", "risk_assessment.json", "trade_proposals.json", "post.json")), | |
| _entry("Publisher", Scope.QUANT, ("QuantStrategist",), "post", | |
| ("trade_proposals.json", "trend_analysis.json", "sentiment_analysis.json", | |
| "risk_assessment.json", "asset_analysis.json", "macro_context.json"), | |
| ("trade_proposals.json", "post.json", "risk_assessment.json")), | |
| _entry("VizAgent", Scope.QUANT, (), "visualizations", | |
| (*raw, "backtest_results.json", "risk_assessment.json", "portfolio_log.json"), | |
| listing=raw, | |
| extra_outputs=("viz/candlestick_{ticker}.png", "viz/rsi_macd_{ticker}.png", | |
| "viz/backtest.png", "viz/risk_heatmap.png", "viz/portfolio_pnl.png"), | |
| context=ExecutionContext.VISUALIZATION), | |
| _entry("PortfolioMonitor", Scope.QUANT, (), "portfolio_log", | |
| context=ExecutionContext.PORTFOLIO_MONITOR), | |
| )) | |