Files
Anubis/tests/Anubis.Tests/TrialEngineTests.cs
T
Alby96andClaude Opus 5.5 f895c54076 Put a seam between the trial judge and the engines
The trial judge was tied to daily bars in many places, so the basket engine of
Phase 14 could not be judged by it. TrialRunner.Run now has an overload that
takes an IResearchFamily and an ITrialEngine (one variant, the window's
sessions, periods per year, data fingerprint, instruments, benchmark,
look-ahead check, limitations, expectations). The old signature is a wrapper
over DailyTrialEngine, which builds the options once and keeps every engine
call in today's order, so the golden reports stay byte for byte the same.

IResearchFamily is the base of IStrategyFamily without Create; ParameterGrid.Of,
StrategyParameters.Of and TrialRunner.Limitations take it. ParameterSpec.Choices
marks a choice axis: the plateau rule only averages variants with the same
value there, numeric axes keep one step. BacktestRun.Baskets and the report's
optional Baskets section (last field, left out when empty) carry units, levels,
legs and exit reason. No plan field changes: plan hashes recorded before the
seam are checked by a test.

refs #118

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-04 10:06:44 +01:00

362 lines
18 KiB
C#

using Anubis.Backtest;
using Anubis.Data;
using Anubis.Strategies;
using Anubis.Trading;
namespace Anubis.Tests;
/// <summary>
/// The seam between the trial judge and the engines (Phase 12, issue #118): the judge takes any <see cref="ITrialEngine"/>
/// and any <see cref="IResearchFamily"/>, the report gains an optional basket section, the plateau rule knows choice axes,
/// and nothing of what exists moves (the golden reports are in <see cref="TrialSeamTests"/>).
/// </summary>
[TestClass]
public sealed class TrialEngineTests
{
private static readonly DateTimeOffset Now = new(2027, 1, 5, 2, 10, 0, TimeSpan.Zero);
private static readonly Guid Id = new("0b7e2c1d-5a3f-4e8b-9c6d-2f1a0e9d8c7b");
private static readonly DateOnly First = new(2024, 1, 1);
[TestMethod]
[TestCategory(Category.Unit)]
public void AnEngineThatIsNotDailyIsJudgedWithItsOwnSessionsYearFingerprintInstrumentsBenchmarkAndLimits()
{
var engine = new StubEngine();
var (report, summary) = TrialRunner.Run(Id, StubPlan(), "stub-plan", StubFamily.Instance, engine, PriorTrials.None, Now);
Assert.AreEqual(StubFamily.FamilyId, report.Strategy);
Assert.AreEqual("Famiglia finta", report.StrategyName);
Assert.AreEqual("USD", report.Currency);
Assert.AreEqual("USD", summary.Currency);
Assert.AreEqual(StubEngine.Year, report.PeriodsPerYear);
Assert.AreEqual(StubEngine.SessionCount, report.Sessions);
Assert.AreEqual("stub-data", report.DataFingerprint);
CollectionAssert.AreEqual(engine.Instruments().ToList(), report.Instruments.ToList());
CollectionAssert.AreEqual(new[] { "Motore finto della prova." }, report.Limitations.ToList());
// The benchmark is the engine's own (here: stay flat), not buy and hold.
Assert.AreEqual(0d, report.Benchmark.TotalReturn);
Assert.IsTrue(report.Curve.All(p => p.Benchmark == StubEngine.Capital));
// Figures are annualised with the engine's periods per year.
var chosen = report.Variants.Single(v => v.Chosen).Parameters;
var expected = BacktestMetrics.Of(StubEngine.Build(StrategyParameters.Of(StubFamily.Instance, chosen), 1m, []), StubEngine.Year);
Assert.AreEqual(expected.Sharpe, report.Metrics.Sharpe);
Assert.AreEqual(expected.AnnualReturn, report.Metrics.AnnualReturn);
Assert.AreNotEqual(BacktestMetrics.Of(StubEngine.Build(StrategyParameters.Of(StubFamily.Instance, chosen), 1m, []), 365).Sharpe, report.Metrics.Sharpe);
// What the engine expects and its look-ahead check reach the report as they are.
Assert.AreEqual(7.5m, report.ExpectedSlippageBp);
CollectionAssert.AreEqual(new[] { -0.01, -0.02 }, report.ExpectedPathP5!.ToList());
Assert.AreEqual(42, report.LookAhead.Decisions);
Assert.IsTrue(report.LookAhead.Passed);
Assert.AreEqual(6, report.Variants.Count);
Assert.IsNull(report.Baskets);
}
[TestMethod]
[TestCategory(Category.Unit)]
public void TheJudgeCallsTheEngineInTheOrderOfToday()
{
var engine = new StubEngine();
var (report, _) = TrialRunner.Run(Id, StubPlan(), "stub-plan", StubFamily.Instance, engine, PriorTrials.None, Now);
var chosen = report.Variants.Single(v => v.Chosen).Parameters;
string[] expected =
[
"run a=1;kind=0 x1", "run a=1;kind=1 x1", "run a=2;kind=0 x1", "run a=2;kind=1 x1", "run a=3;kind=0 x1", "run a=3;kind=1 x1",
$"run {chosen} x2", $"run {chosen} x3", "benchmark", $"look_ahead {chosen} 6",
];
CollectionAssert.AreEqual(expected, engine.Calls);
}
[TestMethod]
[TestCategory(Category.Unit)]
public void AJudgedVariantOutsideTheGridRunsOnceMoreOnTheEngine()
{
var engine = new StubEngine();
var (report, _) = TrialRunner.Run(Id, StubPlan() with { Judged = "a=4;kind=1" }, "stub-plan", StubFamily.Instance, engine, PriorTrials.None, Now);
Assert.AreEqual("a=4;kind=1", report.Judged);
Assert.AreEqual("run a=4;kind=1 x1", engine.Calls[6]);
Assert.IsTrue(report.Variants[^1].OutsideGrid);
Assert.AreEqual(2, report.Limitations.Count);
}
[TestMethod]
[TestCategory(Category.Unit)]
public void TheReportHasNoBasketsKeyWhenTheRunHasNone()
{
var (report, _) = TrialRunner.Run(Id, StubPlan(), "stub-plan", StubFamily.Instance, new StubEngine(), PriorTrials.None, Now);
Assert.IsNull(report.Baskets);
Assert.IsFalse(report.ToJson().Contains("\"baskets\"", StringComparison.Ordinal));
}
[TestMethod]
[TestCategory(Category.Unit)]
public void TheReportCarriesTheBasketsOfTheRunWithUnitsLevelsLegsAndExitReasonAsItsLastSection()
{
var opened = new DateTimeOffset(2024, 3, 4, 14, 15, 0, TimeSpan.Zero);
BacktestBasket[] baskets =
[
new("EURUSD-USDCHF", opened, opened.AddHours(5), 1_000m, 3, ["EURUSD", "USDCHF"], "target", 12.5m),
new("AUDUSD", opened.AddDays(1), null, 2_000m, 1, ["AUDUSD"], null, -3.25m),
];
var (report, _) = TrialRunner.Run(Id, StubPlan(), "stub-plan", StubFamily.Instance, new StubEngine { Baskets = baskets }, PriorTrials.None, Now);
Assert.IsNotNull(report.Baskets);
Assert.AreEqual(2, report.Baskets.Count);
var first = report.Baskets[0];
Assert.AreEqual(new ReportBasket("EURUSD-USDCHF", opened, opened.AddHours(5), 1_000m, 3, first.Legs, "target", 12.5m), first);
CollectionAssert.AreEqual(new[] { "EURUSD", "USDCHF" }, first.Legs.ToList());
Assert.IsNull(report.Baskets[1].Closed);
Assert.IsNull(report.Baskets[1].ExitReason);
var json = report.ToJson();
StringAssert.Contains(json, "\"units\":1000");
StringAssert.Contains(json, "\"levels\":3");
StringAssert.Contains(json, "\"legs\":[\"EURUSD\",\"USDCHF\"]");
StringAssert.Contains(json, "\"exit_reason\":\"target\"");
Assert.IsTrue(json.IndexOf("\"baskets\":", StringComparison.Ordinal) > json.IndexOf("\"seconds\":", StringComparison.Ordinal), "The baskets come after every other field.");
Assert.IsTrue(json.IndexOf("\"baskets\":", StringComparison.Ordinal) > json.IndexOf("\"expected_slippage_bp\":", StringComparison.Ordinal));
Assert.IsTrue(json.EndsWith("]}", StringComparison.Ordinal));
var back = BacktestReport.FromJson(json);
Assert.AreEqual(2, back.Baskets!.Count);
CollectionAssert.AreEqual(new[] { "EURUSD", "USDCHF" }, back.Baskets[0].Legs.ToList());
Assert.AreEqual(json, back.ToJson());
}
[TestMethod]
[TestCategory(Category.Unit)]
public void TheReportKeepsOnlyTheLastBasketsUpToTheLimitOfTheTrades()
{
var opened = new DateTimeOffset(2024, 3, 4, 0, 0, 0, TimeSpan.Zero);
var baskets = Enumerable.Range(0, TrialRunner.MaxTrades + 5)
.Select(i => new BacktestBasket("EURUSD", opened.AddHours(i), opened.AddHours(i + 1), 1_000m, 1, ["EURUSD"], "target", i))
.ToArray();
var (report, _) = TrialRunner.Run(Id, StubPlan(), "stub-plan", StubFamily.Instance, new StubEngine { Baskets = baskets }, PriorTrials.None, Now);
Assert.AreEqual(TrialRunner.MaxTrades, report.Baskets!.Count);
Assert.AreEqual(5m, report.Baskets[0].Result);
Assert.AreEqual(TrialRunner.MaxTrades + 4m, report.Baskets[^1].Result);
}
[TestMethod]
[TestCategory(Category.Unit)]
public void TheDailyEngineThroughTheNewOverloadGivesTheReportOfTheOldOne()
{
var data = BacktestData.One(BacktestData.Btc(), BacktestData.Walk(400, 3, start: 40_000, drift: 0.001, volatility: 0.03, from: First));
var grid = new Dictionary<string, IReadOnlyList<decimal>> { ["fast"] = [5m, 10m], ["slow"] = [20m, 40m] };
var plan = Laboratory.BuildPlan(new TrialRequest(MovingAverageCrossFamily.FamilyId, TrialSources.Database, Venues.Okx, ["BTC-EUR"],
First.AddDays(60), First.AddDays(399), 10_000m, grid), Now).Plan;
var hash = TrialPlan.Hash(plan.ToJson());
var family = MovingAverageCrossFamily.Instance;
var engine = new DailyTrialEngine(plan, family, data);
Assert.AreEqual(data.Sessions.Count(d => d >= plan.Data.From && d <= plan.Data.To), engine.Sessions);
Assert.AreEqual(data.PeriodsPerYear, engine.PeriodsPerYear);
Assert.AreEqual(data.Currency, engine.Currency);
Assert.AreEqual(data.Fingerprint(), engine.Fingerprint());
CollectionAssert.AreEqual(TrialRunner.Limitations(plan, family, data).ToList(), engine.Limitations().ToList());
var old = TrialRunner.Run(Id, plan, hash, family, data, PriorTrials.None, Now);
var seam = TrialRunner.Run(Id, plan, hash, family, engine, PriorTrials.None, Now);
Assert.AreEqual((old.Report with { Seconds = 0 }).ToJson(), (seam.Report with { Seconds = 0 }).ToJson());
Assert.AreEqual(old.Summary.Chosen, seam.Summary.Chosen);
Assert.AreEqual(old.Summary.NetResult, seam.Summary.NetResult);
}
/// <summary>
/// The hashes of plans built the way the laboratory and the protocols build them, recorded on commit 88b2883 before the
/// seam: a plan written today has the same hash, so the trial ids derived from it and the recorded outcomes do not move.
/// </summary>
[TestMethod]
[TestCategory(Category.Golden)]
public void APlanBuiltTodayHasTheHashItHadBeforeTheSeam()
{
var expected = new Dictionary<string, string>
{
[StrategyNames.CryptoTrend] = "2a30b537ecf0d6a0d94794c5d9fe97695cc912d5a1ada6ca9c10382853d7b3cb",
["equity_momentum"] = "9555ef93f3d90ae54ede9068f4db7dc38697f283ac586de6dff324c3475f4cd7",
["equity_meanrev"] = "5b64b09419ba153703909c81b13b9934938d6f8ba1b984fc00330980ff0e082c",
[StrategyNames.StockAthBreakout] = "5bf77e99a0d2e4372002e9cc306cec84a98acee3804ace5dda8ab24ca90fb378",
[StrategyNames.CryptoRelativeMomentum] = "99a85eb937c80bbe14a5113973271fc73ca3f5f7ac966321bca3a9e44204985e",
[MovingAverageCrossFamily.FamilyId] = "952279ca4cd6193b08da61b96ecd12cac86c925a10c946099798dccb0c3326ca",
[BuyAndHoldFamily.FamilyId] = "8266b414ea78d9ad1317ce578f23e3def2bb37bcb28a6103fae1bab6bc082a06",
};
var written = new DateTimeOffset(2026, 11, 11, 9, 0, 0, TimeSpan.Zero);
Assert.AreEqual(expected.Count, StrategyCatalog.All.Count);
foreach (var family in StrategyCatalog.All)
{
var plan = Laboratory.BuildPlan(new TrialRequest(family.Id, TrialSources.Research, EuroHistory.Venue, ["BTCEUR", "ETHEUR"],
CryptoTrendProtocol.From, new DateOnly(2026, 10, 31), CryptoTrendProtocol.Capital), written).Plan;
Assert.AreEqual(expected[family.Id], TrialPlan.Hash(plan.ToJson()), family.Id);
}
}
[TestMethod]
[TestCategory(Category.Unit)]
public void ThePlateauRuleNeverTreatsTwoValuesOfAChoiceAxisAsNeighbours()
{
var variants = ParameterGrid.Of(StubFamily.Instance);
Assert.AreEqual(6, variants.Count);
Assert.IsTrue(variants.All(v => v.Choices is [false, true]));
// Grid order: a = 1, 2, 3 outside, kind = 0, 1 inside. Kind 0 is a valley on the numeric axis, kind 1 a flat hill.
double[] values = [3, 5, 0, 5, 3, 5];
var scores = Validation.PlateauScores(variants, values);
// Kind 1 is averaged only with kind 1: no score is dragged down by the other choice.
Assert.AreEqual(5d, scores[1]);
Assert.AreEqual(5d, scores[3]);
Assert.AreEqual(5d, scores[5]);
// The numeric axis still averages one step either side: (3 + 0) / 2 at the ends, min(0, 2) in the middle.
Assert.AreEqual(1.5, scores[0]);
Assert.AreEqual(0d, scores[2]);
Assert.AreEqual(1.5, scores[4]);
Assert.AreEqual(1, Validation.ChoosePlateau(variants, values));
// Without the choice mark the same grid mixes the two kinds, as the numeric rule always did.
var plain = variants.Select(v => v with { Choices = null }).ToList();
Assert.AreEqual(3.25, Validation.PlateauScores(plain, values)[1]);
}
[TestMethod]
[TestCategory(Category.Unit)]
public void AGridWithoutChoiceAxesMarksNoVariant()
{
Assert.IsTrue(ParameterGrid.Of(MovingAverageCrossFamily.Instance).All(v => v.Choices is null));
Assert.IsTrue(StrategyCatalog.All.SelectMany(f => f.Parameters).All(p => !p.Choices));
}
[TestMethod]
[TestCategory(Category.Unit)]
public void EveryStrategyFamilyIsAResearchFamilyAndTheCatalogStillKnowsWhoNeedsTheWholeHistory()
{
Assert.IsTrue(typeof(IResearchFamily).IsAssignableFrom(typeof(IStrategyFamily)));
foreach (var family in StrategyCatalog.All)
{
Assert.IsInstanceOfType<IResearchFamily>(family, family.Id);
}
Assert.IsTrue(StrategyCatalog.Find(StrategyNames.StockAthBreakout) is { NeedsFullHistory: true });
Assert.IsFalse(StrategyCatalog.Find(StrategyNames.CryptoTrend) is { NeedsFullHistory: true });
IResearchFamily research = StockAthBreakoutFamily.Instance;
Assert.IsTrue(research.NeedsFullHistory);
IResearchFamily cross = MovingAverageCrossFamily.Instance;
Assert.IsFalse(cross.Accepts(new StrategyParameters([KeyValuePair.Create("fast", 50m), KeyValuePair.Create("slow", 20m)])));
Assert.AreEqual("fast=20;slow=100", StrategyParameters.Of(cross, "fast=50;slow=20").ToString());
}
[TestMethod]
[TestCategory(Category.Unit)]
public void AResearchFamilyWithoutStrategiesHasItsGridAndItsParameters()
{
Assert.AreEqual("a=2;kind=1", StrategyParameters.Of(StubFamily.Instance, "a=2;kind=1").ToString());
Assert.AreEqual("a=2;kind=0", StrategyParameters.Of(StubFamily.Instance, null).ToString());
Assert.AreEqual(6, ParameterGrid.Of(StubFamily.Instance).Count);
Assert.IsFalse(typeof(IStrategyFamily).IsAssignableFrom(typeof(StubFamily)));
}
private static TrialPlan StubPlan() => new(
StubFamily.FamilyId,
StubFamily.Instance.Version,
new SortedDictionary<string, IReadOnlyList<decimal>>(StringComparer.Ordinal) { ["a"] = [1m, 2m, 3m], ["kind"] = [0m, 1m] },
new TrialData(TrialSources.Research, "dukascopy", ["EURUSD"], First, First.AddDays(StubEngine.Days - 1)),
StubEngine.Capital,
[1m, 2m, 3m],
TrialValidation.Default,
TrialThresholds.Default,
"stub",
Now);
/// <summary>A research family that cannot build a strategy: a numeric axis and a choice axis.</summary>
private sealed class StubFamily : IResearchFamily
{
public const string FamilyId = "stub_baskets";
public static StubFamily Instance { get; } = new();
public string Id => FamilyId;
public string Version => "1";
public string Name => "Famiglia finta";
public string Description => "Famiglia finta per provare il giunto del giudice.";
public IReadOnlyList<ParameterSpec> Parameters =>
[
new("a", "Numero", 2m, [1m, 2m, 3m], 1m, 9m, Whole: true),
new("kind", "Tipo", 0m, [0m, 1m], 0m, 1m, Whole: true) { Choices = true },
];
}
/// <summary>An engine that is not daily: it builds its runs by hand, records every call and has its own figures.</summary>
private sealed class StubEngine : ITrialEngine
{
public const int Days = 320;
public const int SessionCount = 7_680;
public const int Year = 6_048;
public const decimal Capital = 10_000m;
public List<string> Calls { get; } = [];
public IReadOnlyList<BacktestBasket> Baskets { get; init; } = [];
public string Currency => "USD";
public int PeriodsPerYear => Year;
public int Sessions => SessionCount;
public string Fingerprint() => "stub-data";
public IReadOnlyList<ReportInstrument> Instruments() => [new("EURUSD", "dukascopy", First, First.AddDays(Days - 1), SessionCount, 0, "file")];
public BacktestRun Run(StrategyParameters parameters, decimal costMultiplier = 1m)
{
Calls.Add(FormattableString.Invariant($"run {parameters} x{costMultiplier}"));
return Build(parameters, costMultiplier, Baskets);
}
public BacktestRun Benchmark()
{
Calls.Add("benchmark");
return new BacktestRun(Currency, Capital, [.. Enumerable.Range(0, Days).Select(i => new EquityPoint(First.AddDays(i), Capital, Capital, 0m))], [], [], [], []);
}
public LookAheadResult LookAhead(StrategyParameters parameters, int cuts)
{
Calls.Add(FormattableString.Invariant($"look_ahead {parameters} {cuts}"));
return new LookAheadResult([First.AddDays(100)], 42, []);
}
public IReadOnlyList<string> Limitations() => ["Motore finto della prova."];
public TrialExpectations Expected(BacktestRun run, double[] returns) => new(7.5m, [-0.01, -0.02]);
/// <summary>A noisy equity whose drift depends on the parameters; costs lower it a little each day.</summary>
public static BacktestRun Build(StrategyParameters parameters, decimal costMultiplier, IReadOnlyList<BacktestBasket> baskets)
{
var a = parameters.Whole("a");
var kind = parameters.Whole("kind");
var gen = new Gen((a * 10) + kind);
var drift = (0.0004 * a) - (0.0006 * kind);
var equity = new List<EquityPoint>();
var value = Capital;
for (var i = 0; i < Days; i++)
{
if (i > 0)
{
value *= 1m + (decimal)(drift + (0.01 * gen.Normal())) - (0.0001m * (costMultiplier - 1m));
value = Math.Round(value, 6);
}
equity.Add(new EquityPoint(First.AddDays(i), value, value, 0m));
}
return new BacktestRun("USD", Capital, equity, [], [], [], []) { Baskets = baskets };
}
}
}