chore: pre-existing in-tree work (event-study/research/vintages/prices + migration script + integrity docs)

Committing the prior uncommitted working-tree state that predates this session's
data-source work (was already modified/untracked at session start) so the tree
is clean before push. Includes: event-study + research report integrity/forward
observation work, prices tests, research hash migration script, and the
2026-08-23/24 engineering-log + test-evidence notes. Verified green as part of
the full 362-test suite.
This commit is contained in:
Kunthawat Greethong committed 2026-08-29 09:19:24 +07:00
1 parent dbb787c50a
commit ead9aeb25c
22 files changed
+2326 -66

No files matched your search

+42 -8
View File
@@ -6,6 +6,7 @@ import math
from datetime import date, datetime, timezone
from statistics import fmean
from typing import Any, Mapping, Sequence
from zoneinfo import ZoneInfo
class EventStudyError(ValueError):
@@ -34,6 +35,18 @@ def _canonical_timestamp(value: str) -> str:
return parsed.astimezone(timezone.utc).isoformat()
def _parse_known_at(value: Any, symbol: str) -> datetime:
if not isinstance(value, str):
raise EventStudyError(f"known_at is required for {symbol}")
try:
parsed = datetime.fromisoformat(value.replace("Z", "+00:00"))
except ValueError as exc:
raise EventStudyError(f"invalid known_at for {symbol}") from exc
if parsed.tzinfo is None:
raise EventStudyError(f"known_at must include a timezone for {symbol}")
return parsed.astimezone(timezone.utc)
def assess_backtest_readiness(vintages: Sequence[Mapping[str, Any]], min_events: int = 12) -> dict[str, Any]:
if isinstance(min_events, bool) or min_events < 1:
raise EventStudyError("min_events must be positive")
@@ -63,13 +76,16 @@ def assess_backtest_readiness(vintages: Sequence[Mapping[str, Any]], min_events:
}
def _price_map(symbol: str, rows: Sequence[Mapping[str, Any]]) -> dict[date, float]:
def _price_map(symbol: str, rows: Sequence[Mapping[str, Any]], *, require_known_at: bool = False) -> dict[date, tuple[float, datetime | None]]:
if not rows:
raise EventStudyError(f"missing prices for {symbol}")
values: dict[date, float] = {}
values: dict[date, tuple[float, datetime | None]] = {}
for row in rows:
try:
trading_day = _parse_date(str(row["date"]))
session_date_value = row.get("session_date")
if session_date_value is None:
session_date_value = row["date"]
trading_day = _parse_date(str(session_date_value))
close = float(row["close"])
except (KeyError, TypeError, ValueError) as exc:
raise EventStudyError(f"invalid price row for {symbol}") from exc
@@ -77,11 +93,22 @@ def _price_map(symbol: str, rows: Sequence[Mapping[str, Any]]) -> dict[date, flo
raise EventStudyError(f"invalid close for {symbol}")
if trading_day in values:
raise EventStudyError(f"duplicate price date for {symbol}")
values[trading_day] = close
known_at = _parse_known_at(row.get("known_at"), symbol) if require_known_at else None
if known_at is not None:
timezone_name = row.get("market_timezone")
if not isinstance(timezone_name, str) or not timezone_name.strip():
raise EventStudyError(f"market_timezone is required for {symbol}")
try:
market_date = known_at.astimezone(ZoneInfo(timezone_name)).date()
except Exception as exc:
raise EventStudyError(f"invalid market_timezone for {symbol}") from exc
if market_date > trading_day:
raise EventStudyError(f"known_at is after session date for {symbol}")
values[trading_day] = (close, known_at)
return dict(sorted(values.items()))
def _window_return(series: dict[date, float], event_date: date, window: int, symbol: str, execution_lag_sessions: int) -> float:
def _window_return(series: dict[date, tuple[float, datetime | None]], event_date: date, window: int, symbol: str, execution_lag_sessions: int) -> float:
dates = list(series)
anchor_candidates = [index for index, trading_day in enumerate(dates) if trading_day >= event_date]
if not anchor_candidates:
@@ -96,7 +123,7 @@ def _window_return(series: dict[date, float], event_date: date, window: int, sym
end = anchor + window
if end >= len(dates):
raise EventStudyError(f"insufficient price history for {symbol} window {window}")
return series[dates[end]] / series[dates[anchor]] - 1.0
return series[dates[end]][0] / series[dates[anchor]][0] - 1.0
def run_event_study(
@@ -108,6 +135,7 @@ def run_event_study(
cost_bps: float = 0.0,
min_events: int = 12,
execution_lag_sessions: int = 1,
require_price_known_at: bool = False,
) -> dict[str, Any]:
"""Calculate weighted post-publication returns from point-in-time events."""
@@ -128,8 +156,13 @@ def run_event_study(
if not math.isfinite(cost_bps) or cost_bps < 0:
raise EventStudyError("cost_bps must be finite and non-negative")
normalized_prices = {str(symbol).upper(): _price_map(str(symbol).upper(), rows) for symbol, rows in prices.items()}
normalized_benchmark = _price_map("benchmark", benchmark_prices) if benchmark_prices is not None else None
if not isinstance(require_price_known_at, bool):
raise EventStudyError("require_price_known_at must be boolean")
normalized_prices = {
str(symbol).upper(): _price_map(str(symbol).upper(), rows, require_known_at=require_price_known_at)
for symbol, rows in prices.items()
}
normalized_benchmark = _price_map("benchmark", benchmark_prices, require_known_at=require_price_known_at) if benchmark_prices is not None else None
seen_event_ids: set[str] = set()
event_rows: list[dict[str, Any]] = []
for event in events:
@@ -189,4 +222,5 @@ def run_event_study(
"event_count": len(event_rows),
"windows": window_results,
"min_events": min_events,
"price_known_at_required": require_price_known_at,
}
+261 -37
View File
@@ -1,8 +1,8 @@
"""Frozen, replayable Tourism research runs.
A run either produces a deterministic event-study result from point-in-time
inputs or persists a blocked report explaining the exact missing gate. It never
falls back to revised vendor history.
Validated runs require point-in-time inputs. Explicit exploratory runs may use
revised vendor history, but their result is permanently labelled descriptive
only and does not satisfy the validated backtest gate.
"""
from __future__ import annotations
@@ -17,12 +17,15 @@ from pathlib import Path
from typing import Any, Mapping, Sequence
from .event_study import EventStudyError, _canonical_timestamp, assess_backtest_readiness, run_event_study
from .prices import PriceSnapshotStore, PriceSourceError
from .prices import PIT_ARCHIVE_CONTRACT, PriceSnapshotStore, PriceSourceError
from .tourism import compute_tourism_signal
from .vintages import VintageStore, VintageStoreError
RUN_SCHEMA_VERSION = 1
REPORT_HASH_ALGORITHM = "sha256-json-canonical-v1"
_RUN_ID_RE = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]{0,127}")
RESEARCH_MODES = {"validated", "exploratory"}
_OBSERVATION_RUNTIME_FIELDS = frozenset({"first_seen_at", "last_seen_at", "observation_count"})
class ResearchRunError(ValueError):
@@ -34,6 +37,20 @@ def _canonical_hash(payload: Mapping[str, Any]) -> str:
return hashlib.sha256(encoded).hexdigest()
def _report_hash(report: Mapping[str, Any]) -> str:
payload = copy.deepcopy(dict(report))
payload.pop("report_hash", None)
payload.pop("report_hash_algorithm", None)
return _canonical_hash(payload)
def _manifest_entry_hash(entry: Mapping[str, Any]) -> str:
payload = copy.deepcopy(dict(entry))
payload.pop("manifest_entry_hash", None)
payload.pop("manifest_entry_hash_algorithm", None)
return _canonical_hash(payload)
def _atomic_write(path: Path, payload: Mapping[str, Any]) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
temporary = path.with_name(f".{path.name}.tmp")
@@ -54,9 +71,13 @@ class ResearchRunStore:
return {"schema_version": RUN_SCHEMA_VERSION, "runs": {}}
try:
manifest = json.loads(self.manifest_path.read_text(encoding="utf-8"))
except (OSError, json.JSONDecodeError) as exc:
except (OSError, UnicodeError, json.JSONDecodeError) as exc:
raise ResearchRunError("research run manifest is unreadable") from exc
if manifest.get("schema_version") != RUN_SCHEMA_VERSION or not isinstance(manifest.get("runs"), dict):
if (
not isinstance(manifest, dict)
or manifest.get("schema_version") != RUN_SCHEMA_VERSION
or not isinstance(manifest.get("runs"), dict)
):
raise ResearchRunError("unsupported research run manifest schema")
return manifest
@@ -74,79 +95,235 @@ class ResearchRunStore:
raise FileNotFoundError(run_id)
try:
report = json.loads(path.read_text(encoding="utf-8"))
except (OSError, json.JSONDecodeError) as exc:
except (OSError, UnicodeError, json.JSONDecodeError) as exc:
raise ResearchRunError("research report is unreadable") from exc
if not isinstance(report, dict):
raise ResearchRunError("research report is invalid")
if report.get("run_id") != run_id or report.get("schema_version") != RUN_SCHEMA_VERSION:
raise ResearchRunError("research report identity mismatch")
declared_hash = report.get("report_hash")
if (
report.get("report_hash_algorithm") != REPORT_HASH_ALGORITHM
or not isinstance(declared_hash, str)
or _report_hash(report) != declared_hash
):
raise ResearchRunError("research report integrity hash mismatch")
manifest_entry = self.load_manifest().get("runs", {}).get(run_id)
declared_manifest_hash = manifest_entry.get("manifest_entry_hash") if isinstance(manifest_entry, dict) else None
if (
not isinstance(manifest_entry, dict)
or manifest_entry.get("run_id") != run_id
or manifest_entry.get("report_file") != path.name
or any(manifest_entry.get(field) != report.get(field) for field in ("status", "reason", "generated_at"))
or manifest_entry.get("report_hash_algorithm") != REPORT_HASH_ALGORITHM
or manifest_entry.get("report_hash") != declared_hash
or manifest_entry.get("manifest_entry_hash_algorithm") != REPORT_HASH_ALGORITHM
or not isinstance(declared_manifest_hash, str)
or _manifest_entry_hash(manifest_entry) != declared_manifest_hash
):
raise ResearchRunError("research report manifest integrity mismatch")
return report
def migrate_legacy(self) -> int:
"""Add integrity metadata to explicitly migrated pre-hash reports."""
manifest = self.load_manifest()
migrated = 0
for raw_run_id, raw_entry in manifest["runs"].items():
run_id = str(raw_run_id)
if not _RUN_ID_RE.fullmatch(run_id) or not isinstance(raw_entry, dict):
raise ResearchRunError("invalid research run manifest entry")
path = self._report_path(run_id)
if raw_entry.get("run_id") != run_id or raw_entry.get("report_file") != path.name:
raise ResearchRunError("research run manifest entry identity mismatch")
if not path.is_file():
raise FileNotFoundError(run_id)
try:
report = json.loads(path.read_text(encoding="utf-8"))
except (OSError, UnicodeError, json.JSONDecodeError) as exc:
raise ResearchRunError("research report is unreadable") from exc
if not isinstance(report, dict) or report.get("run_id") != run_id or report.get("schema_version") != RUN_SCHEMA_VERSION:
raise ResearchRunError("research report identity mismatch")
has_report_integrity = "report_hash" in report or "report_hash_algorithm" in report
has_manifest_integrity = "manifest_entry_hash" in raw_entry or "manifest_entry_hash_algorithm" in raw_entry
if has_manifest_integrity and not has_report_integrity:
raise ResearchRunError("research run integrity metadata is incomplete")
declared_report_hash = report.get("report_hash")
report_integrity_valid = (
report.get("report_hash_algorithm") == REPORT_HASH_ALGORITHM
and isinstance(declared_report_hash, str)
and _report_hash(report) == declared_report_hash
)
if has_report_integrity and not report_integrity_valid:
raise ResearchRunError("research run integrity metadata is invalid")
if not has_report_integrity or not has_manifest_integrity:
if any(raw_entry.get(field) != report.get(field) for field in ("status", "reason", "generated_at")):
raise ResearchRunError("research report manifest metadata mismatch")
if not has_report_integrity:
stored = copy.deepcopy(report)
stored["report_hash_algorithm"] = REPORT_HASH_ALGORITHM
stored["report_hash"] = _report_hash(stored)
declared_report_hash = stored["report_hash"]
_atomic_write(path, stored)
if not has_manifest_integrity:
migrated_entry = copy.deepcopy(raw_entry)
migrated_entry["report_hash_algorithm"] = REPORT_HASH_ALGORITHM
migrated_entry["report_hash"] = declared_report_hash
migrated_entry["manifest_entry_hash_algorithm"] = REPORT_HASH_ALGORITHM
migrated_entry["manifest_entry_hash"] = _manifest_entry_hash(migrated_entry)
manifest["runs"][run_id] = migrated_entry
migrated += 1
continue
declared_manifest_hash = raw_entry.get("manifest_entry_hash")
if (
not report_integrity_valid
or raw_entry.get("report_hash_algorithm") != REPORT_HASH_ALGORITHM
or raw_entry.get("report_hash") != declared_report_hash
or raw_entry.get("manifest_entry_hash_algorithm") != REPORT_HASH_ALGORITHM
or not isinstance(declared_manifest_hash, str)
or _manifest_entry_hash(raw_entry) != declared_manifest_hash
or any(raw_entry.get(field) != report.get(field) for field in ("status", "reason", "generated_at"))
):
raise ResearchRunError("research run integrity metadata is invalid")
if migrated:
_atomic_write(self.manifest_path, manifest)
return migrated
def _validated_manifest_entries(self) -> list[dict[str, Any]]:
manifest = self.load_manifest()
entries: list[dict[str, Any]] = []
for run_id, raw_entry in manifest["runs"].items():
if not _RUN_ID_RE.fullmatch(str(run_id)) or not isinstance(raw_entry, dict) or raw_entry.get("run_id") != run_id:
raise ResearchRunError("invalid research run manifest entry")
try:
self.load(run_id)
except FileNotFoundError as exc:
raise ResearchRunError("research run manifest entry report is missing") from exc
entries.append(raw_entry)
return entries
def persist(self, report: dict[str, Any]) -> dict[str, Any]:
run_id = str(report.get("run_id", ""))
path = self._report_path(run_id)
manifest = self.load_manifest()
existing = manifest["runs"].get(run_id)
if existing:
stored = self.load(run_id)
if stored != report:
raise ResearchRunError("research run id already contains a different report")
return stored
stored = copy.deepcopy(report)
stored["report_hash_algorithm"] = REPORT_HASH_ALGORITHM
stored["report_hash"] = _report_hash(stored)
manifest = self.load_manifest()
self._validated_manifest_entries()
if run_id in manifest["runs"]:
if not isinstance(manifest["runs"][run_id], dict):
raise ResearchRunError("invalid research run manifest entry")
existing_report = self.load(run_id)
if existing_report != stored:
raise ResearchRunError("research run id already contains a different report")
return existing_report
_atomic_write(path, stored)
manifest["runs"][run_id] = {
manifest_entry = {
"run_id": run_id,
"status": stored.get("status"),
"reason": stored.get("reason"),
"generated_at": stored.get("generated_at"),
"report_file": path.name,
"report_hash_algorithm": REPORT_HASH_ALGORITHM,
"report_hash": stored["report_hash"],
}
manifest_entry["manifest_entry_hash_algorithm"] = REPORT_HASH_ALGORITHM
manifest_entry["manifest_entry_hash"] = _manifest_entry_hash(manifest_entry)
manifest["runs"][run_id] = manifest_entry
_atomic_write(self.manifest_path, manifest)
return stored
def latest(self) -> dict[str, Any]:
entries = list(self.load_manifest().get("runs", {}).values())
entries = self._validated_manifest_entries()
if not entries:
raise FileNotFoundError("no research runs")
latest = max(entries, key=lambda item: (str(item.get("generated_at", "")), str(item.get("run_id", ""))))
return self.load(str(latest["run_id"]))
def list_runs(self) -> list[dict[str, Any]]:
entries = list(self.load_manifest().get("runs", {}).values())
entries = self._validated_manifest_entries()
return sorted(entries, key=lambda item: (str(item.get("generated_at", "")), str(item.get("run_id", ""))), reverse=True)
def _validate_config(windows: Sequence[int], cost_bps: float, min_events: int, execution_lag_sessions: int) -> tuple[list[int], float, int, int]:
if not windows or any(isinstance(window, bool) or int(window) != window or int(window) <= 0 for window in windows):
raise ResearchRunError("windows must contain positive integers")
def _parse_config_integer(value: Any, field: str, minimum: int) -> int:
if isinstance(value, bool) or not isinstance(value, (int, float)):
raise ResearchRunError(f"{field} must be an integer")
try:
parsed = int(value)
numeric = float(value)
except (OverflowError, TypeError, ValueError) as exc:
raise ResearchRunError(f"{field} must be an integer") from exc
if not math.isfinite(numeric) or parsed != value or parsed < minimum:
qualifier = "positive" if minimum > 0 else "non-negative"
raise ResearchRunError(f"{field} must be a {qualifier} integer")
return parsed
def _validate_config(windows: Sequence[int], cost_bps: float, min_events: int, execution_lag_sessions: int) -> tuple[list[int], float, int, int]:
if not isinstance(windows, (list, tuple)) or not windows:
raise ResearchRunError("windows must contain positive integers")
parsed_windows = [_parse_config_integer(window, "windows", 1) for window in windows]
try:
if isinstance(cost_bps, bool):
raise TypeError
parsed_cost = float(cost_bps)
except (TypeError, ValueError) as exc:
except (OverflowError, TypeError, ValueError) as exc:
raise ResearchRunError("cost_bps must be finite and non-negative") from exc
if not math.isfinite(parsed_cost) or parsed_cost < 0:
raise ResearchRunError("cost_bps must be finite and non-negative")
if isinstance(min_events, bool) or int(min_events) != min_events or int(min_events) < 1:
raise ResearchRunError("min_events must be positive")
if isinstance(execution_lag_sessions, bool) or int(execution_lag_sessions) != execution_lag_sessions or int(execution_lag_sessions) < 0:
raise ResearchRunError("execution_lag_sessions must be a non-negative integer")
return [int(window) for window in windows], parsed_cost, int(min_events), int(execution_lag_sessions)
parsed_min_events = _parse_config_integer(min_events, "min_events", 1)
parsed_execution_lag = _parse_config_integer(execution_lag_sessions, "execution_lag_sessions", 0)
return parsed_windows, parsed_cost, parsed_min_events, parsed_execution_lag
def _price_gate(price_entry: Mapping[str, Any] | None) -> dict[str, Any]:
def _validate_mode(mode: str) -> str:
if not isinstance(mode, str) or mode not in RESEARCH_MODES:
raise ResearchRunError(f"mode must be one of: {', '.join(sorted(RESEARCH_MODES))}")
return mode
def _price_gate(price_entry: Mapping[str, Any] | None, mode: str = "validated") -> dict[str, Any]:
mode = _validate_mode(mode)
if not price_entry:
return {"status": "blocked", "reason": "price_snapshot_missing", "snapshot_count": 0}
if price_entry.get("point_in_time") is not True:
return {
"status": "blocked",
"status": "descriptive_only" if mode == "exploratory" else "blocked",
"reason": "price_series_not_point_in_time",
"snapshot_id": price_entry.get("snapshot_id"),
"quality": price_entry.get("quality"),
"point_in_time": False,
"validated": False,
}
if price_entry.get("quality") != "point_in_time_archive" or price_entry.get("archive_contract") != PIT_ARCHIVE_CONTRACT:
return {
"status": "descriptive_only" if mode == "exploratory" else "blocked",
"reason": "price_archive_contract_missing",
"snapshot_id": price_entry.get("snapshot_id"),
"quality": price_entry.get("quality"),
"archive_contract": price_entry.get("archive_contract"),
"point_in_time": True,
"validated": False,
}
if mode == "exploratory":
return {
"status": "descriptive_only",
"reason": "exploratory_mode_non_validated",
"snapshot_id": price_entry.get("snapshot_id"),
"quality": price_entry.get("quality"),
"archive_contract": price_entry.get("archive_contract"),
"provider_release_id": price_entry.get("provider_release_id"),
"point_in_time": True,
"validated": False,
}
return {
"status": "ready",
"reason": None,
"snapshot_id": price_entry.get("snapshot_id"),
"quality": price_entry.get("quality"),
"archive_contract": price_entry.get("archive_contract"),
"provider_release_id": price_entry.get("provider_release_id"),
"point_in_time": True,
"validated": True,
}
@@ -164,11 +341,25 @@ def _select_independent_vintages(entries: Sequence[Mapping[str, Any]]) -> list[d
entry = dict(raw_entry)
key = _revision_key(entry)
current = selected.get(key)
candidate_rank = (str(entry.get("first_seen_at", "")), str(entry.get("last_seen_at", "")), str(entry.get("vintage_id", "")))
current_rank = (str(current.get("first_seen_at", "")), str(current.get("last_seen_at", "")), str(current.get("vintage_id", ""))) if current else ("", "", "")
candidate_rank = (
_canonical_timestamp(str(entry.get("first_seen_at") or "")),
_canonical_timestamp(str(entry.get("last_seen_at") or "")),
str(entry.get("vintage_id", "")),
)
current_rank = (
_canonical_timestamp(str(current.get("first_seen_at") or "")),
_canonical_timestamp(str(current.get("last_seen_at") or "")),
str(current.get("vintage_id", "")),
) if current else ("", "", "")
if current is None or candidate_rank > current_rank:
selected[key] = entry
return sorted(selected.values(), key=lambda item: (str(item.get("published_at", "")), str(item.get("vintage_id", ""))))
return sorted(
selected.values(),
key=lambda item: (
_canonical_timestamp(str(item.get("published_at") or "")),
str(item.get("vintage_id", "")),
),
)
def _series_rows(series: Mapping[str, Any], price_field: str, symbol: str) -> list[dict[str, Any]]:
@@ -179,7 +370,15 @@ def _series_rows(series: Mapping[str, Any], price_field: str, symbol: str) -> li
for bar in bars:
if not isinstance(bar, dict) or price_field not in bar:
raise ResearchRunError(f"price field {price_field} missing for {symbol}")
rows.append({"date": bar.get("date"), "close": bar.get(price_field)})
session_date = bar.get("session_date", bar.get("date"))
row = {"date": session_date, "close": bar.get(price_field)}
if "session_date" in bar:
row["session_date"] = session_date
if "known_at" in bar:
row["known_at"] = bar.get("known_at")
if "timezone" in series:
row["market_timezone"] = series.get("timezone")
rows.append(row)
return rows
@@ -192,13 +391,15 @@ def run_tourism_research(
windows: Sequence[int] = (1, 3, 5, 20),
cost_bps: float = 20.0,
execution_lag_sessions: int = 1,
mode: str = "validated",
) -> dict[str, Any]:
mode = _validate_mode(mode)
windows, cost_bps, min_events, execution_lag_sessions = _validate_config(windows, cost_bps, min_events, execution_lag_sessions)
try:
vintages = _select_independent_vintages(vintage_store.list_vintages())
price_entry = price_store.latest_snapshot_entry()
except (VintageStoreError, PriceSourceError) as exc:
raise ResearchRunError(str(exc)) from exc
raise ResearchRunError(f"research input integrity validation failed: {exc}") from exc
vintage_gate = assess_backtest_readiness(vintages, min_events=min_events)
validated_vintage_snapshots: dict[str, dict[str, Any]] = {}
try:
@@ -219,9 +420,11 @@ def run_tourism_research(
**price_entry,
"point_in_time": price_source.get("point_in_time"),
"quality": price_source.get("quality"),
"archive_contract": price_source.get("archive_contract"),
"provider_release_id": price_source.get("provider_release_id"),
"normalized_snapshot_hash": price_source.get("normalized_snapshot_hash"),
}
price_gate = _price_gate(price_gate_entry)
price_gate = _price_gate(price_gate_entry, mode)
input_vintages = [
{
"vintage_id": entry.get("vintage_id"),
@@ -229,17 +432,28 @@ def run_tourism_research(
"as_of": entry.get("as_of"),
"published_at": entry.get("published_at"),
"raw_payload_hash": entry.get("raw_payload_hash"),
"normalized_snapshot_hash": entry.get("normalized_snapshot_hash"),
"normalized_hash_algorithm": entry.get("normalized_hash_algorithm"),
"parser_version": entry.get("parser_version"),
"revision_status": entry.get("revision_status"),
}
for entry in vintages
]
input_price = copy.deepcopy(price_gate_entry) if price_gate_entry else None
input_price = (
{
key: copy.deepcopy(value)
for key, value in price_gate_entry.items()
if key not in _OBSERVATION_RUNTIME_FIELDS
}
if price_gate_entry
else None
)
config = {
"min_events": min_events,
"windows": windows,
"cost_bps": cost_bps,
"execution_lag_sessions": execution_lag_sessions,
"mode": mode,
}
input_fingerprint = _canonical_hash({"theme": "tourism", "config": config, "vintages": input_vintages, "price_snapshot": input_price})
run_id = f"tourism-run-{input_fingerprint[:16]}"
@@ -255,6 +469,8 @@ def run_tourism_research(
"status": "blocked",
"reason": None,
"generated_at": generated_at,
"research_mode": mode,
"result_scope": "blocked",
"config": config,
"gates": {"vintages": vintage_gate, "prices": price_gate},
"inputs": {"vintages": input_vintages, "price_snapshot": input_price},
@@ -262,7 +478,7 @@ def run_tourism_research(
if vintage_gate["status"] != "ready":
report["reason"] = vintage_gate["reason"]
return run_store.persist(report)
if price_gate["status"] != "ready":
if price_gate["status"] == "blocked":
report["reason"] = price_gate["reason"]
return run_store.persist(report)
if not price_entry or price_snapshot is None:
@@ -294,13 +510,21 @@ def run_tourism_research(
cost_bps=cost_bps,
min_events=min_events,
execution_lag_sessions=execution_lag_sessions,
require_price_known_at=mode == "validated",
)
except (FileNotFoundError, VintageStoreError, EventStudyError, ResearchRunError, KeyError, TypeError, ValueError) as exc:
report["reason"] = "research_inputs_invalid"
report["error"] = str(exc)
return run_store.persist(report)
report["status"] = "ready"
report["status"] = "descriptive_only" if mode == "exploratory" else "ready"
report["reason"] = None
report["result_scope"] = "validated_pit_event_study" if mode == "validated" else "non_pit_descriptive_only"
if mode == "exploratory":
report["limitations"] = ["This result is descriptive only and must not be used as validated backtest evidence."]
if price_source.get("point_in_time") is not True:
report["limitations"].insert(0, "Historical price data may be revised vendor history and is not point-in-time validated.")
else:
report["limitations"].insert(0, "Point-in-time-capable inputs are intentionally not promoted by exploratory mode.")
report["result"] = result
report["input_summary"] = {
"event_count": len(events),
+10 -3
View File
@@ -42,10 +42,12 @@ def _data_quality(snapshot: dict[str, Any], observations: list[dict[str, Any]])
def compute_tourism_signal(snapshot: dict[str, Any]) -> dict[str, Any]:
"""Compute a replayable Tourism Pulse signal from a frozen snapshot."""
observations = list(snapshot.get("observations", []))
if not observations:
observations = snapshot.get("observations", [])
if not isinstance(observations, list) or not observations:
raise ValueError("tourism snapshot must contain observations")
for observation in observations:
if not isinstance(observation, dict):
raise ValueError("tourism observation must be an object")
_validate_observation(observation)
standardized = []
@@ -58,7 +60,12 @@ def compute_tourism_signal(snapshot: dict[str, Any]) -> dict[str, Any]:
theme_surprise = round(fmean(standardized), 8)
signal_rows = []
for exposure in snapshot.get("exposures", []):
exposures = snapshot.get("exposures", [])
if not isinstance(exposures, list):
raise ValueError("tourism snapshot exposures must be a list")
for exposure in exposures:
if not isinstance(exposure, dict):
raise ValueError("tourism exposure must be an object")
symbol = str(exposure.get("symbol", "")).strip().upper()
coefficient = float(exposure.get("coefficient", 0))
confidence = float(exposure.get("confidence", 1.0))
+9 -3
View File
@@ -90,7 +90,7 @@ class VintageStore:
return {"schema_version": MANIFEST_SCHEMA_VERSION, "vintages": {}}
try:
payload = json.loads(self.manifest_path.read_text(encoding="utf-8"))
except (OSError, json.JSONDecodeError) as exc:
except (OSError, UnicodeError, json.JSONDecodeError) as exc:
raise VintageStoreError("vintage manifest is unreadable") from exc
if not isinstance(payload, dict) or payload.get("schema_version") != MANIFEST_SCHEMA_VERSION:
raise VintageStoreError("unsupported vintage manifest schema")
@@ -174,8 +174,10 @@ class VintageStore:
raise FileNotFoundError(vintage_id)
try:
snapshot = json.loads(snapshot_path.read_text(encoding="utf-8"))
except (OSError, json.JSONDecodeError) as exc:
except (OSError, UnicodeError, json.JSONDecodeError) as exc:
raise VintageStoreError("vintage snapshot is unreadable") from exc
if not isinstance(snapshot, dict):
raise VintageStoreError("vintage snapshot is invalid")
source = snapshot.get("source")
if not isinstance(source, dict) or source.get("vintage_id") != vintage_id:
raise VintageStoreError("vintage snapshot identity mismatch")
@@ -186,7 +188,11 @@ class VintageStore:
raw_path = (self.raw_dir / raw_filename).resolve()
if raw_path.parent != self.raw_dir.resolve() or not raw_path.is_file():
raise VintageStoreError("vintage raw payload is missing")
if hashlib.sha256(raw_path.read_bytes()).hexdigest() != source.get("raw_payload_hash"):
try:
raw_payload_hash = hashlib.sha256(raw_path.read_bytes()).hexdigest()
except OSError as exc:
raise VintageStoreError("vintage raw payload is unreadable") from exc
if raw_payload_hash != source.get("raw_payload_hash"):
raise VintageStoreError("vintage raw payload hash mismatch")
manifest_entry = self.load_manifest().get("vintages", {}).get(vintage_id)
if not isinstance(manifest_entry, dict):