import importlib.util import sys from pathlib import Path from types import SimpleNamespace import pytest def load_module(): path = Path(__file__).resolve().parents[1] / "scripts" / "search_eth_nextgen_micro_portfolio.py" spec = importlib.util.spec_from_file_location("search_eth_nextgen_micro_portfolio", path) assert spec is not None module = importlib.util.module_from_spec(spec) assert spec.loader is not None sys.modules[spec.name] = module spec.loader.exec_module(module) return module def test_trade_returns_apply_selected_cost_model(): module = load_module() result = SimpleNamespace( trades=[ { "return_pct": 1.0, "cost_weight": 0.5, "exit_time": "2026-04-30 12:00", } ] ) maker = module.nextgen_trade_returns(result, 1.0, 0.0021) taker = module.nextgen_trade_returns(result, 1.0, 0.0030) assert maker[0].value == pytest.approx(0.01 - 0.0021 * 0.5) assert taker[0].value == pytest.approx(0.01 - 0.0030 * 0.5) def test_monthly_stability_groups_by_name_and_cost_model(): module = load_module() pandas = pytest.importorskip("pandas") frame = pandas.DataFrame( [ {"cost_model": "maker_taker", "name": "a", "return": 0.02}, {"cost_model": "maker_taker", "name": "a", "return": -0.01}, {"cost_model": "taker_taker", "name": "a", "return": -0.03}, ] ) stability = module.monthly_stability(frame).sort_values(["cost_model", "name"]).reset_index(drop=True) assert stability.loc[0, "cost_model"] == "maker_taker" assert stability.loc[0, "months"] == 2 assert stability.loc[0, "positive_month_rate"] == pytest.approx(0.5) assert stability.loc[1, "cost_model"] == "taker_taker" assert stability.loc[1, "positive_month_rate"] == pytest.approx(0.0) def test_robust_survivors_requires_positive_returns_and_calmar_per_cost_model(): module = load_module() pandas = pytest.importorskip("pandas") rows = [] for cost_model, ret_3m in (("maker_taker", 0.04), ("taker_taker", -0.01)): for horizon, total_return in (("full", 0.30), ("3y", 0.20), ("1y", 0.10), ("6m", 0.08), ("3m", ret_3m)): rows.append( { "cost_model": cost_model, "name": "candidate", "horizon": horizon, "net_total_return": total_return, "net_calmar": 0.50, } ) survivors = module.robust_survivors(pandas.DataFrame(rows)) assert survivors["cost_model"].tolist() == ["maker_taker"]