diff --git a/README.md b/README.md index d9c5f70..e99c455 100644 --- a/README.md +++ b/README.md @@ -137,6 +137,7 @@ No performance claims yet. The scaffold proves the invariants: | BeliefBench runner and baselines | `tests/test_beliefbench.py` | | GDELT and RSS map to observations | `tests/test_gdelt.py`, `tests/test_rss.py` | | Retries, dead letters, and replay | `tests/test_scheduler.py` | +| Persona evolution is seeded and held-out gated | `tests/test_persona_evolution.py` | | Quality checks catch duplicate, future, and stale data | `tests/test_quality.py` | | Predictions are immutable and settle once | `tests/test_ledger.py` | | RSI stays bounded; MACD / Bollinger / OBV behave | `tests/test_indicators.py` | diff --git a/core/janus/persona/evolution.py b/core/janus/persona/evolution.py new file mode 100644 index 0000000..9a6e099 --- /dev/null +++ b/core/janus/persona/evolution.py @@ -0,0 +1,253 @@ +from __future__ import annotations + +import hashlib +import json +import math +import random +from dataclasses import asdict, dataclass +from datetime import datetime +from typing import Any, Optional, Sequence + +from ..forecast.calibration import brier_score +from ..memory.models import Persona +from .profile import DIMENSIONS +from .weighting import PersonaPolicy, build_persona + + +def _clip(value: float) -> float: + return max(0.0, min(1.0, value)) + + +def _sigmoid(value: float) -> float: + value = max(-50.0, min(50.0, value)) + return 1.0 / (1.0 + math.exp(-value)) + + +@dataclass(frozen=True) +class EvolutionScenario: + id: str + as_of: datetime + resolved_at: datetime + outcome: float + features: dict[str, float] + + def __post_init__(self) -> None: + for name, stamp in (("as_of", self.as_of), ("resolved_at", self.resolved_at)): + if stamp.tzinfo is None or stamp.tzinfo.utcoffset(stamp) is None: + raise ValueError(f"{name} must be timezone-aware") + if self.resolved_at <= self.as_of: + raise ValueError("resolved_at must be after as_of") + if self.outcome not in (0.0, 1.0): + raise ValueError("outcome must be 0 or 1") + + +@dataclass(frozen=True) +class Fitness: + n: int + brier: float + hit_rate: float + + def to_dict(self) -> dict[str, Any]: + return asdict(self) + + +@dataclass(frozen=True) +class Generation: + index: int + best_brier: float + mean_brier: float + best_profile: dict[str, float] + + +@dataclass(frozen=True) +class EvolutionResult: + seed: int + generations: tuple[Generation, ...] + train: Fitness + validation: Fitness + baseline_validation: Fitness + promoted: bool + reason: str + persona: Persona + train_ids: tuple[str, ...] + validation_ids: tuple[str, ...] + + def to_dict(self) -> dict[str, Any]: + return { + "seed": self.seed, + "generations": [asdict(generation) for generation in self.generations], + "train": self.train.to_dict(), + "validation": self.validation.to_dict(), + "baseline_validation": self.baseline_validation.to_dict(), + "promoted": self.promoted, + "reason": self.reason, + "persona": self.persona.model_dump(mode="json"), + "train_ids": list(self.train_ids), + "validation_ids": list(self.validation_ids), + } + + +def persona_probability(features: dict[str, float], profile: dict[str, float]) -> float: + weights = PersonaPolicy(profile).feature_weights() + rsi_value = float(features.get("rsi_14", 50.0)) + trend = _clip(float(features.get("return_21d", features.get("trend", 0.0)))) + breadth = _clip(float(features.get("breadth", 0.5))) + score = ( + 0.4 * ((rsi_value - 50.0) / 50.0) * weights.get("rsi_14", 1.0) + + 0.4 * trend * weights.get("return_21d", 1.0) + + 0.2 * (2.0 * (breadth - 0.5)) * weights.get("breadth", 1.0) + ) + for key in ("valuation", "quality", "macro", "liquidity"): + score += 0.1 * _clip(float(features.get(key, 0.0))) * weights.get(key, 1.0) + return _sigmoid(score) + + +def _fitness(profile: dict[str, float], scenarios: Sequence[EvolutionScenario]) -> Fitness: + probabilities = [persona_probability(scenario.features, profile) for scenario in scenarios] + outcomes = [scenario.outcome for scenario in scenarios] + hit = sum( + 1 + for probability, outcome in zip(probabilities, outcomes) + if (probability >= 0.5) == bool(outcome) + ) / len(scenarios) + return Fitness(n=len(scenarios), brier=brier_score(probabilities, outcomes), hit_rate=hit) + + +def split_scenarios( + scenarios: Sequence[EvolutionScenario], *, heldout_fraction: float = 0.25 +) -> tuple[list[EvolutionScenario], list[EvolutionScenario]]: + if not 0.0 < heldout_fraction < 1.0: + raise ValueError("heldout_fraction must be in (0, 1)") + ordered = sorted(scenarios, key=lambda scenario: (scenario.as_of, scenario.id)) + if len(ordered) < 2: + raise ValueError("at least two scenarios are required") + validation_size = max(1, int(round(len(ordered) * heldout_fraction))) + validation_size = min(validation_size, len(ordered) - 1) + return ordered[:-validation_size], ordered[-validation_size:] + + +def _neutral_profile() -> dict[str, float]: + return {dimension: 0.5 for dimension in DIMENSIONS} + + +def _mutate( + profile: dict[str, float], rng: random.Random, rate: float, scale: float = 0.15 +) -> dict[str, float]: + child = dict(profile) + for dimension in DIMENSIONS: + if rng.random() < rate: + child[dimension] = _clip(child[dimension] + rng.uniform(-scale, scale)) + return child + + +def _crossover( + left: dict[str, float], right: dict[str, float], rng: random.Random +) -> dict[str, float]: + return { + dimension: left[dimension] if rng.random() < 0.5 else right[dimension] + for dimension in DIMENSIONS + } + + +def evolve( + scenarios: Sequence[EvolutionScenario], + *, + seed: int = 7, + generations: int = 20, + population_size: int = 24, + mutation_rate: float = 0.2, + elite_fraction: float = 0.1, + heldout_fraction: float = 0.25, + improvement_threshold: float = 0.0, + base_profile: Optional[dict[str, float]] = None, +) -> EvolutionResult: + """Deterministic evolutionary search with a held-out promotion gate. + + The search optimizes training Brier score only. A candidate is promoted only + when validation Brier improves by more than ``improvement_threshold`` over + the neutral baseline; otherwise the baseline persona is returned. + """ + + if generations < 1 or population_size < 2: + raise ValueError("generations >= 1 and population_size >= 2 are required") + if not 0.0 < elite_fraction < 1.0: + raise ValueError("elite_fraction must be in (0, 1)") + train, validation = split_scenarios(scenarios, heldout_fraction=heldout_fraction) + baseline_profile = dict(base_profile or _neutral_profile()) + for dimension in DIMENSIONS: + baseline_profile.setdefault(dimension, 0.5) + baseline_profile[dimension] = _clip(float(baseline_profile[dimension])) + baseline_validation = _fitness(baseline_profile, validation) + + rng = random.Random(seed) + population = [dict(baseline_profile)] + while len(population) < population_size: + population.append(_mutate(baseline_profile, rng, 1.0, scale=0.3)) + + history: list[Generation] = [] + elite_count = max(1, int(round(population_size * elite_fraction))) + for index in range(generations): + ranked = sorted( + population, + key=lambda profile: (_fitness(profile, train).brier, profile["contrarian"]), + ) + scores = [_fitness(profile, train) for profile in ranked] + history.append( + Generation( + index=index, + best_brier=scores[0].brier, + mean_brier=sum(score.brier for score in scores) / len(scores), + best_profile=dict(ranked[0]), + ) + ) + elites = [dict(profile) for profile in ranked[:elite_count]] + next_population = [dict(profile) for profile in elites] + while len(next_population) < population_size: + left = elites[rng.randrange(len(elites))] + right = elites[rng.randrange(len(elites))] + next_population.append( + _mutate(_crossover(left, right, rng), rng, mutation_rate) + ) + population = next_population + + best = min(population, key=lambda profile: _fitness(profile, train).brier) + validation_fitness = _fitness(best, validation) + improvement = baseline_validation.brier - validation_fitness.brier + promoted = improvement > improvement_threshold + chosen = best if promoted else baseline_profile + persona = build_persona(profile=chosen, name="Evolved" if promoted else "Baseline") + generation_count = len(history) + version = f"evolved-{seed}-{generation_count}" if promoted else "baseline" + persona_id = hashlib.sha256( + json.dumps( + {"profile": chosen, "seed": seed, "version": version}, + sort_keys=True, + separators=(",", ":"), + ).encode("utf-8") + ).hexdigest()[:32] + persona = persona.model_copy( + update={ + "id": persona_id, + "version": version, + "created_at": train[-1].resolved_at, + } + ) + reason = ( + f"validation Brier improved by {improvement:.4f} " + f"(threshold {improvement_threshold:.4f})" + if promoted + else f"held-out Brier did not improve by {improvement_threshold:.4f}; " + "baseline retained" + ) + return EvolutionResult( + seed=seed, + generations=tuple(history), + train=_fitness(chosen, train), + validation=_fitness(chosen, validation) if promoted else baseline_validation, + baseline_validation=baseline_validation, + promoted=promoted, + reason=reason, + persona=persona, + train_ids=tuple(scenario.id for scenario in train), + validation_ids=tuple(scenario.id for scenario in validation), + ) diff --git a/docs/ANALYSIS.md b/docs/ANALYSIS.md index 37293e8..540b8d1 100644 --- a/docs/ANALYSIS.md +++ b/docs/ANALYSIS.md @@ -49,6 +49,15 @@ feature_store.history("AAPL", "rsi_14") These models are part of `CONTRACT_MODELS` and the exported JSON Schema. +## Persona evolution + +`core/janus/persona/evolution.py` runs a deterministic evolutionary search over +the taste profile. Fitness is training Brier score; promotion requires a +held-out time split to improve by more than the configured threshold, otherwise +the baseline persona is retained. RNG, persona id, version, and created_at are +derived from the seed and chosen profile so a run is reproducible. This is a +safe local fallback for AgentDescent, not a claim of alpha. + ## Regime baseline `classify_regime` is a rule-based baseline: diff --git a/docs/BACKLOG.md b/docs/BACKLOG.md index f27cbdb..b38de54 100644 --- a/docs/BACKLOG.md +++ b/docs/BACKLOG.md @@ -7,7 +7,7 @@ criteria. ## How to read this -**Current status (2026-11-24):** JAN-001, JAN-002, JAN-003, JAN-005, JAN-007, +**Current status (2026-11-24):** JAN-001, JAN-002, JAN-003, JAN-005, JAN-007, JAN-039, JAN-008, JAN-009, JAN-010, JAN-015, JAN-016, JAN-019, JAN-023, JAN-024, JAN-025, JAN-027, JAN-028, JAN-031 (tracker #39 / JAN-074), JAN-033, JAN-034, JAN-035, JAN-037, JAN-040, JAN-041, @@ -25,7 +25,7 @@ DSH UI wiring and cron are deferred to v0.2. See `schemas/janus.schema.json`, `tests/test_debrief.py`, `tests/test_persona_weighting.py`, `tests/test_mcp_service.py`, `tests/test_beliefbench.py`, `tests/test_gdelt.py`, `tests/test_rss.py`, `tests/test_scheduler.py`, -`tests/test_quality.py`, and `tests/test_copy.py`. +`tests/test_quality.py`, `tests/test_persona_evolution.py`, and `tests/test_copy.py`. - **Milestones** are delivery windows, not promises: M0 foundation, M1 data and memory, M2 analysis, M3 forecast and review, M4 interface, M5 evaluation and diff --git a/tests/test_persona_evolution.py b/tests/test_persona_evolution.py new file mode 100644 index 0000000..dc55c52 --- /dev/null +++ b/tests/test_persona_evolution.py @@ -0,0 +1,95 @@ +from __future__ import annotations + +from datetime import datetime, timedelta, timezone + +import pytest + +from janus.persona.evolution import ( + EvolutionScenario, + evolve, + split_scenarios, +) + + +def _scenarios(count: int = 40) -> list[EvolutionScenario]: + start = datetime(2026, 1, 1, tzinfo=timezone.utc) + rows = [] + for index in range(count): + trend = 0.08 if index % 2 == 0 else -0.08 + rows.append( + EvolutionScenario( + id=f"s{index}", + as_of=start + timedelta(days=index), + resolved_at=start + timedelta(days=index + 30), + outcome=1.0 if trend > 0 else 0.0, + features={ + "rsi_14": 65.0 if trend > 0 else 35.0, + "return_21d": trend, + "breadth": 0.65 if trend > 0 else 0.35, + }, + ) + ) + return rows + + +def test_split_is_time_ordered_and_disjoint() -> None: + train, validation = split_scenarios(_scenarios(), heldout_fraction=0.25) + assert {scenario.id for scenario in train}.isdisjoint( + {scenario.id for scenario in validation} + ) + assert max(scenario.as_of for scenario in train) < min( + scenario.as_of for scenario in validation + ) + + +def test_evolution_is_reproducible_with_a_seed() -> None: + scenarios = _scenarios() + first = evolve(scenarios, seed=11, generations=6, population_size=12) + second = evolve(scenarios, seed=11, generations=6, population_size=12) + assert first.to_dict() == second.to_dict() + assert first.train_ids == second.train_ids + assert first.validation_ids == second.validation_ids + + +def test_promotion_gate_keeps_baseline_when_threshold_is_high() -> None: + result = evolve( + _scenarios(), + seed=5, + generations=6, + population_size=12, + improvement_threshold=10.0, + ) + assert result.promoted is False + assert result.persona.version == "baseline" + assert "baseline retained" in result.reason + + +def test_evolved_profile_is_bounded_and_versioned() -> None: + result = evolve( + _scenarios(), + seed=3, + generations=8, + population_size=16, + improvement_threshold=-10.0, + ) + assert result.promoted is True + assert result.persona.version.startswith("evolved-3-") + assert all(0.0 <= value <= 1.0 for value in result.persona.profile.values()) + assert result.validation.brier <= 1.0 + + +def test_invalid_inputs_are_rejected() -> None: + with pytest.raises(ValueError, match="at least two"): + split_scenarios(_scenarios(1)) + with pytest.raises(ValueError, match="heldout_fraction"): + split_scenarios(_scenarios(4), heldout_fraction=0.0) + with pytest.raises(ValueError, match="population_size"): + evolve(_scenarios(), population_size=1) + with pytest.raises(ValueError, match="timezone-aware"): + EvolutionScenario( + id="bad", + as_of=datetime(2026, 1, 1), + resolved_at=datetime(2026, 2, 1, tzinfo=timezone.utc), + outcome=1.0, + features={}, + )