Files
Jyotisha/scripts/market_astrology_research_pack.py
ClaudeandClaude Opus 5.5 6a57faacdb feat(consult): run the astrologer's upstream skill in full (BUG-1696, BUG-1697, BUG-1698)
- root SKILL.md is her upstream file (body byte-identical to the 5fb8379c mirror; description quoted so YAML parses and Mastra can load the skill)
- chat binds the whole SKILL.md plus references/product_runtime_contract.md (safety-only) instead of a ~477-character excerpt
- every turn carries her full strict-workflow-router (synced to upstream) and the domain's event-judgment file; product lists follow as an extra layer
- import her 10 sub-skills, family router, interpretation status contract, technique ontology and the 54 files her method names
- tests/test_upstream_skill_parity.py (in the quick gate) fails whenever her skill and ours drift
- 18 frontend guards that locked the excerpt design updated with 原值/新值/原因 notes

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DbBXoyn7Hj3LCW3BUs5bZ8
2026-11-07 14:02:26 +08:00

472 lines
18 KiB
Python

#!/usr/bin/env python3
"""Market / financial astrology research pack.
This is a research scaffold, not a market prediction engine.
It keeps price data, astro signals, and validation hooks in one auditable packet.
"""
from __future__ import annotations
try: # reached as a script: this directory is on the path, the root is not
import _script_root # noqa: F401
except ModuleNotFoundError: # pragma: no cover - reached as scripts.x instead
try:
from scripts import _script_root # noqa: F401
except ModuleNotFoundError:
pass
import argparse
import json
from pathlib import Path
from typing import Any
SCHEMA = "jyotish.market_astrology_research_pack.v1"
DEFAULT_FEATURES = [
"transit_jupiter",
"transit_saturn",
"transit_rahuketu",
"retrograde_flags",
"moon_phase",
"d2_wealth_support",
"d11_gains_support",
"dasha_activation",
"shadbala_support",
"ashtakavarga_support",
]
DEFAULT_SIGNAL_WEIGHTS = {
"transit_jupiter": 2.0,
"transit_saturn": 1.5,
"transit_rahuketu": 1.2,
"retrograde_flags": 0.5,
"moon_phase": 0.4,
"d2_wealth_support": 1.8,
"d11_gains_support": 1.8,
"dasha_activation": 2.2,
"shadbala_support": 1.4,
"ashtakavarga_support": 1.4,
}
def _as_dict(value: Any) -> dict[str, Any]:
return value if isinstance(value, dict) else {}
def _normalize_list(value: Any) -> list[Any]:
return value if isinstance(value, list) else []
def _section(name: str, value: Any, source_path: str) -> dict[str, Any]:
present = bool(value)
return {
"name": name,
"status": "available" if present else "blocked",
"source_path": source_path,
"reason": None if present else f"{name}_missing",
}
def _normalize_signals(signals: list[dict[str, Any]] | None) -> list[dict[str, Any]]:
normalized: list[dict[str, Any]] = []
for item in signals or []:
if not isinstance(item, dict):
continue
theme = str(item.get("theme") or "").strip()
claim = str(item.get("claim") or "").strip()
if not theme or not claim:
continue
normalized.append(
{
"theme": theme,
"claim": claim,
"timeframe": str(item.get("timeframe") or "unspecified"),
"source": str(item.get("source") or "market_astrology_research_pack"),
}
)
return normalized
def _normalize_prices(price_series: list[dict[str, Any]] | None) -> list[dict[str, Any]]:
normalized: list[dict[str, Any]] = []
for row in price_series or []:
if not isinstance(row, dict):
continue
date = str(row.get("date") or "").strip()
close = row.get("close")
if not date or close is None:
continue
normalized.append(
{
"date": date,
"open": row.get("open"),
"high": row.get("high"),
"low": row.get("low"),
"close": close,
"volume": row.get("volume"),
}
)
return normalized
def _signal_score(signal: dict[str, Any]) -> float:
feature = str(signal.get("feature") or signal.get("theme") or "").strip()
weight = float(DEFAULT_SIGNAL_WEIGHTS.get(feature, 1.0))
strength = str(signal.get("strength") or signal.get("score") or "1").strip()
try:
strength_value = float(strength)
except ValueError:
strength_value = 1.0
return round(weight * strength_value, 3)
def _rank_signals(signals: list[dict[str, Any]]) -> list[dict[str, Any]]:
ranked: list[dict[str, Any]] = []
for index, signal in enumerate(signals, start=1):
item = dict(signal)
item["rank_score"] = _signal_score(signal)
item["rank"] = index
ranked.append(item)
ranked.sort(key=lambda item: (-float(item.get("rank_score") or 0.0), str(item.get("theme") or "")))
for index, item in enumerate(ranked, start=1):
item["rank"] = index
return ranked
def _walk_forward_backtest(
price_series: list[dict[str, Any]],
labels: list[dict[str, Any]],
signals: list[dict[str, Any]],
) -> dict[str, Any]:
label_lookup = {
str(row.get("date")): str(row.get("label") or row.get("outcome") or "")
for row in labels
if isinstance(row, dict) and row.get("date")
}
total = len(price_series)
if total == 0 or not label_lookup:
return {
"status": "blocked",
"reason": "price_series_or_labels_missing",
"windows": [],
"metrics": {"sample_count": 0, "hit_count": 0, "hit_rate": None},
}
windows: list[dict[str, Any]] = []
hit_count = 0
signal_bias = "up" if sum(item["rank_score"] for item in _rank_signals(signals)[:3]) >= 0 else "down"
for idx, row in enumerate(price_series, start=1):
date = str(row.get("date"))
actual = label_lookup.get(date)
if not actual:
continue
close = row.get("close")
open_price = row.get("open")
movement = None
if isinstance(open_price, (int, float)) and isinstance(close, (int, float)):
movement = "up" if close >= open_price else "down"
predicted = signal_bias
hit = bool(movement and predicted == movement and actual in {predicted, "neutral"})
if hit:
hit_count += 1
windows.append(
{
"index": idx,
"date": date,
"predicted": predicted,
"actual": actual,
"movement": movement,
"hit": hit,
}
)
sample_count = len(windows)
return {
"status": "validated" if sample_count else "blocked",
"windows": windows,
"metrics": {
"sample_count": sample_count,
"hit_count": hit_count,
"hit_rate": round(hit_count / sample_count, 3) if sample_count else None,
},
}
def build_market_astrology_research_pack(
*,
market_profile: dict[str, Any] | None,
astro_signals: list[dict[str, Any]] | None,
price_series: list[dict[str, Any]] | None,
labels: list[dict[str, Any]] | None = None,
benchmark: dict[str, Any] | None = None,
case_notes: dict[str, Any] | None = None,
) -> dict[str, Any]:
"""Build a compact, auditable market-astrology research packet."""
market_profile = _as_dict(market_profile)
signals = _normalize_signals(astro_signals)
prices = _normalize_prices(price_series)
labels = _normalize_list(labels)
benchmark = _as_dict(benchmark)
case_notes = _as_dict(case_notes)
ranked_signals = _rank_signals(signals)
backtest = _walk_forward_backtest(prices, labels, ranked_signals)
try:
from scripts.market_astrology_feature_store import build_market_astrology_feature_store
except ImportError: # pragma: no cover
from market_astrology_feature_store import build_market_astrology_feature_store
feature_store = build_market_astrology_feature_store(
market_profile=market_profile,
price_series=prices,
astro_signals=ranked_signals,
labels=labels,
benchmark=benchmark,
)
try:
from scripts.top_reader_closure_review import build_top_reader_closure_review
except ImportError: # pragma: no cover
from top_reader_closure_review import build_top_reader_closure_review
top_reader_gap_review = build_top_reader_closure_review(
market_profile=market_profile,
signals=ranked_signals,
prices=prices,
labels=labels,
benchmark=benchmark,
backtest=backtest,
)
sections = {
"market_profile": _section("market_profile", market_profile, "market.profile"),
"astro_signals": _section("astro_signals", signals, "market.astro_signals"),
"price_series": _section("price_series", prices, "market.price_series"),
"labels": _section("labels", labels, "market.labels"),
"benchmark": _section("benchmark", benchmark, "market.benchmark"),
}
missing = [name for name, section in sections.items() if section["status"] == "blocked"]
status = "ready_for_backtest" if not missing else ("partial" if len(missing) < len(sections) else "blocked")
return {
"schema": SCHEMA,
"system": "market_astrology_research",
"status": status,
"market_profile": {
"asset_class": str(market_profile.get("asset_class") or "unknown"),
"symbol": str(market_profile.get("symbol") or market_profile.get("name") or "unknown"),
"exchange": str(market_profile.get("exchange") or "unspecified"),
"timeframe": str(market_profile.get("timeframe") or "unspecified"),
"benchmark_symbol": str(market_profile.get("benchmark_symbol") or benchmark.get("symbol") or ""),
},
"required_sections": ["market_profile", "astro_signals", "price_series", "labels", "benchmark"],
"sections": sections,
"astro_signals": signals,
"ranked_signals": ranked_signals,
"price_series": prices,
"labels": labels,
"feature_store": feature_store,
"feature_blueprint": list(DEFAULT_FEATURES),
"backtest": backtest,
"top_reader_gap_review": top_reader_gap_review,
"research_steps": [
"data_ingestion",
"astro_feature_extraction",
"label_alignment",
"walk_forward_backtest",
"signal_ranking",
],
"benchmark": benchmark,
"case_notes": case_notes,
"missing_sections": missing,
"audit": {
"technique_audit": [
{"technique": "Market data ingestion", "status": "used" if prices else "blocked"},
{"technique": "Astro signal blueprint", "status": "used" if signals else "blocked"},
{"technique": "Label alignment", "status": "used" if labels else "blocked"},
{"technique": "Signal ranking", "status": "used" if ranked_signals else "blocked"},
{"technique": "Walk-forward validation", "status": backtest["status"], "reason": backtest.get("reason")},
{"technique": "Market feature store", "status": feature_store["status"]},
{"technique": "Top reader gap review", "status": top_reader_gap_review["status"]},
],
"claim_boundary": "This packet supports research and backtesting only; it does not claim market prediction truth.",
},
}
def build_market_astrology_scan_bridge(
payload: dict[str, Any],
*,
scan_fn: Any | None = None,
) -> dict[str, Any]:
"""Bridge market research inputs into the existing time-sensitivity scanner."""
scan_fn = scan_fn or _default_scan_fn
profile = _as_dict(payload.get("market_profile"))
astro_signals = _normalize_signals(payload.get("astro_signals"))
labels = _normalize_list(payload.get("labels"))
scan_input = {
"year": payload.get("year"),
"month": payload.get("month"),
"day": payload.get("day"),
"hour": payload.get("hour"),
"minute": payload.get("minute"),
"lat": payload.get("lat"),
"lon": payload.get("lon"),
"tz": payload.get("tz"),
}
scan = scan_fn(scan_input, uncertainty_minutes=int(payload.get("uncertainty_minutes") or 30), step_minutes=int(payload.get("step_minutes") or 1))
pack = build_market_astrology_research_pack(
market_profile=profile,
astro_signals=astro_signals,
price_series=_normalize_prices(payload.get("price_series")),
labels=labels,
benchmark=_as_dict(payload.get("benchmark")),
case_notes=_as_dict(payload.get("case_notes")),
)
pack["scan_bridge"] = {
"status": "used" if scan.get("status") else "blocked",
"scan_scope": scan.get("scope"),
"candidate_count": scan.get("candidate_count"),
"supported_vargas": scan.get("supported_vargas") or [],
"unavailable_vargas": scan.get("unavailable_vargas") or [],
"boundary": scan.get("boundary"),
}
pack["time_sensitivity_scan"] = scan
pack["audit"]["technique_audit"].append(
{
"technique": "Candidate time sensitivity scan",
"status": scan.get("status", "blocked"),
"reason": scan.get("boundary"),
}
)
return pack
def build_market_western_kp_research_pack(
*,
market_profile: dict[str, Any] | None,
astro_signals: list[dict[str, Any]] | None,
price_series: list[dict[str, Any]] | None,
labels: list[dict[str, Any]] | None = None,
benchmark: dict[str, Any] | None = None,
case_notes: dict[str, Any] | None = None,
route_packet: dict[str, Any] | None = None,
natal: dict[str, Any] | None = None,
timing_techniques: dict[str, Any] | None = None,
kp_probe: dict[str, Any] | None = None,
kp_support: dict[str, Any] | None = None,
real_case_support: dict[str, Any] | None = None,
) -> dict[str, Any]:
"""Build a merged market + western + KP research packet."""
try:
from scripts.western_evidence_packet import build_western_kp_combined_packet
except ImportError: # pragma: no cover
from western_evidence_packet import build_western_kp_combined_packet
pack = build_market_astrology_research_pack(
market_profile=market_profile,
astro_signals=astro_signals,
price_series=price_series,
labels=labels,
benchmark=benchmark,
case_notes=case_notes,
)
western_packet = build_western_kp_combined_packet(
route_packet=route_packet or {"question_type": "market_research", "primary_theme": "wealth"},
natal=natal,
timing_techniques=timing_techniques,
signals=astro_signals,
kp_probe=kp_probe,
kp_support=kp_support,
real_case_support=real_case_support,
)
pack["merged_surfaces"] = {
"status": "used" if western_packet else "blocked",
"western_kp_status": western_packet.get("status"),
"kp_bridge_status": (western_packet.get("kp_bridge") or {}).get("status"),
"signal_count": len(pack.get("ranked_signals") or []),
}
pack["western_kp_packet"] = western_packet
pack["audit"]["technique_audit"].append(
{
"technique": "Western + KP combined packet",
"status": western_packet.get("status", "blocked"),
"reason": (western_packet.get("kp_bridge") or {}).get("claim_boundary"),
}
)
return pack
def _default_scan_fn(scan_input: dict[str, Any], *, uncertainty_minutes: int, step_minutes: int) -> dict[str, Any]:
try:
from scripts.candidate_time_sensitivity_scan import scan_candidate_times
except ImportError: # pragma: no cover
from candidate_time_sensitivity_scan import scan_candidate_times
return scan_candidate_times(scan_input, uncertainty_minutes=uncertainty_minutes, step_minutes=step_minutes)
def _load_json(path: Path) -> Any:
return json.loads(path.read_text(encoding="utf-8"))
def _load_market_rows(source: str | Path) -> list[dict[str, Any]]:
try:
from scripts.market_astrology_source_connector import fetch_market_labels
except ImportError: # pragma: no cover
from market_astrology_source_connector import fetch_market_labels
return fetch_market_labels(str(source))
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(description="Build a market astrology research pack")
parser.add_argument("--market-profile", type=Path, required=True)
parser.add_argument("--astro-signals", type=Path, required=True)
parser.add_argument("--price-series", required=True, help="Path or URL to CSV/JSON price data")
parser.add_argument("--labels", help="Path or URL to CSV/JSON labels")
parser.add_argument("--benchmark", type=Path)
parser.add_argument("--case-notes", type=Path)
parser.add_argument("--birth-year", type=int)
parser.add_argument("--birth-month", type=int)
parser.add_argument("--birth-day", type=int)
parser.add_argument("--birth-hour", type=int)
parser.add_argument("--birth-minute", type=int)
parser.add_argument("--lat", type=float)
parser.add_argument("--lon", type=float)
parser.add_argument("--tz", type=float)
args = parser.parse_args(argv)
payload = {
"market_profile": _load_json(args.market_profile),
"astro_signals": _load_json(args.astro_signals),
"price_series": _load_market_rows(args.price_series),
"labels": _load_market_rows(args.labels) if args.labels else None,
"benchmark": _load_json(args.benchmark) if args.benchmark else None,
"case_notes": _load_json(args.case_notes) if args.case_notes else None,
"year": args.birth_year,
"month": args.birth_month,
"day": args.birth_day,
"hour": args.birth_hour,
"minute": args.birth_minute,
"lat": args.lat,
"lon": args.lon,
"tz": args.tz,
}
if all(value is not None for value in (args.birth_year, args.birth_month, args.birth_day, args.birth_hour, args.birth_minute, args.lat, args.lon, args.tz)):
pack = build_market_astrology_scan_bridge(payload)
else:
pack = build_market_astrology_research_pack(
market_profile=payload["market_profile"],
astro_signals=payload["astro_signals"],
price_series=payload["price_series"],
labels=payload["labels"],
benchmark=payload["benchmark"],
case_notes=payload["case_notes"],
)
print(json.dumps(pack, ensure_ascii=False, indent=2, sort_keys=True))
return 0
if __name__ == "__main__":
raise SystemExit(main())