Files
Cerbero-Bite/tests/unit/test_config_loader.py
T
root 1c6baaee83 feat(strategy): F+D+A miglioramenti — auto-pause, vol-harvest, delta dinamico
Implementa tre miglioramenti dalla roadmap di "📚 Strategia" + scaffolding del quarto.
Tutti retro-compatibili: i defaults della golden config disabilitano le nuove funzioni
così il comportamento attuale resta invariato finché l'operatore non le accende
esplicitamente in `strategy.yaml`. Il profilo `strategy.aggressiva.yaml` opta-in
agli incrementi più impattanti.

**F — Auto-pause su drawdown rolling (§7-bis)**

Circuit breaker sopra il kill-switch tecnico. Quando le ultime N posizioni
chiuse hanno cumulato perdite oltre `max_drawdown_pct × capitale_attuale`,
l'engine si auto-mette in pausa per `pause_weeks` settimane. Difende dai
regime change non rilevati dai filtri quant — se i filtri stanno fallendo
sistematicamente, fermarsi è meglio che continuare a sanguinare.

- `AutoPauseConfig` + `cfg.auto_pause` (top-level, default disabled).
- Migrazione SQL `0004_auto_pause.sql`: `system_state.auto_pause_until`
  e `auto_pause_reason` (NULL = engine attivo).
- Nuovo modulo puro `runtime/auto_pause.py` con `is_paused()` (gate I/O-free)
  e `evaluate_drawdown_breach()` (decide se armare).
- `entry_cycle` consulta `is_paused` subito dopo il kill-switch e arma
  la pausa dopo aver calcolato il capitale; nuovo status `_STATUS_AUTO_PAUSED`.
- Repository: `set_auto_pause`, `recent_closed_position_pnls_usd`.
- 12 test unitari: gate filter on/off, lookback insufficiente, soglia
  esatta, capitale non valido, transizioni paused → not-paused.

**D — Vol-collapse harvest (§7-bis)**

Exit opportunistica: quando DVOL è scesa di tot punti rispetto all'entry
e siamo in profit, esce subito. Edge IV-RV catturato, non c'è motivo di
tenere fino al profit-take. Nuovo `ExitAction = "CLOSE_VOL_HARVEST"`,
gate `exit.vol_harvest_dvol_decrease` (default 0 = off). 5 test unitari.

**A — Delta target dinamico per regime DVOL (§3.2)**

Strike short adattivo alla volatilità: a DVOL bassa il margine OTM è
generoso ⇒ posso prendere più premio (delta 0.15); a DVOL alta voglio
più safety distance (delta 0.10). Nuovo `DeltaByDvolBand` (step
function); quando `delta_by_dvol` è popolato, `_select_short` legge
la prima banda ascending con `dvol_now ≤ dvol_under`. Default vuoto =
comportamento invariato. `select_strikes` accetta nuovo kwarg
`dvol_now`, propagato da `entry_cycle`. 4 test unitari.

**C — Scaffolding profit-take graduale (§7.1bis)**

Schema in place ma runtime non ancora wirato. Aggiunge `PartialProfitLevel`
e `exit.profit_take_partial_levels` (default vuoto). Nuovo
`ExitAction = "CLOSE_PROFIT_PARTIAL"` nella Literal. La pipeline di
chiusure parziali nel runtime (entry_cycle / repository / clients)
richiede refactor del position model — lasciato come TODO per un PR
dedicato. La schema è pronta a recepire la config futura senza altri
breaking change.

**Profili aggiornati**

- `strategy.yaml` (golden, 1.2.0): tutto disabilitato by default.
- `strategy.conservativa.yaml` (1.2.0-cons): identico al golden.
- `strategy.aggressiva.yaml` (1.2.0-aggr): A+D+F enabled
  (delta_by_dvol 0.15/0.12/0.10, vol_harvest a 15 pt vol,
  auto_pause @ 15% DD su 5 trade, 2 settimane pausa).

Bump versioni 1.1.0 → 1.2.0, hash ricalcolati, test pinning aggiornato.

Suite: 426 passed.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-01 20:07:25 +00:00

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.2.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")