4ab7590745
Aggiunge il filtro a maggior impatto sul win-rate atteso: l'entry
salta se la IV implicita non sta pagando un margine misurabile sopra
la realized vol. La letteratura short-vol systematic indica che
l'edge sostenibile della strategia esiste solo quando IV30g − RV30g
supera una soglia di alcuni punti vol; senza questo gate il selling
vol nudo è strutturalmente neutro a win-rate 70-72%.
Implementazione end-to-end:
- `EntryConfig`: due nuovi campi `iv_minus_rv_min` e
`iv_minus_rv_filter_enabled`, con default `0` / `false` per non
rompere setup pre-calibrazione.
- `validate_entry`: §2.9 hard gate che blocca l'entry se
`iv_minus_rv < iv_minus_rv_min` (skip silenzioso quando il dato è
`None`, coerente con il pattern §2.8 dei filtri quant).
- `entry_cycle._gather_snapshot`: nuovo `_safe_iv_minus_rv` che
legge `deribit.realized_vol("ETH")["iv_minus_rv_30d"]` in
best-effort e lo propaga via `_MarketSnapshot.iv_minus_rv` →
`EntryContext.iv_minus_rv` → audit `inputs.snapshot.iv_minus_rv`.
- `tests/unit/test_entry_validator.py`: 5 nuovi casi (default
permissivo, gate sotto/sopra/uguale soglia, dato mancante).
- `tests/integration/test_entry_cycle.py`: stub `get_realized_vol`
nel mock helper così tutti gli scenari di happy/edge path
continuano a passare.
Configurazione di profili coerente con la disciplina:
- `strategy.yaml` (golden 1.1.0) e `strategy.conservativa.yaml`:
gate `enabled=false, min=0`. Manteniamo i lunedì pre-calibrazione
per accumulare dati sulla distribuzione di `iv_minus_rv`.
- `strategy.aggressiva.yaml` (1.1.0-aggressiva): gate
`enabled=true, min=3`. Coerente con la filosofia del profilo —
size più grande pretende win-rate più alto. La soglia 3 è
conservativa; la documentazione raccomanda 5 dopo 4-8 settimane di
calibrazione.
Doc + GUI:
- `docs/13-strategia-spiegata.md` §4-quater: spiega gate, parametri,
default per profilo, effetto atteso sul P/L (trade/anno scendono
ma E[trade] sale → APR cresce comunque), roadmap di hardening
(soglia adattiva, vol-of-vol guard, multi-asset).
- pagina `📚 Strategia`: la riga "IV − RV" passa da informativa a
pass/fail reale; mostra "filtro DISABILITATO (info-only)" quando
spento, ✅/❌ contro la soglia di config quando acceso.
Bump versioni e hash di tutti e tre i file YAML
(`config_version: 1.1.0`, hash ricalcolato). Test pinning aggiornato
(`test_load_repo_strategy_yaml`).
Suite: 410 passed.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
150 lines
5.0 KiB
Python
150 lines
5.0 KiB
Python
"""Tests for the YAML loader and hash verification."""
|
|
|
|
from __future__ import annotations
|
|
|
|
from decimal import Decimal
|
|
from pathlib import Path
|
|
|
|
import pytest
|
|
import yaml
|
|
|
|
from cerbero_bite.config.loader import (
|
|
ConfigHashError,
|
|
compute_config_hash,
|
|
load_strategy,
|
|
)
|
|
|
|
REPO_ROOT = Path(__file__).resolve().parents[2]
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Helpers
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
def _golden_yaml_skeleton(**overrides: object) -> dict[str, object]:
|
|
base = {
|
|
"config_version": "1.0.0-test",
|
|
"config_hash": "0" * 64,
|
|
"last_review": "2026-04-26",
|
|
"last_reviewer": "test",
|
|
}
|
|
base.update(overrides)
|
|
return base
|
|
|
|
|
|
def _write_with_correct_hash(path: Path, doc: dict[str, object]) -> None:
|
|
"""Write a YAML doc and patch ``config_hash`` to match the file body."""
|
|
text = yaml.safe_dump(doc, sort_keys=False)
|
|
path.write_text(text, encoding="utf-8")
|
|
new_hash = compute_config_hash(path.read_text(encoding="utf-8"))
|
|
doc = {**doc, "config_hash": new_hash}
|
|
text = yaml.safe_dump(doc, sort_keys=False)
|
|
path.write_text(text, encoding="utf-8")
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# compute_config_hash
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
def test_compute_hash_is_independent_of_recorded_hash_value(tmp_path: Path) -> None:
|
|
a = tmp_path / "a.yaml"
|
|
b = tmp_path / "b.yaml"
|
|
a.write_text(
|
|
'config_version: "1.0.0"\nconfig_hash: "aaa"\nfoo: 1\n', encoding="utf-8"
|
|
)
|
|
b.write_text(
|
|
'config_version: "1.0.0"\nconfig_hash: "bbb"\nfoo: 1\n', encoding="utf-8"
|
|
)
|
|
assert compute_config_hash(a.read_text()) == compute_config_hash(b.read_text())
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# load_strategy — happy path
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
def test_load_repo_strategy_yaml(tmp_path: Path) -> None:
|
|
"""The committed strategy.yaml validates with the recorded hash."""
|
|
result = load_strategy(REPO_ROOT / "strategy.yaml")
|
|
assert result.config.config_version == "1.1.0"
|
|
assert result.config.sizing.kelly_fraction == Decimal("0.13")
|
|
assert result.computed_hash == result.config.config_hash
|
|
|
|
|
|
def test_load_with_local_override_merges(tmp_path: Path) -> None:
|
|
main = tmp_path / "strategy.yaml"
|
|
_write_with_correct_hash(main, _golden_yaml_skeleton())
|
|
override = tmp_path / "strategy.local.yaml"
|
|
override.write_text(
|
|
yaml.safe_dump(
|
|
{"sizing": {"max_concurrent_positions": 0}},
|
|
sort_keys=False,
|
|
),
|
|
encoding="utf-8",
|
|
)
|
|
loaded = load_strategy(main)
|
|
assert loaded.config.sizing.max_concurrent_positions == 0
|
|
assert override in loaded.sources
|
|
|
|
|
|
def test_local_override_does_not_invalidate_main_hash(tmp_path: Path) -> None:
|
|
main = tmp_path / "strategy.yaml"
|
|
_write_with_correct_hash(main, _golden_yaml_skeleton())
|
|
(tmp_path / "strategy.local.yaml").write_text(
|
|
"sizing:\n kelly_fraction: '0.10'\n", encoding="utf-8"
|
|
)
|
|
loaded = load_strategy(main)
|
|
assert loaded.config.sizing.kelly_fraction == Decimal("0.10")
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# load_strategy — error paths
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
def test_load_with_mismatched_hash_raises(tmp_path: Path) -> None:
|
|
main = tmp_path / "strategy.yaml"
|
|
main.write_text(
|
|
yaml.safe_dump(_golden_yaml_skeleton(), sort_keys=False), encoding="utf-8"
|
|
)
|
|
with pytest.raises(ConfigHashError, match="config_hash mismatch"):
|
|
load_strategy(main)
|
|
|
|
|
|
def test_load_with_enforce_hash_false_skips_check(tmp_path: Path) -> None:
|
|
main = tmp_path / "strategy.yaml"
|
|
main.write_text(
|
|
yaml.safe_dump(_golden_yaml_skeleton(), sort_keys=False), encoding="utf-8"
|
|
)
|
|
loaded = load_strategy(main, enforce_hash=False)
|
|
assert loaded.config.config_hash == "0" * 64
|
|
|
|
|
|
def test_load_rejects_top_level_non_mapping(tmp_path: Path) -> None:
|
|
main = tmp_path / "strategy.yaml"
|
|
main.write_text("- a\n- b\n", encoding="utf-8")
|
|
with pytest.raises(ValueError, match="top-level mapping"):
|
|
load_strategy(main, enforce_hash=False)
|
|
|
|
|
|
def test_local_override_path_pointing_to_missing_file_is_ignored(
|
|
tmp_path: Path,
|
|
) -> None:
|
|
main = tmp_path / "strategy.yaml"
|
|
_write_with_correct_hash(main, _golden_yaml_skeleton())
|
|
loaded = load_strategy(
|
|
main, local_override_path=tmp_path / "nonexistent.yaml"
|
|
)
|
|
assert main in loaded.sources
|
|
assert len(loaded.sources) == 1
|
|
|
|
|
|
def test_empty_local_override_file_is_no_op(tmp_path: Path) -> None:
|
|
main = tmp_path / "strategy.yaml"
|
|
_write_with_correct_hash(main, _golden_yaml_skeleton())
|
|
(tmp_path / "strategy.local.yaml").write_text("", encoding="utf-8")
|
|
loaded = load_strategy(main)
|
|
assert loaded.config.sizing.kelly_fraction == Decimal("0.13")
|